Example usage for org.w3c.dom Node getParentNode

List of usage examples for org.w3c.dom Node getParentNode

Introduction

In this page you can find the example usage for org.w3c.dom Node getParentNode.

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

/**
 * Compute the xpath of a node relative to an anchor.
 * /*from  ww w. j  a  v a  2 s .com*/
 * @param node
 *            node to find the xpath from.
 * @param anchor
 *            the relative point to fid from.
 * @return the computed xpath.
 */
public static String calcXpath(Node node, Node anchor) {
    String xpath = "";
    Node current = null;

    if (node == null || node.equals(anchor))
        return "";

    // add attribute to xpath
    if (node instanceof Attr) {
        Attr attr = (Attr) node;
        node = attr.getOwnerElement();
        xpath = '@' + attr.getName() + '/';
    }

    while ((current = node.getParentNode()) != anchor) {
        Engine.logEngine.trace("Calc Xpath : current node : " + current.getNodeName());
        NodeList childs = current.getChildNodes();
        int index = 0;
        for (int i = 0; i < childs.getLength(); i++) {
            if (childs.item(i).getNodeType() != Node.ELEMENT_NODE
                    && !childs.item(i).getNodeName().equalsIgnoreCase("#text"))
                continue;

            Engine.logEngine.trace("Calc Xpath : ==== > Child node : " + childs.item(i).getNodeName());

            // Bump the index if we have the same tag names..
            if (childs.item(i).getNodeName().equalsIgnoreCase(node.getNodeName())) {
                // tag names are equal ==> bump the index.
                index++;
                // is our node the one that is listed ?
                if (childs.item(i).equals(node))
                    // We found our node in the parent node list
                    break;
            }
        }
        // count the number of elements having the same tag
        int nbElements = 0;
        for (int i = 0; i < childs.getLength(); i++) {
            if (childs.item(i).getNodeName().equalsIgnoreCase(node.getNodeName())) {
                nbElements++;
            }
        }

        String name = node.getNodeName();
        if (name.equalsIgnoreCase("#text"))
            name = "text()";
        name = xpathEscapeColon(name);

        if (nbElements > 1) {
            xpath = name + "[" + index + "]/" + xpath;
        } else {
            // only one element had the same tag ==> do not compute the [xx]
            // syntax..
            xpath = name + "/" + xpath;
        }
        node = current;
    }
    if (xpath.length() > 0)
        // remove the trailing '/'
        xpath = xpath.substring(0, xpath.length() - 1);

    return xpath;
}

From source file:com.crawljax.plugins.errorreport.ErrorReport.java

private Document addMarker(String id, Document doc, String xpath) {
    try {// w  w  w .  ja  v  a2s. c  o m

        String prefixMarker = "###BEGINMARKER" + id + "###";
        String suffixMarker = "###ENDMARKER###";

        NodeList nodeList = XPathHelper.evaluateXpathExpression(doc, xpath);

        if (nodeList.getLength() == 0 || nodeList.item(0) == null) {
            return doc;
        }
        Node element = nodeList.item(0);

        if (element.getNodeType() == Node.ELEMENT_NODE) {
            Node beginNode = doc.createTextNode(prefixMarker);
            Node endNode = doc.createTextNode(suffixMarker);

            element.getParentNode().insertBefore(beginNode, element);
            if (element.getNextSibling() == null) {
                element.getParentNode().appendChild(endNode);
            } else {
                element.getParentNode().insertBefore(endNode, element.getNextSibling());
            }
        } else if (element.getNodeType() == Node.TEXT_NODE && element.getTextContent() != null) {
            element.setTextContent(prefixMarker + element.getTextContent() + suffixMarker);
        } else if (element.getNodeType() == Node.ATTRIBUTE_NODE) {
            element.setNodeValue(prefixMarker + element.getTextContent() + suffixMarker);
        }

        return doc;
    } catch (Exception e) {
        return doc;
    }
}

From source file:com.concursive.connect.cms.portal.dao.DashboardTemplateList.java

