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:de.tudarmstadt.ukp.dkpro.core.io.mmax2.MMAXWriter.java

public void registerMarkableLevel(String levelname, String schemeFilename, String customizationFilename)
        throws MMAXWriterException {

    Document compath = loadXML(commonPathsFile);

    Element annotations = (Element) compath.getElementsByTagName("annotations").item(0);
    NodeList annos = annotations.getElementsByTagName("level");
    boolean found = false;
    for (int j = 0; j < annos.getLength(); j++) {
        if (annos.item(j).getAttributes().getNamedItem("name").getTextContent().equals(levelname)) {
            found = true;//from   www.ja  v a  2s .  com
            System.err.println("Level " + levelname + " already exists.");
            break;
        }
    }

    // if the level is not already present in the commons_path file, add it
    if (!found) {
        Element anno = compath.createElement("level");
        anno.setAttribute("name", levelname);
        anno.setAttribute("schemefile", schemeFilename);
        anno.setAttribute("customization_file", customizationFilename);
        anno.appendChild(compath.createTextNode("$_" + levelname + ".xml"));
        annotations.appendChild(anno);
    }

    saveXML(compath, commonPathsFile, null, null);
}

From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient.java

public Document buildGetIdentityLinkRequest(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname,
        String PEPSDateOfBirth, String signature, String representative, String represented,
        String mandateContent) throws SZRGWClientException {

    String SZRGW_NS = "http://reference.e-government.gv.at/namespace/szrgw/20070807#";
    try {/*  ww  w .j a  va2 s . c  o  m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();

        Element getIdentityLink = doc.createElementNS(SZRGW_NS, "szrgw:GetIdentityLinkRequest");
        getIdentityLink.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:szrgw", SZRGW_NS);
        doc.appendChild(getIdentityLink);

        if ((PEPSIdentifier != null) || (PEPSFirstname != null) || (PEPSFamilyname != null)
                || (PEPSDateOfBirth != null)) {

            Element pepsDataElem = doc.createElementNS(SZRGW_NS, "szrgw:PEPSData");
            getIdentityLink.appendChild(pepsDataElem);

            if (PEPSIdentifier != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Identifier");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSIdentifier);
                elem.appendChild(text);
            }
            if (PEPSFirstname != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Firstname");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSFirstname);
                elem.appendChild(text);
            }

            if (PEPSFamilyname != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Familyname");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSFamilyname);
                elem.appendChild(text);
            }

            if (PEPSDateOfBirth != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:DateOfBirth");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(PEPSDateOfBirth);
                elem.appendChild(text);
            }

            if (representative != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Representative");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(representative);
                elem.appendChild(text);
            }

            if (represented != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Represented");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(represented);
                elem.appendChild(text);
            }

            if (mandateContent != null) {
                Element elem = doc.createElementNS(SZRGW_NS, "szrgw:MandateContent");
                pepsDataElem.appendChild(elem);
                Text text = doc.createTextNode(mandateContent);
                elem.appendChild(text);
            }
        }

        if (signature == null)
            throw new SZRGWClientException("Signature element must not be null!");
        else {
            Element sig = doc.createElementNS(SZRGW_NS, "szrgw:Signature");
            Element base64content = doc.createElementNS(SZRGW_NS, "szrgw:Base64Content");
            sig.appendChild(base64content);
            getIdentityLink.appendChild(sig);
            Text text = doc.createTextNode(signature);
            base64content.appendChild(text);
        }

        if (representative != null && represented != null && mandateContent != null) {
            Element mis = doc.createElementNS(SZRGW_NS, "szrgw:MIS");
            Element filters = doc.createElementNS(SZRGW_NS, "szrgw:Filters");
            mis.appendChild(filters);
            Element target = doc.createElementNS(SZRGW_NS, "szrgw:Target");
            mis.appendChild(target);
            Element friendlyName = doc.createElementNS(SZRGW_NS, "szrgw:OAFriendlyName");
            mis.appendChild(friendlyName);
            getIdentityLink.appendChild(mis);

            //            TODO fetch data from oa params
            //             String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID);
            //             moasessionid = StringEscapeUtils.escapeHtml(moasessionid);
            //              AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moasessionid);
            //             OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix());
            //             if (oaParam == null)
            //                   throw new AuthenticationException("auth.00", new Object[] { moasession.getPublicOAURLPrefix() });
            //              Text text = doc.createTextNode(oaParam.getFriendlyName());
        }

        return doc;
    } catch (ParserConfigurationException e) {
        throw new SZRGWClientException(e);
    } /*catch (CertificateEncodingException e) {
       throw new SZRGWClientException(e);
      }*/

}

From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertyDeserializer.java

@Override
protected JSONProperty doDeserializeV3(final JsonParser parser, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    final JSONProperty property = new JSONProperty();

    if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
        property.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
        tree.remove(ODataConstants.JSON_METADATA);
    }//from   ww w.  j av  a  2 s .c  o  m

    try {
        final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = builder.newDocument();

        Element content = document.createElement(ODataConstants.ELEM_PROPERTY);

        if (property.getMetadata() != null) {
            final String metadataURI = property.getMetadata().toASCIIString();
            final int dashIdx = metadataURI.lastIndexOf('#');
            if (dashIdx != -1) {
                content.setAttribute(ODataConstants.ATTR_M_TYPE, metadataURI.substring(dashIdx + 1));
            }
        }

        JsonNode subtree = null;
        if (tree.has(ODataConstants.JSON_VALUE)) {
            if (tree.has(ODataConstants.JSON_TYPE)
                    && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {

                content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(ODataConstants.JSON_TYPE).asText());
            }

            final JsonNode value = tree.get(ODataConstants.JSON_VALUE);
            if (value.isValueNode()) {
                content.appendChild(document.createTextNode(value.asText()));
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                subtree = tree.objectNode();
                ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE));
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
            } else {
                subtree = tree.get(ODataConstants.JSON_VALUE);
            }
        } else {
            subtree = tree;
        }

        if (subtree != null) {
            DOMTreeUtilsV3.buildSubtree(content, subtree);
        }

        final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE);
        if (children.size() == 1) {
            final Element value = (Element) children.iterator().next();
            if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) {
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    value.setAttribute(ODataConstants.ATTR_M_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
                content = value;
            }
        }

        property.setContent(content);
    } catch (ParserConfigurationException e) {
        throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e);
    }

    return property;
}

