Example usage for org.w3c.dom Document createTextNode

List of usage examples for org.w3c.dom Document createTextNode

Introduction

In this page you can find the example usage for org.w3c.dom Document createTextNode.

Prototype

public Text createTextNode(String data);

Source Link

Document

Creates a Text node given the specified string.

Usage

From source file:org.sakaiproject.signup.tool.entityproviders.SignupEntityProducer.java

@SuppressWarnings("unchecked")
@Override//from   w  ww .j  av  a 2 s .  c o  m
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments) {

    String currentUserId = getSakaiFacade().getCurrentUserId();
    StringBuilder results = new StringBuilder();

    results.append("archiving " + getLabel() + Entity.SEPARATOR + siteId + Entity.SEPARATOR
            + SiteService.MAIN_CONTAINER + ".\n");

    Element rootElement = doc.createElement(SignupMeetingService.class.getName());
    ((Element) stack.peek()).appendChild(rootElement); //<org.sakaiproject>
    stack.push(rootElement);

    List<SignupMeeting> allMeetings = getSignupMeetingService().getAllSignupMeetings(siteId, currentUserId);

    if (allMeetings.size() > 0) {
        Element meetingListElement = this.copyFileProcessor.toXml("meetingList", doc, stack); //<meetingList>

        //adds meetings
        for (int i = 0; allMeetings.size() > i; i++) {
            try {
                SignupMeeting meeting = allMeetings.get(i);

                Element meetingElement = this.copyFileProcessor.toXml("meeting", doc, stack); //<meeting>
                Element titleElement = this.copyFileProcessor.toXml("title", doc, stack); //<title>
                Element locElement = this.copyFileProcessor.toXml("location", doc, stack); //<location>
                Element descElement = this.copyFileProcessor.toXml("description", doc, stack); //<description>
                Element meetingTypeElement = this.copyFileProcessor.toXml("meetingType", doc, stack); //<meetingType>
                Element creatorIdElement = this.copyFileProcessor.toXml("creatorId", doc, stack); //<creatorId>

                titleElement.appendChild(doc.createTextNode(meeting.getTitle())); //title
                locElement.appendChild(doc.createTextNode(meeting.getLocation())); //location
                descElement.appendChild(doc.createTextNode(meeting.getDescription())); //description
                meetingTypeElement.appendChild(doc.createTextNode(meeting.getMeetingType())); //meetingType
                creatorIdElement.appendChild(doc.createTextNode(meeting.getCreatorUserId())); //creatorId

                meetingElement.appendChild(titleElement);
                meetingElement.appendChild(locElement);
                meetingElement.appendChild(descElement);
                meetingElement.appendChild(meetingTypeElement);
                meetingElement.appendChild(creatorIdElement);

                if (meeting.isRecurredMeeting()) {
                    Element recurElement = this.copyFileProcessor.toXml("recurrenceType", doc, stack); //<recurrenceType>
                    recurElement.appendChild(doc.createTextNode(meeting.getRepeatType())); //recurrence
                    meetingElement.appendChild(recurElement);
                }

                Element timeslotListElement = this.copyFileProcessor.toXml("timeslotList", doc, stack); //<timeslotList>
                meetingElement.appendChild(timeslotListElement);

                List<SignupTimeslot> timeslots = meeting.getSignupTimeSlots(); //get the timeslots

                //adds timeslots to timeslotList
                for (int j = 0; j < timeslots.size(); j++) {
                    SignupTimeslot timeslot = timeslots.get(j);
                    List<SignupAttendee> attendees = timeslot.getAttendees();

                    Element timeslotElement = CopyFileProcessor.timeslotToXml(timeslot, doc, stack); //<timeslot>
                    timeslotListElement.appendChild(timeslotElement);

                    if (attendees.size() > 0) {
                        Element attendeeListElement = this.copyFileProcessor.toXml("attendeeList", doc, stack); //<attendeeList>
                        timeslotElement.appendChild(attendeeListElement);

                        //adds attendees and attendeeIds
                        for (int q = 0; q < attendees.size(); q++) {
                            SignupAttendee attendee = (SignupAttendee) attendees.get(q);
                            Element attendeeElement = this.copyFileProcessor.toXml("attendee", doc, stack); //<attendee>
                            Element attendeeIdElement = this.copyFileProcessor.toXml("attendeeId", doc, stack); //<attendeeId>
                            Element attendeeSiteIdElement = this.copyFileProcessor.toXml("attendeeSiteId", doc,
                                    stack); //<attendeeSiteId>

                            attendeeIdElement.appendChild(doc.createTextNode(attendee.getAttendeeUserId()));
                            attendeeSiteIdElement.appendChild(doc.createTextNode(attendee.getSignupSiteId()));
                            attendeeElement.appendChild(attendeeIdElement);
                            attendeeElement.appendChild(attendeeSiteIdElement);
                            attendeeListElement.appendChild(attendeeElement);
                        } //attendee loop end
                    } //if any attendee end
                } //timeslot loop end

                //if there are any attachments
                if (meeting.hasSignupAttachments()) {
                    Element attachmentListElement = this.copyFileProcessor.toXml("attachmentList", doc, stack); //<attachmentList>
                    List<SignupAttachment> allAttachments = meeting.getSignupAttachments();
                    meetingElement.appendChild(attachmentListElement);

                    //adds attachments
                    for (int m = 0; m < allAttachments.size(); m++) {
                        SignupAttachment attachment = allAttachments.get(m);

                        Element attachmentElement = this.copyFileProcessor.toXml("attachment", doc, stack); //<attachment>
                        Element attachmentUrlElement = this.copyFileProcessor.toXml("attachmentUrl", doc,
                                stack); //<attachmentUrl>
                        Element attachmentName = this.copyFileProcessor.toXml("attachmentName", doc, stack); //<attachmentName>
                        attachmentUrlElement.appendChild(doc.createTextNode(attachment.getResourceId()));
                        attachmentName.appendChild(doc.createTextNode(attachment.getFilename()));
                        attachmentElement.appendChild(attachmentUrlElement);
                        attachmentElement.appendChild(attachmentName);
                        attachmentListElement.appendChild(attachmentElement);
                    }
                }

                List<SignupSite> allSitesInMeeting = meeting.getSignupSites();

                Element availableToElement = this.copyFileProcessor.toXml("availableTo", doc, stack); //<availableTo>
                Element siteListElement = this.copyFileProcessor.toXml("siteList", doc, stack); //<siteList>
                availableToElement.appendChild(siteListElement);
                meetingElement.appendChild(availableToElement);

                for (int n = 0; n < allSitesInMeeting.size(); n++) {
                    SignupSite site = allSitesInMeeting.get(n);

                    Element siteElement = this.copyFileProcessor.toXml("site", doc, stack); //<site>
                    Element siteIdElement = this.copyFileProcessor.toXml("siteId", doc, stack); //<siteId>
                    siteIdElement.appendChild(doc.createTextNode(site.getSiteId()));
                    siteElement.appendChild(siteIdElement);
                    siteListElement.appendChild(siteElement);

                    //if there are groups
                    if (site.getSignupGroups().size() > 0) {
                        List<SignupGroup> allGroupsInSite = site.getSignupGroups();
                        Element groupListElement = this.copyFileProcessor.toXml("groupList", doc, stack); //<groupList>
                        siteElement.appendChild(groupListElement);

                        //adds groups
                        for (int g = 0; g < allGroupsInSite.size(); g++) {
                            SignupGroup group = allGroupsInSite.get(g);

                            Element groupElement = this.copyFileProcessor.toXml("group", doc, stack); //<group>
                            Element groupIdElement = this.copyFileProcessor.toXml("groupId", doc, stack); //<groupId>

                            groupIdElement.appendChild(doc.createTextNode(group.getGroupId()));
                            groupElement.appendChild(groupIdElement);
                            groupListElement.appendChild(groupElement);
                        }
                    } //signupGroups if end
                } //allSites for-loop end

                //add meetings to root
                meetingListElement.appendChild(meetingElement);
                rootElement.appendChild(meetingListElement);

            } catch (Exception e) {
                log.warn(e.getMessage());
            }
        } //main for-loop end
    }
    stack.pop();
    return results.toString();
}