private void parseLibrary(XMLUtils library) {
    LOG.debug("objectType=" + objectType);
    LOG.debug("has xml? " + (library != null));
    if (LOG.isTraceEnabled()) {
        LOG.trace(library.toString());/* ww  w . ja  v a 2s .co  m*/
    }

    // Use XPath for querying xml elements
    XPath xpath = XPathFactory.newInstance().newXPath();

    // Build a list of dashboard pages
    ArrayList<Element> pageElements = new ArrayList<Element>();
    XMLUtils.getAllChildren(XMLUtils.getFirstChild(library.getDocumentElement(), objectType), "page",
            pageElements);
    Iterator i = pageElements.iterator();
    int count = 0;
    while (i.hasNext()) {
        ++count;
        Element el = (Element) i.next();
        DashboardTemplate thisTemplate = new DashboardTemplate();
        thisTemplate.setId(count);
        thisTemplate.setName(el.getAttribute("name"));

        // Check for xml included fragments declaration
        // <xml-include fragment="portal-fragments-id"/>
        // NOTE: since the document is being read as a resource, xinclude and xpointer could not be used
        // mainly due to xpointer not being implemented
        try {
            NodeList includeList = (NodeList) xpath.evaluate("row/column/portlet/xml-include", el,
                    XPathConstants.NODESET);
            // XML Include found, so find all the fragments
            for (int nodeIndex = 0; nodeIndex < includeList.getLength(); nodeIndex++) {
                Node xmlInclude = includeList.item(nodeIndex);
                String fragmentId = ((Element) xmlInclude).getAttribute("fragment");

                NodeList fragmentNodeList = (NodeList) xpath.evaluate(
                        "*/fragment[@id=\"" + fragmentId + "\"]/*", library.getDocumentElement(),
                        XPathConstants.NODESET);
                if (LOG.isDebugEnabled() && fragmentNodeList.getLength() == 0) {
                    LOG.error("Could not find fragment with id: " + fragmentId);
                }
                for (int prefIndex = 0; prefIndex < fragmentNodeList.getLength(); prefIndex++) {
                    xmlInclude.getParentNode().appendChild(fragmentNodeList.item(prefIndex).cloneNode(true));
                }
                // Remove the XML Include declaration
                xmlInclude.getParentNode().removeChild(xmlInclude);

            }
        } catch (Exception e) {
            LOG.error("Replace xml fragments", e);
        }

        // Set the completed xml layout
        thisTemplate.setXmlDesign(XMLUtils.toString(el));

        // Check for properties that affect the rendering of the portal page
        if (el.hasAttribute("permission")) {
            thisTemplate.setPermission(el.getAttribute("permission"));
        }
        if (el.hasAttribute("title")) {
            thisTemplate.setTitle(el.getAttribute("title"));
        }
        if (el.hasAttribute("description")) {
            thisTemplate.setDescription(el.getAttribute("description"));
        }
        if (el.hasAttribute("keywords")) {
            thisTemplate.setKeywords(el.getAttribute("keywords"));
        }
        if (el.hasAttribute("category")) {
            thisTemplate.setCategory(el.getAttribute("category"));
        }
        this.add(thisTemplate);
    }
}

From source file:DomPrintUtil.java

private Node getVisibleNextSibling(Node target, Node root) {
    if (target == root) {
        return null;
    }/* ww w .  j a  va2  s . c  om*/
    Node tmpN = target.getNextSibling();
    if (null == tmpN) {
        Node tmpP = target.getParentNode();
        if (eval(tmpP) == NodeFilter.FILTER_SKIP) {
            return getVisibleNextSibling(tmpP, root);
        }
        return null;
    }
    switch (eval(tmpN)) {
    case NodeFilter.FILTER_ACCEPT:
        return tmpN;
    case NodeFilter.FILTER_SKIP:
        Node tmpC = getVisibleFirstChild(tmpN);
        if (null != tmpC) {
            return tmpC;
        }
        // case NodeFilter.FILTER_REJECT:
    default:
        return getVisibleNextSibling(tmpN, root);
    }
}