From source file:com.sms.server.service.AdaptiveStreamingService.java

public Document generateDASHPlaylist(long id, String baseUrl) {

    Job job = jobDao.getJobByID(id);/*from   ww w .  j a  va 2 s .com*/

    if (job == null) {
        return null;
    }

    MediaElement mediaElement = mediaDao.getMediaElementByID(job.getMediaElement());

    if (mediaElement == null) {
        return null;
    }

    AdaptiveStreamingProfile profile = getProfileByID(id);

    if (profile == null) {
        LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME,
                "Unable to get transcode profile to generate manifest for job " + id, null);
        return null;
    }

    // Transcode Parameters
    Dimension resolution = transcodeService.getVideoResolution(profile.getVideoQuality(), mediaElement);
    String codec;
    String mimeType;

    switch (profile.getType()) {
    case StreamType.DASH:
        codec = "avc1";
        mimeType = "video/MP2T";
        break;

    case StreamType.DASH_MP4:
        codec = "avc1";
        mimeType = "video/mp4";
        break;

    case StreamType.DASH_WEBM:
        codec = "vp8";
        mimeType = "video/webm";
        break;

    default:
        return null;
    }

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // Root MPD Element
        Document mpd = docBuilder.newDocument();
        Element root = mpd.createElement("MPD");
        root.setAttribute("xmnls", "urn:mpeg:dash:schema:mpd:2011");
        root.setAttribute("profiles", "urn:mpeg:dash:profile:isoff-on-demand:2011");
        root.setAttribute("type", "static");
        root.setAttribute("mediaPresentationDuration", "PT" + mediaElement.getDuration() + "S");
        root.setAttribute("minBufferTime", "PT2.0S");
        mpd.appendChild(root);

        // Program Information
        Element programInformation = mpd.createElement("ProgramInformation");
        root.appendChild(programInformation);

        // Title
        Element title = mpd.createElement("Title");
        title.appendChild(mpd.createTextNode(mediaElement.getTitle()));
        programInformation.appendChild(title);

        // Period
        Element period = mpd.createElement("Period");
        period.setAttribute("duration", "PT" + mediaElement.getDuration() + "S");
        period.setAttribute("start", "PT0S");
        root.appendChild(period);

        // Adaptation Set
        Element adaptationSet = mpd.createElement("AdaptationSet");
        adaptationSet.setAttribute("bitstreamSwitching", "false");
        period.appendChild(adaptationSet);

        // Representation
        Element representation = mpd.createElement("Representation");
        representation.setAttribute("id", "1");
        representation.setAttribute("codecs", codec);
        representation.setAttribute("mimeType", mimeType);
        representation.setAttribute("width", String.valueOf(resolution.width));
        representation.setAttribute("height", String.valueOf(resolution.height));
        adaptationSet.appendChild(representation);

        // Segment List
        Element segmentList = mpd.createElement("SegmentList");
        segmentList.setAttribute("timescale", "1000");
        segmentList.setAttribute("duration", Integer.toString(DASHTranscode.DEFAULT_SEGMENT_DURATION * 1000));
        representation.appendChild(segmentList);

        // Initialisation
        Element initialisation = mpd.createElement("Initialization");
        initialisation.setAttribute("sourceURL", createDASHSegmentUrl(baseUrl, job.getID(), 0));
        segmentList.appendChild(initialisation);

        // Segment URLs
        for (int i = 1; i < (mediaElement.getDuration() / DASHTranscode.DEFAULT_SEGMENT_DURATION); i++) {
            Element segmentUrl = mpd.createElement("SegmentURL");
            segmentUrl.setAttribute("media", createDASHSegmentUrl(baseUrl, job.getID(), i));
            segmentList.appendChild(segmentUrl);
        }

        // Determine the duration of the final segment.
        Integer remainder = mediaElement.getDuration() % DASHTranscode.DEFAULT_SEGMENT_DURATION;
        if (remainder > 0) {
            Element segmentUrl = mpd.createElement("SegmentURL");
            segmentUrl.setAttribute("media", createDASHSegmentUrl(baseUrl, job.getID(),
                    mediaElement.getDuration() / HLSTranscode.DEFAULT_SEGMENT_DURATION));
            segmentList.appendChild(segmentUrl);
        }

        mpd.normalizeDocument();

        return mpd;
    } catch (ParserConfigurationException ex) {
    }

    return null;
}

