Example usage for javax.xml.parsers DocumentBuilder newDocument

List of usage examples for javax.xml.parsers DocumentBuilder newDocument

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder newDocument.

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

From source file:ddf.catalog.services.xsltlistener.XsltResponseQueueTransformer.java

@Override
public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse,
        Map<String, Serializable> arguments) throws CatalogTransformerException {

    LOGGER.debug("Transforming ResponseQueue with XSLT tranformer");

    long grandTotal = -1;

    try {/*w w  w .  j  av  a 2 s .  c om*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.newDocument();

        Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null));

        // TODO use streaming XSLT, not DOM
        List<Result> results = upstreamResponse.getResults();
        grandTotal = upstreamResponse.getHits();

        for (Result result : results) {
            Metacard metacard = result.getMetacard();
            String thisMetacard = metacard.getMetadata();
            if (metacard != null && thisMetacard != null) {
                Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null);
                if (metacard.getId() != null) {
                    metacardElement
                            .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId()));
                }
                if (metacard.getMetacardType().toString() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type",
                            metacard.getMetacardType().getName()));
                }
                if (metacard.getTitle() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle()));
                }
                if (result.getRelevanceScore() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score",
                            result.getRelevanceScore().toString()));
                }
                if (result.getDistanceInMeters() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance",
                            result.getDistanceInMeters().toString()));
                }
                if (metacard.getSourceId() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId()));
                }
                if (metacard.getContentTypeName() != null) {
                    String contentType = metacard.getContentTypeName();
                    Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type",
                            contentType);
                    // TODO revisit what to put in the qualifier
                    typeElement.setAttribute("qualifier", "content-type");
                    metacardElement.appendChild(typeElement);
                }
                if (metacard.getResourceURI() != null) {
                    try {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product",
                                metacard.getResourceURI().toString()));
                    } catch (DOMException e) {
                        LOGGER.warn(" Unable to create resource uri element", e);
                    }
                }
                if (metacard.getThumbnail() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail",
                            Base64.encodeBase64String(metacard.getThumbnail())));
                    try {
                        String mimeType = URLConnection
                                .guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail()));
                        metacardElement
                                .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        metacardElement.appendChild(
                                createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png"));
                    }
                }
                DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                if (metacard.getCreatedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created",
                            fmt.print(metacard.getCreatedDate().getTime())));
                }
                // looking at the date last modified
                if (metacard.getModifiedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated",
                            fmt.print(metacard.getModifiedDate().getTime())));
                }
                if (metacard.getEffectiveDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective",
                            fmt.print(metacard.getEffectiveDate().getTime())));
                }
                if (metacard.getLocation() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation()));
                }
                Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document");
                metacardElement.appendChild(documentElement);
                resultsElement.appendChild(metacardElement);

                Node importedNode = doc.importNode(new XPathHelper(thisMetacard).getDocument().getFirstChild(),
                        true);
                documentElement.appendChild(importedNode);
            } else {
                LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer");
                continue;
            }
        }

        if (LOGGER.isDebugEnabled()) {
            DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
            LSSerializer lsSerializer = domImplementation.createLSSerializer();
            LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc));
        }

        LOGGER.debug("Starting responsequeue xslt transform.");

        Transformer transformer;

        Map<String, Object> mergedMap = new HashMap<String, Object>();
        mergedMap.put(GRAND_TOTAL, grandTotal);
        if (arguments != null) {
            mergedMap.putAll(arguments);
        }

        BinaryContent resultContent;
        StreamResult resultOutput = null;
        Source source = new DOMSource(doc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        resultOutput = new StreamResult(baos);

        try {
            transformer = templates.newTransformer();
        } catch (TransformerConfigurationException tce) {
            throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(),
                    tce.getCause());
        }

        if (mergedMap != null && !mergedMap.isEmpty()) {
            for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "Adding parameter to transform {" + entry.getKey() + ":" + entry.getValue() + "}");
                }
                transformer.setParameter(entry.getKey(), entry.getValue());
            }
        }

        try {
            transformer.transform(source, resultOutput);
            byte[] bytes = baos.toByteArray();
            LOGGER.debug("Transform complete.");
            resultContent = new XsltTransformedContent(bytes, mimeType);
        } catch (TransformerException te) {
            LOGGER.error("Could not perform Xslt transform: " + te.getException(), te.getCause());
            throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getException(),
                    te.getCause());
        } finally {
            // transformer.reset();
            // don't need to do that unless we are putting it back into a
            // pool -- which we should do, but that can wait until later.
        }

        return resultContent;
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Error creating new document: " + e.getMessage(), e.getCause());
        throw new CatalogTransformerException("Error merging entries to xml feed.", e);
    }
}

From source file:com.rapidsist.portal.cliente.editor.ConnectorServlet.java

/**
 * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It execute the command and then return the results to the client in XML format.
 *
 *///from  www  .j ava  2 s .co  m
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println("PASO POR EL METODO doGet DEL SERVLET ConnectorServlet");

    //OBTIENE EL USUARIO QUE OPERA EL EDITOR HTML
    HttpSession session = SesionUsuario.compruebaSesionUsuario(request, response);
    Usuario usuario = (Usuario) session.getAttribute("Usuario");

    //OBTIENE LA CLAVE DE LA EMPRESA Y LA CLAVE DEL PORTAL ASIGNADOS AL USUARIO
    String sCveGpoEmpresa = usuario.sCveGpoEmpresa;
    String sCvePortal = usuario.sCvePortal;

    //CREA LA CARPETA UserFiles EN CASO DE NO EXISTIR.
    baseDir = "/UserFiles/";
    String realBaseDir = getServletContext().getRealPath(baseDir);
    File baseFile = new File(realBaseDir);
    if (!baseFile.exists()) {
        baseFile.mkdir();
    }

    //CREA LA CARPETA CveGpoEmpresa EN CASO DE NO EXISTIR.
    baseDir = "/UserFiles/" + sCveGpoEmpresa + "/";
    realBaseDir = getServletContext().getRealPath(baseDir);
    baseFile = new File(realBaseDir);
    if (!baseFile.exists()) {
        baseFile.mkdir();
    }

    //CREA LA CARPETA sCvePortal EN CASO DE NO EXISTIR LA CUAL ES LA RAIZ DEL REPOSITORIO DE ARCHIVOS.
    baseDir = "/UserFiles/" + sCveGpoEmpresa + "/" + sCvePortal + "/";
    realBaseDir = getServletContext().getRealPath(baseDir);
    baseFile = new File(realBaseDir);
    if (!baseFile.exists()) {
        baseFile.mkdir();
    }

    response.setContentType("text/xml; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdir();
    }

    Document document = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.newDocument();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }

    Node root = CreateCommonXml(document, commandStr, typeStr, currentFolderStr,
            request.getContextPath() + currentPath);

    if (commandStr.equals("GetFolders")) {
        getFolders(currentDir, root, document);
    } else if (commandStr.equals("GetFoldersAndFiles")) {
        getFolders(currentDir, root, document);
        getFiles(currentDir, root, document);
    } else if (commandStr.equals("CreateFolder")) {
        String newFolderStr = request.getParameter("NewFolderName");
        File newFolder = new File(currentDir, newFolderStr);
        String retValue = "110";

        if (newFolder.exists()) {
            retValue = "101";
        } else {
            try {
                boolean dirCreated = newFolder.mkdir();
                if (dirCreated)
                    retValue = "0";
                else
                    retValue = "102";
            } catch (SecurityException sex) {
                retValue = "103";
            }

        }
        setCreateFolderResponse(retValue, root, document);
    }

    document.getDocumentElement().normalize();
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        DOMSource source = new DOMSource(document);

        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    out.flush();
    out.close();
}