From source file:DomPrintUtil.java

private Node getVisiblePreviousSibling(Node target, Node root) {
    if (target == root) {
        return null;
    }//from   w  ww. ja  v a 2s  . co  m
    Node tmpN = target.getPreviousSibling();
    if (null == tmpN) {
        Node tmpP = target.getParentNode();
        if (eval(tmpP) == NodeFilter.FILTER_SKIP) {
            return getVisiblePreviousSibling(tmpP, root);
        }
        return null;
    }
    switch (eval(tmpN)) {
    case NodeFilter.FILTER_ACCEPT:
        return tmpN;
    case NodeFilter.FILTER_SKIP:
        Node tmpC = getVisibleLastChild(tmpN);
        if (null != tmpC) {
            return tmpC;
        }
        // case NodeFilter.FILTER_REJECT:
    default:
        return getVisiblePreviousSibling(tmpN, root);
    }
}

From source file:com.portfolio.data.attachment.XSLService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**/*  ww w  . j a  v  a2 s  .c  om*/
     * Format demand:
     * <convert>
     *   <portfolioid>{uuid}</portfolioid>
     *   <portfolioid>{uuid}</portfolioid>
     *   <nodeid>{uuid}</nodeid>
     *   <nodeid>{uuid}</nodeid>
     *   <documentid>{uuid}</documentid>
     *   <xsl>{rpertoire}{fichier}</xsl>
     *   <format>[pdf rtf xml ...]</format>
     *   <parameters>
     *     <maVar1>lala</maVar1>
     *     ...
     *   </parameters>
     * </convert>
     */
    try {
        //On initialise le dataProvider
        Connection c = null;
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String origin = request.getRequestURL().toString();

    /// Variable stuff
    int userId = 0;
    int groupId = 0;
    String user = "";
    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    /// TODO: A voire si un form get ne ferait pas l'affaire aussi

    /// On lis le xml
    /*
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while( (line = rd.readLine()) != null )
       sb.append(line);
            
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    Document doc=null;
    try
    {
       documentBuilder = documentBuilderFactory.newDocumentBuilder();
       doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
            
    /// On lit les paramtres
    NodeList portfolioNode = doc.getElementsByTagName("portfolioid");
    NodeList nodeNode = doc.getElementsByTagName("nodeid");
    NodeList documentNode = doc.getElementsByTagName("documentid");
    NodeList xslNode = doc.getElementsByTagName("xsl");
    NodeList formatNode = doc.getElementsByTagName("format");
    NodeList parametersNode = doc.getElementsByTagName("parameters");
    //*/
    //      String xslfile = xslNode.item(0).getTextContent();
    String xslfile = request.getParameter("xsl");
    String format = request.getParameter("format");
    //      String format = formatNode.item(0).getTextContent();
    String parameters = request.getParameter("parameters");
    String documentid = request.getParameter("documentid");
    String portfolios = request.getParameter("portfolioids");
    String[] portfolioid = null;
    if (portfolios != null)
        portfolioid = portfolios.split(";");
    String nodes = request.getParameter("nodeids");
    String[] nodeid = null;
    if (nodes != null)
        nodeid = nodes.split(";");

    System.out.println("PARAMETERS: ");
    System.out.println("xsl: " + xslfile);
    System.out.println("format: " + format);
    System.out.println("user: " + userId);
    System.out.println("portfolioids: " + portfolios);
    System.out.println("nodeids: " + nodes);
    System.out.println("parameters: " + parameters);

    boolean redirectDoc = false;
    if (documentid != null) {
        redirectDoc = true;
        System.out.println("documentid @ " + documentid);
    }

    boolean usefop = false;
    String ext = "";
    if (MimeConstants.MIME_PDF.equals(format)) {
        usefop = true;
        ext = ".pdf";
    } else if (MimeConstants.MIME_RTF.equals(format)) {
        usefop = true;
        ext = ".rtf";
    }
    //// Paramtre portfolio-uuid et file-xsl
    //      String uuid = request.getParameter("uuid");
    //      String xslfile = request.getParameter("xsl");

    StringBuilder aggregate = new StringBuilder();
    try {
        int portcount = 0;
        int nodecount = 0;
        // On aggrge les donnes
        if (portfolioid != null) {
            portcount = portfolioid.length;
            for (int i = 0; i < portfolioid.length; ++i) {
                String p = portfolioid[i];
                String portfolioxml = dataProvider
                        .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0)
                        .toString();
                aggregate.append(portfolioxml);
            }
        }

        if (nodeid != null) {
            nodecount = nodeid.length;
            for (int i = 0; i < nodeid.length; ++i) {
                String n = nodeid[i];
                String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "")
                        .toString();
                aggregate.append(nodexml);
            }
        }

        // Est-ce qu'on a eu besoin d'aggrger les donnes?
        String input = aggregate.toString();
        String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration

        input = input.replaceAll(pattern, "");

        input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet ["
                + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir
                + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \""
                + servletDir + "xhtml-symbol.ent\">"
                + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir
                + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters
                "<root>" + input + "</root>";

        //         System.out.println("INPUT WITH PROXY:"+ input);

        /// Rsolution des proxys
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(input));
        Document doc = documentBuilder.parse(is);

        /// Proxy stuff
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//asmResource[@xsi_type='Proxy']";
        String filterCode = "./code/text()";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        XPathExpression codeFilter = xPath.compile(filterCode);

        for (int i = 0; i < nodelist.getLength(); ++i) {
            Node res = nodelist.item(i);
            Node gp = res.getParentNode(); // resource -> context -> container
            Node ggp = gp.getParentNode();
            Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE);

            /// Fetch node we want to replace
            String returnValue = dataProvider
                    .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "")
                    .toString();

            Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue)));
            Element repNode = rep.getDocumentElement();
            Node proxyNode = repNode.getFirstChild();
            proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned
            //            doc.replaceChild(proxyNode, gp);
            ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work.
            ggp.removeChild(gp);
        }

        try // Convert XML document to string
        {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            writer.flush();
            input = writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }

        //         System.out.println("INPUT DATA:"+ input);

        // Setup a buffer to obtain the content length
        ByteArrayOutputStream stageout = new ByteArrayOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //// Setup Transformer (1st stage)
        /// Base path
        String basepath = xslfile.substring(0, xslfile.indexOf(File.separator));
        String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator
                + "xsl" + File.separator + "html2xml.xsl";
        System.out.println("FIRST: " + firstStage);
        Source xsltSrc1 = new StreamSource(new File(firstStage));
        Transformer transformer1 = transFactory.newTransformer(xsltSrc1);
        StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes()));
        Result stageRes = new StreamResult(stageout);
        transformer1.transform(stageSource, stageRes);

        // Setup Transformer (2nd stage)
        String secondStage = baseDir + File.separator + xslfile;
        Source xsltSrc2 = new StreamSource(new File(secondStage));
        Transformer transformer2 = transFactory.newTransformer(xsltSrc2);

        // Configure parameter from xml
        String[] table = parameters.split(";");
        for (int i = 0; i < table.length; ++i) {
            String line = table[i];
            int var = line.indexOf(":");
            String par = line.substring(0, var);
            String val = line.substring(var + 1);
            transformer2.setParameter(par, val);
        }

        // Setup input
        StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes()));
        //         StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") );

        Result res = null;
        if (usefop) {
            /// FIXME: Might need to include the entity for html stuff?
            //Setup FOP
            //Make sure the XSL transformation's result is piped through to FOP
            Fop fop = fopFactory.newFop(format, out);

            res = new SAXResult(fop.getDefaultHandler());

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        } else {
            res = new StreamResult(out);

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        }

        if (redirectDoc) {

            // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]
            String urlTarget = "http://" + server + "/resources/resource/file/" + documentid;
            System.out.println("Redirect @ " + urlTarget);

            HttpClientBuilder clientbuilder = HttpClientBuilder.create();
            CloseableHttpClient client = clientbuilder.build();

            HttpPost post = new HttpPost(urlTarget);
            post.addHeader("referer", origin);
            String sessionid = request.getSession().getId();
            System.out.println("Session: " + sessionid);
            post.addHeader("Cookie", "JSESSIONID=" + sessionid);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext);

            builder.addPart("uploadfile", body);

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse ret = client.execute(post);
            String stringret = new BasicResponseHandler().handleResponse(ret);

            int code = ret.getStatusLine().getStatusCode();
            response.setStatus(code);
            ServletOutputStream output = response.getOutputStream();
            output.write(stringret.getBytes(), 0, stringret.length());
            output.close();
            client.close();

            /*
            HttpURLConnection connection = CreateConnection( urlTarget, request );
                    
            /// Helping construct Json
            connection.setRequestProperty("referer", origin);
                    
            /// Send post data
            ServletInputStream inputData = request.getInputStream();
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
                    
            byte[] buffer = new byte[1024];
            int dataSize;
            while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
            {
               writer.write(buffer, 0, dataSize);
            }
            inputData.close();
            writer.close();
                    
            RetrieveAnswer(connection, response, origin);
            //*/
        } else {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=generated" + ext);
            response.setContentType(format);
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        String message = e.getMessage();
        response.setStatus(500);
        response.getOutputStream().write(message.getBytes());
        response.getOutputStream().close();

        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }
}