From source file:com.aurel.track.exchange.track.exporter.TrackExportBL.java

/**
 * Create a dom element with text content and attributes
 * @param elementName//from  ww  w .j  a  v  a 2  s .c  o  m
 * @param textContent
 * @param attributeValues
 * @param dom
 * @return
 */
private static Element createElementWithAttributes(String elementName, String textContent, boolean needCDATA,
        Map<String, String> attributeValues, Document dom) {
    //create the main element
    Element element = null;
    try {
        element = dom.createElement(elementName);
    } catch (DOMException e) {
        LOGGER.warn("Creating an XML node with the element name " + elementName + " failed with " + e);
    }
    if (element == null) {
        return null;
    }

    //create the text element
    if (textContent != null) {
        if (needCDATA) {
            CDATASection cdataText = dom.createCDATASection(Html2Text.stripNonValidXMLCharacters(textContent));
            element.appendChild(cdataText);
        } else {
            Text textElement;
            try {
                textElement = dom.createTextNode(textContent);
            } catch (DOMException e) {
                LOGGER.info("Creating the text node for the element " + elementName + " and text " + textContent
                        + " failed with " + e);
                textElement = dom.createTextNode("");
            }
            //append the text to the element
            element.appendChild(textElement);
        }
    }

    //set the attributes
    if (attributeValues != null) {
        Iterator<String> iterator = attributeValues.keySet().iterator();
        while (iterator.hasNext()) {
            String attributeName = iterator.next();
            String attributeValue = attributeValues.get(attributeName);
            if (attributeValue != null) {
                try {
                    element.setAttribute(attributeName, attributeValue);
                } catch (DOMException e) {
                    LOGGER.warn("Setting the attribute name " + attributeName + " to attribute value "
                            + attributeValue + " faield with " + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
    }
    return element;
}

From source file:com.redsqirl.workflow.server.action.AbstractDictionary.java

private void saveXml(File f) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("dictionary");
    doc.appendChild(rootElement);//from  w ww  .  ja  va2 s  . c om
    for (Entry<String, String[][]> e : functionsMap.entrySet()) {
        Element menu = doc.createElement("menu");
        menu.setAttribute("name", e.getKey());
        for (String[] function : e.getValue()) {
            try {
                Element functionEl = doc.createElement("function");
                {
                    Element name = doc.createElement("name");
                    name.appendChild(doc.createTextNode(function[0]));
                    functionEl.appendChild(name);
                }
                {
                    Element input = doc.createElement("input");
                    input.appendChild(doc.createTextNode(function[1]));
                    functionEl.appendChild(input);
                }
                {
                    Element output = doc.createElement("return");
                    output.appendChild(doc.createTextNode(function[2]));
                    functionEl.appendChild(output);
                }

                if (function.length >= 4) {
                    Element help = doc.createElement("help");
                    help.appendChild(doc.createTextNode(function[3]));
                    functionEl.appendChild(help);
                }

                for (int i = 4; i < function.length; ++i) {
                    Element other = doc.createElement("other" + (i - 3));
                    other.appendChild(doc.createTextNode(function[i]));
                    functionEl.appendChild(other);
                }

                menu.appendChild(functionEl);
            } catch (NullPointerException exc) {
            }
        }
        rootElement.appendChild(menu);
    }

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(f);
    transformer.transform(source, result);
}

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

/**
* Provisions a new SQL Database server in a subscription.
*
* @param parameters Required. The parameters needed to provision a server.
* @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.//from  w  w  w  .ja  va2s.co m
* @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 returned from the Create Server operation.  This
* contains all the information returned from the service when a server is
* created.
*/
@Override
public ServerCreateResponse create(ServerCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getAdministratorPassword() == null) {
        throw new NullPointerException("parameters.AdministratorPassword");
    }
    if (parameters.getAdministratorUserName() == null) {
        throw new NullPointerException("parameters.AdministratorUserName");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }

    // 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("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createAsync", 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";
    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", "2012-03-01");

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

    Element serverElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/",
            "Server");
    requestDoc.appendChild(serverElement);

    Element administratorLoginElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLogin");
    administratorLoginElement.appendChild(requestDoc.createTextNode(parameters.getAdministratorUserName()));
    serverElement.appendChild(administratorLoginElement);

    Element administratorLoginPasswordElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLoginPassword");
    administratorLoginPasswordElement
            .appendChild(requestDoc.createTextNode(parameters.getAdministratorPassword()));
    serverElement.appendChild(administratorLoginPasswordElement);

    Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/",
            "Location");
    locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
    serverElement.appendChild(locationElement);

    if (parameters.getVersion() != null) {
        Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/",
                "Version");
        versionElement.appendChild(requestDoc.createTextNode(parameters.getVersion()));
        serverElement.appendChild(versionElement);
    }

    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_CREATED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element serverNameElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/sqlazure/2010/12/", "ServerName");
            if (serverNameElement != null) {
                Attr fullyQualifiedDomainNameAttribute = serverNameElement.getAttributeNodeNS(
                        "http://schemas.microsoft.com/sqlazure/2010/12/", "FullyQualifiedDomainName");
                if (fullyQualifiedDomainNameAttribute != null) {
                    result.setFullyQualifiedDomainName(fullyQualifiedDomainNameAttribute.getValue());
                }

                result.setServerName(serverNameElement.getTextContent());
            }

        }
        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:isl.FIMS.servlet.imports.ImportXML.java