From source file:com.urbancode.terraform.main.Main.java

public void writeEnvToXml(File file, TerraformContext context) throws XmlParsingException {
    try {/*from w  w w .  jav  a 2s  .c o m*/
        XmlWrite write = new XmlWrite();
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.newDocument();
        write.makeXml(context, doc, null);
        write.writeDocToFile(file, doc);
    } catch (Exception e) {
        throw new XmlParsingException("Exception while writing out XML: " + e.getMessage(), e);
    }

}

From source file:crds.pub.FCKeditor.connector.ConnectorServlet.java

/**
 * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It execute the command and then return the results to the client in XML format.
 *
 *//*from w  w  w. j a  v a  2 s  .co  m*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    FormUserOperation formUser = Constant.getFormUserOperation(request);
    String fck_task_id = (String) session.getAttribute("fck_task_id");
    if (fck_task_id == null) {
        fck_task_id = "temp_task_id";
    }

    response.setContentType("text/xml; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + formUser.getCompany_code() + currentFolderStr + fck_task_id
            + currentFolderStr + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdirs();
    }

    Document document = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.newDocument();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }
    //???IP
    String server_ip = (String) session.getAttribute("server_ip");
    if (server_ip == null) {
        server_ip = CommonMethod.getServerIP(request) + ":" + request.getServerPort();//???IP?
    }
    String url = "http://" + server_ip + currentPath.substring(2, currentPath.length());
    Node root = CreateCommonXml(document, commandStr, typeStr, currentFolderStr, url);

    if (commandStr.equals("GetFolders")) {
        getFolders(currentDir, root, document);
    } else if (commandStr.equals("GetFoldersAndFiles")) {
        getFolders(currentDir, root, document);
        getFiles(currentDir, root, document);
    } else if (commandStr.equals("CreateFolder")) {
        String newFolderStr = request.getParameter("NewFolderName");
        File newFolder = new File(currentDir, newFolderStr);
        String retValue = "110";

        if (newFolder.exists()) {
            retValue = "101";
        } else {
            try {
                boolean dirCreated = newFolder.mkdir();
                if (dirCreated)
                    retValue = "0";
                else
                    retValue = "102";
            } catch (SecurityException sex) {
                retValue = "103";
            }

        }
        setCreateFolderResponse(retValue, root, document);
    }

    document.getDocumentElement().normalize();
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        DOMSource source = new DOMSource(document);

        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);

        if (debug) {
            StreamResult dbgResult = new StreamResult(System.out);
            transformer.transform(source, dbgResult);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    out.flush();
    out.close();
}

From source file:com.photon.phresco.service.impl.DependencyManagerImpl.java

private void updatePOMWithPluginArtifact(File path, List<ArtifactGroup> modules) throws PhrescoException {
    if (isDebugEnabled) {
        LOGGER.debug("DependencyManagerImpl.updatePOMWithPluginArtifact:Entry");
        LOGGER.info(ServiceConstants.DEPENDENCY_MGR_IMPL_UPDATE_POM_WITH_PLUGIN_ARTF,
                ServiceConstants.PATH_EQUALS_SLASH + path.getPath() + "\"");
    }/*w  ww. ja  va2s. c  o m*/
    try {
        if (CollectionUtils.isEmpty(modules)) {
            if (isDebugEnabled) {
                LOGGER.warn(ServiceConstants.DEPENDENCY_MGR_IMPL_UPDATE_POM_WITH_PLUGIN_ARTF,
                        ServiceConstants.STATUS_BAD_REQUEST, "message=\"Modules is empty\"");
            }
            return;
        }

        List<Element> configList = new ArrayList<Element>();
        File pomFile = new File(path, "pom.xml");
        if (pomFile.exists()) {
            PomProcessor processor = new PomProcessor(pomFile);
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            for (ArtifactGroup module : modules) {
                if (module != null) {
                    String groupId = module.getGroupId();
                    String artifactId = module.getArtifactId();
                    String version = module.getVersions().get(0).getVersion();
                    configList = configList(pomFile, groupId, artifactId, version, doc);
                    processor.addExecutionConfiguration("org.apache.maven.plugins", "maven-dependency-plugin",
                            "unpack-module", "validate", "unpack", configList, doc);
                }
            }
            processor.save();
        }
        if (isDebugEnabled) {
            LOGGER.debug("DependencyManagerImpl.updatePOMWithPluginArtifact:Exit");
        }
    } catch (PhrescoPomException e) {
        LOGGER.error(ServiceConstants.DEPENDENCY_MGR_IMPL_UPDATE_POM_WITH_PLUGIN_ARTF,
                ServiceConstants.STATUS_FAILURE,
                ServiceConstants.MESSAGE_EQUALS + "\"" + e.getLocalizedMessage() + "\"");
        throw new PhrescoException(e);
    } catch (ParserConfigurationException e) {
        LOGGER.error(ServiceConstants.DEPENDENCY_MGR_IMPL_UPDATE_POM_WITH_PLUGIN_ARTF,
                ServiceConstants.STATUS_FAILURE,
                ServiceConstants.MESSAGE_EQUALS + "\"" + e.getLocalizedMessage() + "\"");
        throw new PhrescoException(e);
    }
}

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