From source file:com.microsoft.windowsazure.management.websites.WebSpaceOperationsImpl.java

/**
* Creates a source control user with permissions to publish to this web
* space./*from   ww  w .j a v a 2 s  .c o m*/
*
* @param username Required. The user name.
* @param password Required. The user password.
* @param parameters Optional. Parameters supplied to the Create Publishing
* User operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The Create Publishing User operation response.
*/
@Override
public WebSpacesCreatePublishingUserResponse createPublishingUser(String username, String password,
        WebSpacesCreatePublishingUserParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (username == null) {
        throw new NullPointerException("username");
    }
    if (password == null) {
        throw new NullPointerException("password");
    }
    if (parameters != null) {
        if (parameters.getPublishingPassword() == null) {
            throw new NullPointerException("parameters.PublishingPassword");
        }
        if (parameters.getPublishingUserName() == null) {
            throw new NullPointerException("parameters.PublishingUserName");
        }
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("username", username);
        tracingParameters.put("password", password);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createPublishingUserAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/WebSpaces";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("properties=publishingCredentials");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2014-04-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    if (parameters != null) {
        Element userElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "User");
        requestDoc.appendChild(userElement);

        if (parameters.getName() != null) {
            Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Name");
            nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
            userElement.appendChild(nameElement);
        }

        Element publishingPasswordElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PublishingPassword");
        publishingPasswordElement.appendChild(requestDoc.createTextNode(parameters.getPublishingPassword()));
        userElement.appendChild(publishingPasswordElement);

        Element publishingUserNameElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PublishingUserName");
        publishingUserNameElement.appendChild(requestDoc.createTextNode(parameters.getPublishingUserName()));
        userElement.appendChild(publishingUserNameElement);
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        WebSpacesCreatePublishingUserResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebSpacesCreatePublishingUserResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element userElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "User");
            if (userElement2 != null) {
                Element nameElement2 = XmlUtility.getElementByTagNameNS(userElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement2 != null) {
                    String nameInstance;
                    nameInstance = nameElement2.getTextContent();
                    result.setName(nameInstance);
                }

                Element publishingPasswordElement2 = XmlUtility.getElementByTagNameNS(userElement2,
                        "http://schemas.microsoft.com/windowsazure", "PublishingPassword");
                if (publishingPasswordElement2 != null) {
                    String publishingPasswordInstance;
                    publishingPasswordInstance = publishingPasswordElement2.getTextContent();
                    result.setPublishingPassword(publishingPasswordInstance);
                }

                Element publishingUserNameElement2 = XmlUtility.getElementByTagNameNS(userElement2,
                        "http://schemas.microsoft.com/windowsazure", "PublishingUserName");
                if (publishingUserNameElement2 != null) {
                    String publishingUserNameInstance;
                    publishingUserNameInstance = publishingUserNameElement2.getTextContent();
                    result.setPublishingUserName(publishingUserNameInstance);
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.microsoft.windowsazure.management.network.ReservedIPOperationsImpl.java

/**
* The BeginAssociate begins to associate a Reserved IP with a service.
*
* @param reservedIpName Required. The name of the reserved IP.
* @param parameters Required. Parameters supplied to the Begin associating
* Reserved IP.//from w w w.  j a  va  2  s. c o m
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginAssociating(String reservedIpName,
        NetworkReservedIPMobilityParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (reservedIpName == null) {
        throw new NullPointerException("reservedIpName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("reservedIpName", reservedIpName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginAssociatingAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/networking/reservedips/";
    url = url + URLEncoder.encode(reservedIpName, "UTF-8");
    url = url + "/operations/associate";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2015-04-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element reservedIPAssociationElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "ReservedIPAssociation");
    requestDoc.appendChild(reservedIPAssociationElement);

    if (parameters.getServiceName() != null) {
        Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ServiceName");
        serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName()));
        reservedIPAssociationElement.appendChild(serviceNameElement);
    }

    if (parameters.getDeploymentName() != null) {
        Element deploymentNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "DeploymentName");
        deploymentNameElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentName()));
        reservedIPAssociationElement.appendChild(deploymentNameElement);
    }

    if (parameters.getVirtualIPName() != null) {
        Element virtualIPNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "VirtualIPName");
        virtualIPNameElement.appendChild(requestDoc.createTextNode(parameters.getVirtualIPName()));
        reservedIPAssociationElement.appendChild(virtualIPNameElement);
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.microsoft.windowsazure.management.network.ReservedIPOperationsImpl.java

/**
* The BeginDisassociate begins to disassociate a Reserved IP from a service.
*
* @param reservedIpName Required. The name of the reserved IP.
* @param parameters Required. Parameters supplied to the Begin
* disassociating Reserved IP./*from  w ww .j  ava2  s. c  om*/
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public OperationStatusResponse beginDisassociating(String reservedIpName,
        NetworkReservedIPMobilityParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (reservedIpName == null) {
        throw new NullPointerException("reservedIpName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("reservedIpName", reservedIpName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginDisassociatingAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/networking/reservedips/";
    url = url + URLEncoder.encode(reservedIpName, "UTF-8");
    url = url + "/operations/disassociate";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2015-04-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element reservedIPAssociationElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "ReservedIPAssociation");
    requestDoc.appendChild(reservedIPAssociationElement);

    if (parameters.getServiceName() != null) {
        Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ServiceName");
        serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName()));
        reservedIPAssociationElement.appendChild(serviceNameElement);
    }

    if (parameters.getDeploymentName() != null) {
        Element deploymentNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "DeploymentName");
        deploymentNameElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentName()));
        reservedIPAssociationElement.appendChild(deploymentNameElement);
    }

    if (parameters.getVirtualIPName() != null) {
        Element virtualIPNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "VirtualIPName");
        virtualIPNameElement.appendChild(requestDoc.createTextNode(parameters.getVirtualIPName()));
        reservedIPAssociationElement.appendChild(virtualIPNameElement);
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:de.betterform.xml.xforms.model.submission.Submission.java