private Document createAdminPart(String fileId, String type, Document doc, String username) {
    //create admin element
    String query = "name(//admin/parent::*)";
    DBFile dbf = new DBFile(this.DBURI, this.systemDbCollection + type, type + ".xml", this.DBuser,
            this.DBpassword);
    String parentOfAdmin = dbf.queryString(query)[0];
    Element parentElement = (Element) doc.getElementsByTagName(parentOfAdmin).item(0);
    Element admin = doc.createElement("admin");
    parentElement.appendChild(admin);//w  w w.ja  v  a2  s.c  om

    //create id element
    String id = fileId.split(type)[1];
    Element idE = doc.createElement("id");
    idE.appendChild(doc.createTextNode(id));
    admin.appendChild(idE);

    //create uri_id element
    String uri_name = "";
    try {
        uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0];
    } catch (DMSException ex) {
        ex.printStackTrace();
    }
    String uriValue = this.URI_Reference_Path + uri_name + "/" + id;
    String uriPath = UtilsXPaths.getPathUriField(type);
    Element uriId = doc.createElement("uri_id");
    uriId.appendChild(doc.createTextNode(uriValue));
    admin.appendChild(uriId);
    if (!uriPath.equals("")) {
        try {
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList) xPath.evaluate(uriPath, doc.getDocumentElement(),
                    XPathConstants.NODESET);
            Node oldChild = nodes.item(0);
            if (oldChild != null) {
                oldChild.setTextContent(uriValue);
            }
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
        }
    }

    //create lang element
    Element lang = doc.createElement("lang");
    lang.appendChild(doc.createTextNode(this.lang));
    admin.appendChild(lang);

    //create organization element
    Element organization = doc.createElement("organization");
    organization.appendChild(doc.createTextNode(this.getUserGroup(username)));
    admin.appendChild(organization);

    //create creator element
    Element creator = doc.createElement("creator");
    creator.appendChild(doc.createTextNode(username));
    admin.appendChild(creator);

    //create creator element
    Element saved = doc.createElement("saved");
    saved.appendChild(doc.createTextNode("yes"));
    admin.appendChild(saved);

    //create locked element
    Element locked = doc.createElement("locked");
    locked.appendChild(doc.createTextNode("no"));
    admin.appendChild(locked);
    Element status = doc.createElement("status");
    if (GetEntityCategory.getEntityCategory(type).equals("primary")) {
        status.appendChild(doc.createTextNode("unpublished"));
    }
    admin.appendChild(status);

    //create version elemnt
    Element versions = doc.createElement("versions");

    //create versionidr elememt
    Element versionId = doc.createElement("versionId");
    versionId.appendChild(doc.createTextNode("1"));
    versions.appendChild(versionId);

    //create versionUser elememt
    Element versionUser = doc.createElement("versionUser");
    versionUser.appendChild(doc.createTextNode(username));
    versions.appendChild(versionUser);

    //create versionDate elememt
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    Element versionDate = doc.createElement("versionDate");
    versionDate.appendChild(doc.createTextNode(dateFormat.format(date)));
    versions.appendChild(versionDate);

    admin.appendChild(versions);
    //create read element
    Element read = doc.createElement("read");
    read.appendChild(doc.createTextNode(username));
    admin.appendChild(read);

    //create write element
    Element write = doc.createElement("write");
    write.appendChild(doc.createTextNode(username));
    admin.appendChild(write);

    //create status element
    //create imported element
    Element imported = doc.createElement("imported");
    imported.appendChild(doc.createTextNode(username));
    admin.appendChild(imported);

    return doc;
}