/**
 * {@inheritDoc }//from w ww.  j av  a2 s  .co  m
 */
@Override
public JSONEntry deserialize(final JsonParser parser, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

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

    if (tree.has(ODataConstants.JSON_VALUE) && tree.get(ODataConstants.JSON_VALUE).isArray()) {
        throw new JsonParseException("Expected OData Entity, found EntitySet", parser.getCurrentLocation());
    }

    final boolean isMediaEntry = tree.hasNonNull(ODataConstants.JSON_MEDIAREAD_LINK)
            && tree.hasNonNull(ODataConstants.JSON_MEDIA_CONTENT_TYPE);

    final JSONEntry entry = new JSONEntry();

    if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
        entry.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
        tree.remove(ODataConstants.JSON_METADATA);
    }

    if (tree.hasNonNull(ODataConstants.JSON_MEDIA_ETAG)) {
        entry.setMediaETag(tree.get(ODataConstants.JSON_MEDIA_ETAG).textValue());
        tree.remove(ODataConstants.JSON_MEDIA_ETAG);
    }

    if (tree.hasNonNull(ODataConstants.JSON_ETAG)) {
        entry.setETag(tree.get(ODataConstants.JSON_ETAG).textValue());
        tree.remove(ODataConstants.JSON_ETAG);
    }

    if (tree.hasNonNull(ODataConstants.JSON_TYPE)) {
        entry.setType(tree.get(ODataConstants.JSON_TYPE).textValue());
        tree.remove(ODataConstants.JSON_TYPE);
    }

    if (tree.hasNonNull(ODataConstants.JSON_ID)) {
        entry.setId(tree.get(ODataConstants.JSON_ID).textValue());
        tree.remove(ODataConstants.JSON_ID);
    }

    if (tree.hasNonNull(ODataConstants.JSON_READ_LINK)) {
        final JSONLink link = new JSONLink();
        link.setRel(ODataConstants.SELF_LINK_REL);
        link.setHref(tree.get(ODataConstants.JSON_READ_LINK).textValue());
        entry.setSelfLink(link);

        tree.remove(ODataConstants.JSON_READ_LINK);
    }

    if (tree.hasNonNull(ODataConstants.JSON_EDIT_LINK)) {
        final JSONLink link = new JSONLink();
        link.setRel(ODataConstants.EDIT_LINK_REL);
        link.setHref(tree.get(ODataConstants.JSON_EDIT_LINK).textValue());
        entry.setEditLink(link);

        tree.remove(ODataConstants.JSON_EDIT_LINK);
    }

    if (tree.hasNonNull(ODataConstants.JSON_MEDIAREAD_LINK)) {
        entry.setMediaContentSource(tree.get(ODataConstants.JSON_MEDIAREAD_LINK).textValue());
        tree.remove(ODataConstants.JSON_MEDIAREAD_LINK);
    }
    if (tree.hasNonNull(ODataConstants.JSON_MEDIAEDIT_LINK)) {
        final JSONLink link = new JSONLink();
        link.setHref(tree.get(ODataConstants.JSON_MEDIAEDIT_LINK).textValue());
        entry.addMediaEditLink(link);

        tree.remove(ODataConstants.JSON_MEDIAEDIT_LINK);
    }
    if (tree.hasNonNull(ODataConstants.JSON_MEDIA_CONTENT_TYPE)) {
        entry.setMediaContentType(tree.get(ODataConstants.JSON_MEDIA_CONTENT_TYPE).textValue());
        tree.remove(ODataConstants.JSON_MEDIA_CONTENT_TYPE);
    }

    final Set<String> toRemove = new HashSet<String>();
    final Iterator<Map.Entry<String, JsonNode>> itor = tree.fields();
    while (itor.hasNext()) {
        final Map.Entry<String, JsonNode> field = itor.next();

        if (field.getKey().endsWith(ODataConstants.JSON_NAVIGATION_LINK_SUFFIX)
                || field.getKey().endsWith(ODataConstants.JSON_NAVIGATION_LINK_ODATA_4_SUFFIX)) {
            final JSONLink link = new JSONLink();
            link.setTitle(getTitle(field));
            link.setRel(ODataConstants.NAVIGATION_LINK_REL + getTitle(field));
            if (field.getValue().isValueNode()) {
                link.setHref(field.getValue().textValue());
                link.setType(ODataLinkType.ENTITY_NAVIGATION.toString());
            }
            // NOTE: this should be expected to happen, but it isn't - at least up to OData 4.0
            /* if (field.getValue().isArray()) {
             * link.setHref(field.getValue().asText());
             * link.setType(ODataLinkType.ENTITY_SET_NAVIGATION.toString());
             * } */
            entry.addNavigationLink(link);

            toRemove.add(field.getKey());
            toRemove.add(setInline(field.getKey(),
                    field.getKey().endsWith(ODataConstants.JSON_NAVIGATION_LINK_SUFFIX)
                            ? ODataConstants.JSON_NAVIGATION_LINK_SUFFIX
                            : ODataConstants.JSON_NAVIGATION_LINK_ODATA_4_SUFFIX,
                    tree, parser.getCodec(), link));
        } else if (field.getKey().endsWith(ODataConstants.JSON_ASSOCIATION_LINK_SUFFIX)) {
            final JSONLink link = new JSONLink();
            link.setTitle(getTitle(field));
            link.setRel(ODataConstants.ASSOCIATION_LINK_REL + getTitle(field));
            link.setHref(field.getValue().textValue());
            link.setType(ODataLinkType.ASSOCIATION.toString());
            entry.addAssociationLink(link);

            toRemove.add(field.getKey());
        } else if (field.getKey().endsWith(ODataConstants.JSON_MEDIAEDIT_LINK_SUFFIX)) {
            final JSONLink link = new JSONLink();
            link.setTitle(getTitle(field));
            link.setRel(ODataConstants.MEDIA_EDIT_LINK_REL + getTitle(field));
            link.setHref(field.getValue().textValue());
            link.setType(ODataLinkType.MEDIA_EDIT.toString());
            entry.addMediaEditLink(link);

            toRemove.add(field.getKey());
            toRemove.add(setInline(field.getKey(), ODataConstants.JSON_MEDIAEDIT_LINK_SUFFIX, tree,
                    parser.getCodec(), link));
        } else if (field.getKey().charAt(0) == '#') {
            final ODataOperation operation = new ODataOperation();
            operation.setMetadataAnchor(field.getKey());

            final ObjectNode opNode = (ObjectNode) tree.get(field.getKey());
            operation.setTitle(opNode.get(ODataConstants.ATTR_TITLE).asText());
            operation.setTarget(URI.create(opNode.get(ODataConstants.ATTR_TARGET).asText()));

            entry.addOperation(operation);

            toRemove.add(field.getKey());
        }
    }
    tree.remove(toRemove);

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

        final Element properties = document.createElementNS(ODataConstants.NS_METADATA,
                ODataConstants.ELEM_PROPERTIES);

        DOMTreeUtils.buildSubtree(properties, tree);

        if (isMediaEntry) {
            entry.setMediaEntryProperties(properties);
        } else {
            entry.setContent(properties);
        }
    } catch (ParserConfigurationException e) {
        throw new JsonParseException("Cannot build entry content", parser.getCurrentLocation(), e);
    }

    return entry;
}