private Map<String, Object> constructEventInfo(Map response) throws XFormsException {
    Map<String, Object> result = new HashMap<String, Object>();

    final Document ownerDocument = this.element.getOwnerDocument();
    final DocumentWrapper wrapper = new DocumentWrapper(ownerDocument,
            this.container.getProcessor().getBaseURI(), this.container.getConfiguration());

    List<Item> headerItems = new ArrayList<Item>(response.size());
    for (Iterator<Map.Entry<String, String>> it = response.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> entry = it.next();
        if (!XFormsProcessor.SUBMISSION_RESPONSE_STREAM.equals(entry.getKey())
                && !XFormsProcessor.SUBMISSION_RESPONSE_DOCUMENT.equals(entry.getKey())
                && !RESPONSE_STATUS_CODE.equals(entry.getKey())
                && !RESPONSE_REASON_PHRASE.equals(entry.getKey())) {

            Element headerEl = ownerDocument.createElement("header");

            Element nameEl = ownerDocument.createElement("name");
            nameEl.appendChild(ownerDocument.createTextNode(entry.getKey()));
            headerEl.appendChild(nameEl);

            Element valueEl = ownerDocument.createElement("value");
            valueEl.appendChild(ownerDocument.createTextNode(entry.getValue()));
            headerEl.appendChild(valueEl);

            headerItems.add(wrapper.wrap(headerEl));
        }// w  w  w  .  ja va 2  s  .c o m
    }
    result.put(RESOURCE_URI, getResourceURI());
    result.put(RESPONSE_STATUS_CODE,
            (response.containsKey(RESPONSE_STATUS_CODE)
                    ? Double.parseDouble((String) response.get(RESPONSE_STATUS_CODE))
                    : Double.valueOf(200d))); //TODO get real response code
    result.put(RESPONSE_HEADERS, headerItems);
    result.put(RESPONSE_REASON_PHRASE,
            (response.containsKey(RESPONSE_REASON_PHRASE) ? (String) response.get(RESPONSE_REASON_PHRASE)
                    : "")); //TODO get real response reason phrase

    return result;
}