From source file:net.sf.jabref.logic.msbib.MSBibEntry.java

private void addField(Document document, Element parent, String name, String value) {
    if (value == null) {
        return;//from  www.ja  v a 2 s. c o  m
    }
    Element elem = document.createElement(B_COLON + name);
    elem.appendChild(document.createTextNode(StringUtil.stripNonValidXMLCharacters(value)));
    parent.appendChild(elem);
}

From source file:edu.cmu.cs.lti.ark.fn.evaluation.PrepareFullAnnotationXML.java

/**
 * Given several parallel lists of predicted frame instances, including their frame elements, create an XML file 
 * for the full-text annotation predicted by the model.
 * @param predictedFELines Lines encoding predicted frames & FEs in the same format as the .sentences.frame.elements files
 * @param sentenceNums Global sentence number for the first sentence being predicted, so as to map FE lines to items in parses/orgLines
 * @param parses Lines encoding the parse for each sentence
 * @param origLines The original sentences, untokenized
 * @return//from www  .ja  v  a 2 s.  c o  m
 */
public static Document createXMLDoc(List<String> predictedFELines, Range sentenceNums, List<String> parses,
        List<String> origLines) {
    final Document doc = XmlUtils.getNewDocument();
    final Element corpus = doc.createElement("corpus");
    addAttribute(doc, "ID", corpus, "100");
    addAttribute(doc, "name", corpus, "ONE");
    addAttribute(doc, "XMLCreated", corpus, new Date().toString());
    final Element documents = doc.createElement("documents");
    corpus.appendChild(documents);

    final Element document = doc.createElement("document");
    addAttribute(doc, "ID", document, "1");
    addAttribute(doc, "description", document, "TWO");
    documents.appendChild(document);

    final Element paragraphs = doc.createElement("paragraphs");
    document.appendChild(paragraphs);

    final Element paragraph = doc.createElement("paragraph");
    addAttribute(doc, "ID", paragraph, "2");
    addAttribute(doc, "documentOrder", paragraph, "1");
    paragraphs.appendChild(paragraph);

    final Element sentences = doc.createElement("sentences");

    // Map sentence offsets to frame annotation data points within each sentence
    final TIntObjectHashMap<Set<String>> predictions = new TIntObjectHashMap<Set<String>>();
    for (String feLine : predictedFELines) {
        final int sentNum = DataPointWithFrameElements.parseFrameNameAndSentenceNum(feLine).second;

        if (!predictions.containsKey(sentNum))
            predictions.put(sentNum, new THashSet<String>());

        predictions.get(sentNum).add(feLine);
    }

    for (int sent = sentenceNums.start; sent < sentenceNums.start + sentenceNums.length(); sent++) {
        final String parseLine = parses.get(sent - sentenceNums.start);

        final Element sentence = doc.createElement("sentence");
        addAttribute(doc, "ID", sentence, "" + (sent - sentenceNums.start));

        final Element text = doc.createElement("text");
        final String origLine = origLines.get(sent - sentenceNums.start);
        final Node textNode = doc.createTextNode(origLine);
        text.appendChild(textNode);
        sentence.appendChild(text);
        final Element tokensElt = doc.createElement("tokens");
        final String[] tokens = origLine.trim().split(" ");
        for (int i : xrange(tokens.length)) {
            final String token = tokens[i];
            final Element tokenElt = doc.createElement("token");
            addAttribute(doc, "index", tokenElt, "" + i);
            final Node tokenNode = doc.createTextNode(token);
            tokenElt.appendChild(tokenNode);
            tokensElt.appendChild(tokenElt);
        }
        sentence.appendChild(tokensElt);

        final Element annotationSets = doc.createElement("annotationSets");

        int frameIndex = 0; // index of the predicted frame within the sentence
        final Set<String> feLines = predictions.get(sent);

        if (feLines != null) {
            final List<DataPointWithFrameElements> dataPoints = Lists.newArrayList();
            for (String feLine : feLines) {
                final DataPointWithFrameElements dp = new DataPointWithFrameElements(parseLine, feLine);
                dp.processOrgLine(origLine);
                dataPoints.add(dp);
            }
            final Set<String> seenTargetSpans = Sets.newHashSet();
            for (DataPointWithFrameElements dp : dataPoints) {
                final String targetIdxsString = Arrays.toString(dp.getTargetTokenIdxs());
                if (seenTargetSpans.contains(targetIdxsString)) {
                    System.err.println("Duplicate target tokens: " + targetIdxsString
                            + ". Skipping. Sentence id: " + sent);
                    continue; // same target tokens should never show up twice in the same sentence
                } else {
                    seenTargetSpans.add(targetIdxsString);
                }
                assert dp.rank == 1; // this doesn't work with k-best lists anymore
                final String frame = dp.getFrameName();
                // Create the <annotationSet> Element for the predicted frame annotation, and add it under the sentence
                Element annotationSet = buildAnnotationSet(frame, ImmutableList.of(dp), doc,
                        sent - sentenceNums.start, frameIndex);
                annotationSets.appendChild(annotationSet);
                frameIndex++;
            }
        }
        sentence.appendChild(annotationSets);
        sentences.appendChild(sentence);
    }
    paragraph.appendChild(sentences);
    doc.appendChild(corpus);
    return doc;
}