From source file:com.wavemaker.tools.project.LocalDeploymentManager.java

private void updateTomcatDeployConfig(Map<String, Object> properties) {
    LocalFolder projectDir = (LocalFolder) properties.get(PROJECT_DIR_PROPERTY);
    String deployName = (String) properties.get(DEPLOY_NAME_PROPERTY);
    LocalFile tomcatConfigXml = (LocalFile) projectDir.getFile(deployName + ".xml");
    if (tomcatConfigXml.exists()) {
        tomcatConfigXml.delete();/*from  w  w  w  . j ava2 s. c  o m*/
    }
    tomcatConfigXml.createIfMissing();
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        NodeList nodeList = doc.getElementsByTagName("Context");

        if (nodeList != null && nodeList.getLength() > 0) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getParentNode() != null) {
                    node.getParentNode().removeChild(node);
                }
            }
        }

        Element context = doc.createElement("Context");
        context.setAttribute("antiJARLocking", "true'");
        context.setAttribute("antiResourceLocking", "false");
        context.setAttribute("privileged", "true");
        String docBase = ((LocalFolder) properties.get(BUILD_WEBAPPROOT_PROPERTY)).getLocalFile()
                .getAbsolutePath();
        context.setAttribute("docBase", docBase);

        doc.appendChild(context);

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tFormer = tFactory.newTransformer();

        Source source = new DOMSource(doc);
        Result dest = new StreamResult(tomcatConfigXml.getLocalFile());
        tFormer.transform(source, dest);

    } catch (Exception e) {
        throw new WMRuntimeException(e);
    }
}