From source file:com.microsoft.windowsazure.management.sql.DatabaseCopyOperationsImpl.java

/**
* Updates a SQL Server database copy.//from  w  w w  .j  av  a  2s  . c  om
*
* @param serverName Required. The name of the source or destination SQL
* Server instance.
* @param databaseName Required. The name of the database.
* @param databaseCopyName Required. The unique identifier for the database
* copy to update.
* @param parameters Required. The additional parameters for the update
* database copy operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Represents a response to the update request.
*/
@Override
public DatabaseCopyUpdateResponse update(String serverName, String databaseName, String databaseCopyName,
        DatabaseCopyUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (databaseCopyName == null) {
        throw new NullPointerException("databaseCopyName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serverName", serverName);
        tracingParameters.put("databaseName", databaseName);
        tracingParameters.put("databaseCopyName", databaseCopyName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/databasecopies/";
    url = url + URLEncoder.encode(databaseCopyName, "UTF-8");
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2012-03-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServiceResource");
    requestDoc.appendChild(serviceResourceElement);

    if (parameters.isForcedTerminate() != null) {
        Element isForcedTerminateElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "IsForcedTerminate");
        isForcedTerminateElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isForcedTerminate()).toLowerCase()));
        serviceResourceElement.appendChild(isForcedTerminateElement);
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        DatabaseCopyUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseCopyUpdateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement2 != null) {
                DatabaseCopy serviceResourceInstance = new DatabaseCopy();
                result.setDatabaseCopy(serviceResourceInstance);

                Element sourceServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceServerName");
                if (sourceServerNameElement != null) {
                    String sourceServerNameInstance;
                    sourceServerNameInstance = sourceServerNameElement.getTextContent();
                    serviceResourceInstance.setSourceServerName(sourceServerNameInstance);
                }

                Element sourceDatabaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName");
                if (sourceDatabaseNameElement != null) {
                    String sourceDatabaseNameInstance;
                    sourceDatabaseNameInstance = sourceDatabaseNameElement.getTextContent();
                    serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance);
                }

                Element destinationServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "DestinationServerName");
                if (destinationServerNameElement != null) {
                    String destinationServerNameInstance;
                    destinationServerNameInstance = destinationServerNameElement.getTextContent();
                    serviceResourceInstance.setDestinationServerName(destinationServerNameInstance);
                }

                Element destinationDatabaseNameElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "DestinationDatabaseName");
                if (destinationDatabaseNameElement != null) {
                    String destinationDatabaseNameInstance;
                    destinationDatabaseNameInstance = destinationDatabaseNameElement.getTextContent();
                    serviceResourceInstance.setDestinationDatabaseName(destinationDatabaseNameInstance);
                }

                Element isContinuousElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsContinuous");
                if (isContinuousElement != null) {
                    boolean isContinuousInstance;
                    isContinuousInstance = DatatypeConverter
                            .parseBoolean(isContinuousElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsContinuous(isContinuousInstance);
                }

                Element replicationStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ReplicationState");
                if (replicationStateElement != null) {
                    byte replicationStateInstance;
                    replicationStateInstance = DatatypeConverter
                            .parseByte(replicationStateElement.getTextContent());
                    serviceResourceInstance.setReplicationState(replicationStateInstance);
                }

                Element replicationStateDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ReplicationStateDescription");
                if (replicationStateDescriptionElement != null) {
                    String replicationStateDescriptionInstance;
                    replicationStateDescriptionInstance = replicationStateDescriptionElement.getTextContent();
                    serviceResourceInstance.setReplicationStateDescription(replicationStateDescriptionInstance);
                }

                Element localDatabaseIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "LocalDatabaseId");
                if (localDatabaseIdElement != null) {
                    int localDatabaseIdInstance;
                    localDatabaseIdInstance = DatatypeConverter
                            .parseInt(localDatabaseIdElement.getTextContent());
                    serviceResourceInstance.setLocalDatabaseId(localDatabaseIdInstance);
                }

                Element isLocalDatabaseReplicationTargetElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "IsLocalDatabaseReplicationTarget");
                if (isLocalDatabaseReplicationTargetElement != null) {
                    boolean isLocalDatabaseReplicationTargetInstance;
                    isLocalDatabaseReplicationTargetInstance = DatatypeConverter.parseBoolean(
                            isLocalDatabaseReplicationTargetElement.getTextContent().toLowerCase());
                    serviceResourceInstance
                            .setIsLocalDatabaseReplicationTarget(isLocalDatabaseReplicationTargetInstance);
                }

                Element isInterlinkConnectedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsInterlinkConnected");
                if (isInterlinkConnectedElement != null) {
                    boolean isInterlinkConnectedInstance;
                    isInterlinkConnectedInstance = DatatypeConverter
                            .parseBoolean(isInterlinkConnectedElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsInterlinkConnected(isInterlinkConnectedInstance);
                }

                Element startDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartDate");
                if (startDateElement != null) {
                    String startDateInstance;
                    startDateInstance = startDateElement.getTextContent();
                    serviceResourceInstance.setStartDate(startDateInstance);
                }

                Element modifyDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ModifyDate");
                if (modifyDateElement != null) {
                    String modifyDateInstance;
                    modifyDateInstance = modifyDateElement.getTextContent();
                    serviceResourceInstance.setModifyDate(modifyDateInstance);
                }

                Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "PercentComplete");
                if (percentCompleteElement != null) {
                    float percentCompleteInstance;
                    percentCompleteInstance = DatatypeConverter
                            .parseFloat(percentCompleteElement.getTextContent());
                    serviceResourceInstance.setPercentComplete(percentCompleteInstance);
                }

                Element isOfflineSecondaryElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsOfflineSecondary");
                if (isOfflineSecondaryElement != null) {
                    boolean isOfflineSecondaryInstance;
                    isOfflineSecondaryInstance = DatatypeConverter
                            .parseBoolean(isOfflineSecondaryElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsOfflineSecondary(isOfflineSecondaryInstance);
                }

                Element isTerminationAllowedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsTerminationAllowed");
                if (isTerminationAllowedElement != null) {
                    boolean isTerminationAllowedInstance;
                    isTerminationAllowedInstance = DatatypeConverter
                            .parseBoolean(isTerminationAllowedElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsTerminationAllowed(isTerminationAllowedInstance);
                }

                Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement != null) {
                    String nameInstance;
                    nameInstance = nameElement.getTextContent();
                    serviceResourceInstance.setName(nameInstance);
                }

                Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Type");
                if (typeElement != null) {
                    String typeInstance;
                    typeInstance = typeElement.getTextContent();
                    serviceResourceInstance.setType(typeInstance);
                }

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    serviceResourceInstance.setState(stateInstance);
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:ai.aitia.meme.paramsweep.intellisweepPlugin.JgapGAPlugin.java

private void saveSelectors(final Element gaSettingsElement) {
    final Document document = gaSettingsElement.getOwnerDocument();

    final Element selectorsElement = document.createElement(SELECTORS);
    gaSettingsElement.appendChild(selectorsElement);

    for (final IGASelectorConfigurator selectorOperator : selectedSelectionOperators) {
        final Element selectorElement = document.createElement(SELECTOR);
        selectorsElement.appendChild(selectorElement);

        selectorElement.setAttribute(WizardSettingsManager.TYPE, selectorOperator.getName());

        for (final Entry<String, String> entry : selectorOperator.getConfiguration().entrySet()) {
            final Element propertyElement = document.createElement(PROPERTY);
            propertyElement.setAttribute(KEY, entry.getKey());
            propertyElement.appendChild(document.createTextNode(entry.getValue()));
            selectorElement.appendChild(propertyElement);
        }/*from  ww  w . j a v  a  2  s  .c o  m*/
    }
}

From source file:act.installer.pubchem.PubchemParser.java

/**
 * Incrementally parses a stream of XML events from a PubChem file, extracting the next available PC-Compound entry
 * as a Chemical object.//from w ww  . j  a  va2s  .  c o  m
 * @param eventReader The xml event reader we are parsing the XML from
 * @return The constructed chemical
 * @throws XMLStreamException
 * @throws XPathExpressionException
 */
public Chemical extractNextChemicalFromXMLStream(XMLEventReader eventReader)
        throws XMLStreamException, JaxenException {
    Document bufferDoc = null;
    Element currentElement = null;
    StringBuilder textBuffer = null;
    /* With help from
     * http://stackoverflow.com/questions/7998733/loading-local-chunks-in-dom-while-parsing-a-large-xml-file-in-sax-java
     */
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();

        switch (event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
            String eventName = event.asStartElement().getName().getLocalPart();
            if (COMPOUND_DOC_TAG.equals(eventName)) {
                // Create a new document if we've found the start of a compound object.
                bufferDoc = documentBuilder.newDocument();
                currentElement = bufferDoc.createElement(eventName);
                bufferDoc.appendChild(currentElement);
            } else if (currentElement != null) { // Wait until we've found a compound entry to start slurping up data.
                // Create a new child element and push down the current pointer when we find a new node.
                Element newElement = bufferDoc.createElement(eventName);
                currentElement.appendChild(newElement);
                currentElement = newElement;
            } // If we aren't in a PC-Compound tree, we just let the elements pass by.
            break;

        case XMLStreamConstants.CHARACTERS:
            if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree.
                continue;
            }

            Characters chars = event.asCharacters();
            // Ignore only whitespace strings, which just inflate the size of the DOM.  Text coalescing makes this safe.
            if (chars.isWhiteSpace()) {
                continue;
            }

            // Rely on the XMLEventStream to coalesce consecutive text events.
            Text textNode = bufferDoc.createTextNode(chars.getData());
            currentElement.appendChild(textNode);
            break;

        case XMLStreamConstants.END_ELEMENT:
            if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree.
                continue;
            }

            eventName = event.asEndElement().getName().getLocalPart();
            Node parentNode = currentElement.getParentNode();
            if (parentNode instanceof Element) {
                currentElement = (Element) parentNode;
            } else if (parentNode instanceof Document && eventName.equals(COMPOUND_DOC_TAG)) {
                // We're back at the top of the node stack!  Convert the buffered document into a Chemical.
                PubchemEntry entry = extractPCCompoundFeatures(bufferDoc);
                if (entry != null) {
                    return entry.asChemical();
                } else {
                    // Skip this entry if we can't process it correctly by resetting the world and continuing on.
                    bufferDoc = null;
                    currentElement = null;
                }
            } else {
                // This should not happen, but is here as a sanity check.
                throw new RuntimeException(String.format("Parent of XML element %s is of type %d, not Element",
                        currentElement.getTagName(), parentNode.getNodeType()));
            }
            break;

        // TODO: do we care about attributes or other XML structures?
        }
    }

    // Return null when we run out of chemicals, just like readLine().
    return null;
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public Element createBasicProcessNode(Document doc, String className, String operation, String oppSuffix,
        String oppPrefix) {/*  ww w. j  a va 2  s  .co  m*/
    Element process = doc.createElement("process");
    process.setAttribute("id", className + oppSuffix);
    process.setAttribute("init", oppPrefix + className);

    Element vars = doc.createElement("vars");

    Element in_var = doc.createElement("in-var");
    in_var.setAttribute("name", "moduleObj");
    in_var.setAttribute("module", className);
    Element local_var = doc.createElement("local-var");
    local_var.setAttribute("name", "retobj");
    local_var.setAttribute("module", "string");
    vars.appendChild(in_var);
    vars.appendChild(local_var);
    process.appendChild(vars);
    Element out_var = doc.createElement("out-var");
    out_var.setAttribute("name", "res");
    process.appendChild(out_var);
    Element node_list = doc.createElement("node-list");
    Element node = doc.createElement("node");
    node.setAttribute("id", oppPrefix + className);
    node.setAttribute("invoke", operation);
    Element output = doc.createElement("output");
    output.appendChild(doc.createTextNode("retObj"));
    Element inputs = doc.createElement("inputs");
    Element var = doc.createElement("var");
    var.setAttribute("name", "moduleObj");
    var.appendChild(doc.createTextNode("moduleObj"));
    inputs.appendChild(var);
    node.appendChild(output);
    node.appendChild(inputs);
    node_list.appendChild(node);

    process.appendChild(node_list);
    return process;
}

From source file:ai.aitia.meme.paramsweep.intellisweepPlugin.JgapGAPlugin.java

private void saveOperators(final Element gaSettingsElement) {
    final Document document = gaSettingsElement.getOwnerDocument();

    final Element geneticOperatorsElement = document.createElement(GENETIC_OPERATORS);
    gaSettingsElement.appendChild(geneticOperatorsElement);

    for (final IGAOperatorConfigurator geneticOperator : selectedGeneticOperators) {
        final Element operatorElement = document.createElement(GENETIC_OPERATOR);
        geneticOperatorsElement.appendChild(operatorElement);

        operatorElement.setAttribute(WizardSettingsManager.TYPE, geneticOperator.getName());

        for (final Entry<String, String> entry : geneticOperator.getConfiguration().entrySet()) {
            final Element propertyElement = document.createElement(PROPERTY);
            propertyElement.setAttribute(KEY, entry.getKey());
            propertyElement.appendChild(document.createTextNode(entry.getValue()));
            operatorElement.appendChild(propertyElement);
        }//from   w  w w.j av a2  s. c om
    }
}