From source file:com.mediaworx.opencms.moduleutils.manifestgenerator.OpenCmsModuleManifestGenerator.java

/**
 * Removes the source node from the given file node (used for siblings).
 * @param fileNode          the file node from which the source node is to be removed
 * @param metaXmlFilePath   path pointing to the VFS file meta file (only used for logging purposes)
 * @throws OpenCmsMetaXmlParseException if the source node can not be found at the expected XPath
 *                                      (see {@link #SOURCE_NODE_XPATH})
 *//*from  w  w w .  j a v  a  2 s  .  c  o m*/
private void removeSourceNodeFromFile(Node fileNode, String metaXmlFilePath)
        throws OpenCmsMetaXmlParseException {
    Node sourceNode;
    try {
        sourceNode = xmlHelper.getSingleNodeForXPath(fileNode, SOURCE_NODE_XPATH);
    } catch (XPathExpressionException e) {
        throw new OpenCmsMetaXmlParseException(
                "Can't remove sibling's source node from " + metaXmlFilePath + " (xpath error)", e);
    }
    sourceNode.getParentNode().removeChild(sourceNode);
}

From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.java

@RequestMapping(value = "/wfs", method = RequestMethod.GET, params = "REQUEST=GetCapabilities")
public ModelAndView doWfsGetCapabilities(@RequestParam("ogpids") Set<String> layerIds,
        HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception {
    logger.info("wfs get capabilities requested");
    List<SolrRecord> solrRecords = null;
    try {/*from www .ja va2s .  co m*/
        solrRecords = this.layerInfoRetriever.fetchAllLayerInfo(layerIds);
    } catch (Exception e) {
        e.printStackTrace();
        throw new ServletException("Unable to retrieve layer info.");
    }
    //need to pass a model to the caps document

    //parse the returned XML
    // Use document builder factory
    DocumentBuilder builder = factory.newDocumentBuilder();

    Map<String, UrlToNameContainer> recordMap = new HashMap<String, UrlToNameContainer>();
    for (SolrRecord solrRecord : solrRecords) {
        //we have to get all of the wfs service points for the passed layerids.  match layerids to service points, so we only have to process each caps document once
        //in the future, we should cache these caps documents
        String workspaceName = solrRecord.getWorkspaceName();
        String layerName = solrRecord.getName();

        String qualifiedName = OgpUtils.getLayerNameNS(workspaceName, layerName);
        String wfsUrl = LocationFieldUtils.getWfsUrl(solrRecord.getLocation());

        URI currentURI = new URI(wfsUrl);
        //is it ok to call these equivalent?
        String currentURIString = currentURI.getScheme() + currentURI.getHost() + currentURI.getPath();
        if (recordMap.containsKey(currentURIString)) {
            UrlToNameContainer urlMap = recordMap.get(currentURIString);
            logger.info(qualifiedName);
            urlMap.qualifiedNames.add(qualifiedName);
        } else {
            UrlToNameContainer urlMap = new UrlToNameContainer();
            urlMap.wfsUrl = wfsUrl;
            Set<String> qNamesSet = new HashSet<String>();
            qNamesSet.add(qualifiedName);
            logger.info(qualifiedName);
            urlMap.qualifiedNames = qNamesSet;

            recordMap.put(currentURIString, urlMap);
        }
    }

    String version = "1.0.0";
    String currentUrl = "";
    String wfsQueryBoilerPlate = "?version=" + version + "&service=wfs";
    String capabilitiesQuery = "&request=GetCapabilities";
    String featureTypeInfo = "";
    for (UrlToNameContainer container : recordMap.values()) {
        //this should happen asynchronously
        currentUrl = container.wfsUrl;
        HttpResponse response = proxyClient
                .execute(new HttpGet(currentUrl + wfsQueryBoilerPlate + capabilitiesQuery));
        InputStream inputStream = response.getEntity().getContent();
        //Parse the document
        Document document = builder.parse(inputStream);
        inputStream.close();

        NodeList layerNodeList = document.getElementsByTagName("Name");
        if (layerNodeList.getLength() == 0) {
            throw new Exception("Malformed GetCapabilities Document.");
        }
        /*
         * <FeatureType><Name>sde:GISPORTAL.GISOWNER01.AFGHANISTANRIVERREGION97</Name><Title>GISPORTAL.GISOWNER01.AFGHANISTANRIVERREGION97</Title><Abstract/><Keywords>ArcSDE, GISPORTAL.GISOWNER01.AFGHANISTANRIVERREGION97</Keywords><SRS>EPSG:100004</SRS><LatLongBoundingBox minx="60.82625305019409" miny="29.95629731861914" maxx="74.6959181471344" maxy="38.59658289704833"/></FeatureType>
         * 
         */
        for (int j = 0; j < layerNodeList.getLength(); j++) {
            Node currentLayerNode = layerNodeList.item(j);
            String layerName = currentLayerNode.getTextContent().toLowerCase();
            if (OgpUtils.getSetAsLowerCase(container.qualifiedNames).contains(layerName)) {
                featureTypeInfo += xmlToString(currentLayerNode.getParentNode());
            }

        }

    }

    String onlineResource = "";
    String describeFeatureUrl = "";
    String getFeatureUrl = "";

    if (recordMap.values().size() == 1) {
        //this is a special case...
        //if every layer is from a single server, pass that server value into the caps doc for describelayer and getfeature.  that way, clients that do the right thing will bypass this ogp service
        //otherwise, everything must be proxied
        onlineResource = currentUrl;
        describeFeatureUrl = currentUrl + wfsQueryBoilerPlate + "&request=DescribeFeatureType";
        getFeatureUrl = currentUrl + wfsQueryBoilerPlate + "&request=GetFeature";
    } else {
        //values for describelayer and getFeature should refer back to this controller
        String thisUrl = servletRequest.getRequestURL().toString() + "?";
        onlineResource = thisUrl + "ogpids=" + servletRequest.getParameter("ogpids");
        describeFeatureUrl = thisUrl + "request=DescribeFeatureType";
        getFeatureUrl = thisUrl + "request=GetFeature";
    }
    ModelAndView mav = new ModelAndView("wfs_caps_1_0_0");

    mav.addObject("onlineResource", StringEscapeUtils.escapeXml(onlineResource));
    mav.addObject("getCapabilities", StringEscapeUtils
            .escapeXml(servletRequest.getRequestURL().toString() + "?" + servletRequest.getQueryString()));
    mav.addObject("describeFeatureUrl", StringEscapeUtils.escapeXml(describeFeatureUrl));
    mav.addObject("getFeatureUrl", StringEscapeUtils.escapeXml(getFeatureUrl));
    mav.addObject("featureTypeInfo", featureTypeInfo);

    servletResponse.setHeader("Content-Disposition", "inline;filename=GetCapabilities.xml");
    return mav;

}

From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java

private String extractWfsFeatureTypeNodes(Document xmlDocument, Set<String> nameList) throws Exception {
    String featureTypeInfo = "";
    NodeList layerNodeList = xmlDocument.getElementsByTagName("Name");
    if (layerNodeList.getLength() == 0) {
        throw new Exception("Malformed GetCapabilities Document.");
    }/*ww w .ja  va  2s .co  m*/
    /*
     * <FeatureType><Name>sde:GISPORTAL.GISOWNER01.AFGHANISTANRIVERREGION97</Name><Title>GISPORTAL.GISOWNER01.AFGHANISTANRIVERREGION97</Title><Abstract/><Keywords>ArcSDE, GISPORTAL.GISOWNER01.AFGHANISTANRIVERREGION97</Keywords><SRS>EPSG:100004</SRS><LatLongBoundingBox minx="60.82625305019409" miny="29.95629731861914" maxx="74.6959181471344" maxy="38.59658289704833"/></FeatureType>
     * 
     */
    for (int j = 0; j < layerNodeList.getLength(); j++) {
        Node currentLayerNode = layerNodeList.item(j);
        String layerName = currentLayerNode.getTextContent().toLowerCase();
        if (OgpUtils.getSetAsLowerCase(nameList).contains(layerName)) {
            featureTypeInfo += xmlToString(currentLayerNode.getParentNode());
        }

    }

    return featureTypeInfo;
}

From source file:org.dozer.eclipse.plugin.sourcepage.hyperlink.DozerClassHyperlinkDetector.java

@SuppressWarnings("restriction")
public final IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
        boolean canShowMultipleHyperlinks) {
    if (region == null || textViewer == null) {
        return null;
    }//from  w ww . j a v a2s  .  c  o m

    IDocument document = textViewer.getDocument();

    Node currentNode = BeansEditorUtils.getNodeByOffset(document, region.getOffset());
    if (currentNode != null) {
        switch (currentNode.getNodeType()) {
        case Node.ELEMENT_NODE:
            // at first try to handle selected attribute value
            Attr currentAttr = BeansEditorUtils.getAttrByOffset(currentNode, region.getOffset());
            IDOMAttr attr = (IDOMAttr) currentAttr;
            if (currentAttr != null && region.getOffset() >= attr.getValueRegionStartOffset()) {
                if (isLinkableAttr(currentAttr)) {
                    IRegion hyperlinkRegion = getHyperlinkRegion(currentAttr);
                    IHyperlink hyperLink = createHyperlink(currentAttr.getName(), currentAttr.getNodeValue(),
                            currentNode, currentNode.getParentNode(), document, textViewer, hyperlinkRegion,
                            region);
                    if (hyperLink != null) {
                        return new IHyperlink[] { hyperLink };
                    }
                }
            }
            break;

        case Node.TEXT_NODE:
            IRegion hyperlinkRegion = getHyperlinkRegion(currentNode);
            Node parentNode = currentNode.getParentNode();
            if (parentNode != null) {
                IHyperlink hyperLink = createHyperlink(parentNode.getNodeName(), currentNode.getNodeValue(),
                        currentNode, parentNode, document, textViewer, hyperlinkRegion, region);
                if (hyperLink != null) {
                    return new IHyperlink[] { hyperLink };
                }
            }
            break;
        }
    }
    return null;
}