From source file:me.uni.sushilkumar.geodine.util.YummlyLookup.java

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request//from w  w w  . j  a v a2 s.co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException {
    response.setContentType("text/xml");
    PrintWriter out = response.getWriter();
    DBConnection con = null;
    try {

        String cuisine = request.getParameter("cuisine");
        con = new DBConnection();
        CuisineObject obj = con.getCuisineData(cuisine);
        int id = obj.getId();
        String cuisineId = obj.getCuisineId();
        String country = obj.getCountry();
        String ytid = obj.getYtid();

        ArrayList<String> directions = obj.getDirections();
        ArrayList<String> ingredients = obj.getIngredients();
        HttpSession session = request.getSession(true);
        String email = (String) session.getAttribute("userName");
        boolean isFav = con.isFavourite(cuisineId, email);
        String fav = "";
        if (isFav)
            fav = "true";
        else
            fav = "false";
        DocumentBuilderFactory docFactory = null;
        DocumentBuilder docBuilder = null;
        Document xmlDoc = null;
        Element root = null;
        docFactory = DocumentBuilderFactory.newInstance();
        docBuilder = docFactory.newDocumentBuilder();
        xmlDoc = docBuilder.newDocument();
        root = xmlDoc.createElement("item");
        xmlDoc.appendChild(root);

        Element eid = xmlDoc.createElement("id");
        eid.appendChild(xmlDoc.createTextNode(Integer.toString(id)));
        root.appendChild(eid);

        Element eisfav = xmlDoc.createElement("favourite");
        eisfav.appendChild(xmlDoc.createTextNode(fav));
        root.appendChild(eisfav);

        Element ecuisineId = xmlDoc.createElement("cuisine-id");
        ecuisineId.appendChild(xmlDoc.createTextNode(cuisineId));
        root.appendChild(ecuisineId);

        Element ecountry = xmlDoc.createElement("country");
        ecountry.appendChild(xmlDoc.createTextNode(country));
        root.appendChild(ecountry);

        Element eytid = xmlDoc.createElement("ytid");
        eytid.appendChild(xmlDoc.createTextNode(ytid));
        root.appendChild(eytid);

        Element edirections = xmlDoc.createElement("steps");
        for (int i = 0; i < directions.size(); i++) {
            Element temp = xmlDoc.createElement("step");
            temp.appendChild(xmlDoc.createTextNode(directions.get(i)));
            edirections.appendChild(temp);
        }
        root.appendChild(edirections);

        Element eingredients = xmlDoc.createElement("ingredients");
        for (int i = 0; i < ingredients.size(); i++) {
            Element temp = xmlDoc.createElement("ingredient");
            temp.appendChild(xmlDoc.createTextNode(ingredients.get(i)));
            eingredients.appendChild(temp);
        }
        root.appendChild(eingredients);

        StringWriter sw = new StringWriter();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        //transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(xmlDoc);
        StreamResult result = new StreamResult(sw);
        transformer.transform(source, result);
        out.println(sw.toString());
        if (email != null) {
            con.addRecentCuisine(cuisineId, email, new Date().toString());
        }

    } catch (TransformerException ex) {
        Logger.getLogger(YummlyLookup.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(YummlyLookup.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
        if (con != null) {
            con.close();
        }
    }
}

From source file:com.seajas.search.attender.service.template.TemplateService.java

/**
 * Create a results template result.// w  ww . java 2 s  .  c o  m
 * 
 * @param language
 * @param queryString
 * @param query
 * @param uuid
 * @param searchResults
 * @return TemplateResult
 */
public TemplateResult createResults(final String language, final String queryString, final String query,
        final String subscriberUUID, final String profileUUID, final List<SearchResult> searchResults)
        throws ScriptException {
    Template template = templateDAO.findTemplate(TemplateType.Results, language);

    if (template == null) {
        logger.warn("Could not retrieve results template for language " + language
                + " - falling back to default language " + attenderService.getDefaultApplicationLanguage());

        template = templateDAO.findTemplate(TemplateType.Confirmation,
                attenderService.getDefaultApplicationLanguage());

        if (template == null) {
            logger.error("Could not retrieve fall-back results template for language "
                    + attenderService.getDefaultApplicationLanguage() + " - not generating a template result");

            return null;
        }
    }

    // Create an input document

    Document document;

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        documentBuilderFactory.setCoalescing(true);
        documentBuilderFactory.setNamespaceAware(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        document = documentBuilder.newDocument();

        Element results = document.createElement("results");

        results.setAttribute("templateLanguage", language);
        results.setAttribute("profileQuery", query);
        results.setAttribute("subscriberUUID", subscriberUUID);
        results.setAttribute("profileUUID", profileUUID);
        results.setAttribute("queryString", queryString);

        for (SearchResult searchResult : searchResults)
            results.appendChild(searchResult.toElement(document));

        document.appendChild(results);

        // Plain text

        Transformer textTransformer = getTransformer(template, true);
        StringWriter textWriter = new StringWriter();

        textTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        textTransformer.transform(new DOMSource(document), new StreamResult(textWriter));

        // HTML

        Transformer htmlTransformer = getTransformer(template, false);
        StringWriter htmlWriter = new StringWriter();

        htmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        htmlTransformer.transform(new DOMSource(document), new StreamResult(htmlWriter));

        return new TemplateResult(textWriter.toString(), htmlWriter.toString());
    } catch (ScriptException e) {
        throw e;
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

From source file:com.adaptris.core.services.jdbc.SplittingXmlPayloadTranslator.java

private DocumentWrapper toDocument(AdaptrisMessage msg, JdbcResultSet rSet)
        throws ParserConfigurationException, SQLException {
    DocumentBuilderFactoryBuilder factoryBuilder = documentFactoryBuilder(msg);
    DocumentBuilderFactory factory = factoryBuilder.configure(DocumentBuilderFactory.newInstance());
    DocumentBuilder builder = factoryBuilder.configure(factory.newDocumentBuilder());
    Document doc = builder.newDocument();
    DocumentWrapper result = new DocumentWrapper(doc, 0);
    ColumnStyle elementNameStyle = getColumnNameStyle();

    Element results = doc.createElement(elementNameStyle.format(ELEMENT_NAME_RESULTS));
    doc.appendChild(results);/*from  w  w  w .  jav a  2s  . com*/

    List<Element> elements = createListFromResultSet(builder, doc, rSet);
    for (Element element : elements) {
        results.appendChild(element);
    }
    result.resultSetCount += elements.size();
    return result;
}