Example usage for org.w3c.dom Document getDocumentElement

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

Introduction

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

Prototype

public Element getDocumentElement();

Source Link

Document

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

Usage

From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java

/**
 *
 * @param filePath : file path/*from w w w. ja  v a2  s . c  om*/
 * @param tagName : tag name
 * @param attributeMap : the map of attribute name-value map. Note: no null value contained in this map
 * @return : value of the elements
 */
public static String[] getDataFromXmlByTagNameAndAttributes(String filePath, String tagName,
        Map<String, String> attributeMap) {
    String[] data = null;
    try {
        File file = new File(filePath);

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(file);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName(tagName);

        int length = nList.getLength();

        if (length == 0) {
            return null;
        }

        List<String> dataList = new ArrayList<>();
        for (int temp = 0; temp < length; temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                boolean attrMatched = true;
                Element eElement = (Element) nNode;
                for (String att : attributeMap.keySet()) {
                    String val = attributeMap.get(att);
                    if (!eElement.hasAttribute(att) || !val.equals(eElement.getAttribute(att))) {
                        attrMatched = false;
                    }
                }
                if (attrMatched == true) {
                    dataList.add(eElement.getTextContent());
                }
            }
        }

        int size = dataList.size();
        data = new String[size];
        data = dataList.toArray(data);

    } catch (ParserConfigurationException | SAXException | IOException | DOMException ex) {
        logger.error("Cannot get the data from file at " + filePath + " by tag name " + tagName
                + " and attributes map", ex);
    }
    return data;
}

From source file:com.ibm.sbt.sample.web.util.SnippetFactory.java

private static JSSnippet createSnippetFromXml(String xml) {
    try {//  ww w. ja  v  a  2s.  c o m
        Document document = DOMUtil.createDocument(xml);
        XResult unid = DOMUtil.evaluateXPath(document, "unid");
        XResult js = DOMUtil.evaluateXPath(document.getDocumentElement(), "js");
        XResult html = DOMUtil.evaluateXPath(document.getDocumentElement(), "html");
        XResult css = DOMUtil.evaluateXPath(document.getDocumentElement(), "css");
        XResult docHtml = DOMUtil.evaluateXPath(document.getDocumentElement(), "docHtml");
        XResult theme = DOMUtil.evaluateXPath(document.getDocumentElement(), "theme");
        XResult description = DOMUtil.evaluateXPath(document.getDocumentElement(), "description");
        XResult tags = DOMUtil.evaluateXPath(document.getDocumentElement(), "tags");
        XResult labels = DOMUtil.evaluateXPath(document.getDocumentElement(), "labels");

        JSSnippet snippet = new JSSnippet();
        if (unid != null)
            snippet.setUnid(unid.getStringValue());
        if (js != null)
            snippet.setJs(js.getStringValue());
        if (html != null)
            snippet.setHtml(html.getStringValue());
        if (css != null)
            snippet.setCss(css.getStringValue());
        if (docHtml != null)
            snippet.setDocHtml(docHtml.getStringValue());

        Properties p = new Properties();
        snippet.init(p);

        if (theme != null && theme.getStringValue() != null)
            snippet.setTheme(theme.getStringValue());
        if (description != null && description.getStringValue() != null)
            snippet.setDescription(description.getStringValue());
        if (tags != null && tags.getValues() != null)
            snippet.setTags(tags.getValues());
        if (labels != null && labels.getValues() != null)
            snippet.setLabels(labels.getValues());

        return snippet;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.openremote.android.console.net.ORControllerServerSwitcher.java

/**
 * Detect the groupmembers of current server url
 *//*from   w  w  w .  j  ava2  s  .  c  o  m*/
public static boolean detectGroupMembers(Context context) {
    Log.i(LOG_CATEGORY, "Detecting group members with current controller server url "
            + AppSettingsModel.getCurrentServer(context));

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);
    HttpClient httpClient = new DefaultHttpClient(params);
    String url = AppSettingsModel.getSecuredServer(context);
    HttpGet httpGet = new HttpGet(url + "/rest/servers");

    if (httpGet == null) {
        Log.e(LOG_CATEGORY, "Create HttpRequest fail.");

        return false;
    }

    SecurityUtil.addCredentialToHttpRequest(context, httpGet);

    // TODO : fix the exception handling in this method -- it is ridiculous.

    try {
        URL uri = new URL(url);

        if ("https".equals(uri.getProtocol())) {
            Scheme sch = new Scheme(uri.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                    uri.getPort());
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        }

        HttpResponse httpResponse = httpClient.execute(httpGet);

        try {
            if (httpResponse.getStatusLine().getStatusCode() == Constants.HTTP_SUCCESS) {
                InputStream data = httpResponse.getEntity().getContent();

                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document dom = builder.parse(data);
                    Element root = dom.getDocumentElement();

                    NodeList nodeList = root.getElementsByTagName("server");
                    int nodeNums = nodeList.getLength();
                    List<String> groupMembers = new ArrayList<String>();

                    for (int i = 0; i < nodeNums; i++) {
                        groupMembers.add(nodeList.item(i).getAttributes().getNamedItem("url").getNodeValue());
                    }

                    Log.i(LOG_CATEGORY, "Detected groupmembers. Groupmembers are " + groupMembers);

                    return saveGroupMembersToFile(context, groupMembers);
                } catch (IOException e) {
                    Log.e(LOG_CATEGORY, "The data is from ORConnection is bad", e);
                } catch (ParserConfigurationException e) {
                    Log.e(LOG_CATEGORY, "Cant build new Document builder", e);
                } catch (SAXException e) {
                    Log.e(LOG_CATEGORY, "Parse data error", e);
                }
            }

            else {
                Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error");
            }
        }

        catch (IllegalStateException e) {
            Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error", e);
        }

        catch (IOException e) {
            Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error", e);
        }

    }

    catch (MalformedURLException e) {
        Log.e(LOG_CATEGORY, "Create URL fail:" + url);
    }

    catch (ConnectException e) {
        Log.e(LOG_CATEGORY, "Connection refused: " + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (ClientProtocolException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (SocketTimeoutException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (IOException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (IllegalArgumentException e) {
        Log.e(LOG_CATEGORY, "Host name can be null :" + AppSettingsModel.getCurrentServer(context), e);
    }

    return false;
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @return//from www  .j ava2 s . c o  m
 * @throws IOException 
 * @throws DomException 
 * @throws BosMemberValidationException 
 */
static Element getCommentTemplate(URL commentsUrl, BosConstructionOptions bosOptions)
        throws IOException, BosMemberValidationException, DomException {
    InputSource commentsTemplateXmlSource = new InputSource(commentsUrl.openStream());
    commentsTemplateXmlSource.setSystemId(DocxConstants.COMMENTS_XML_PATH);
    Document commentsTemplateDom = DomUtil.getDomForSource(commentsTemplateXmlSource, bosOptions, false, false);
    NodeList comments = commentsTemplateDom.getDocumentElement()
            .getElementsByTagNameNS(DocxConstants.nsByPrefix.get("w"), "comment");
    Element commentTemplate = (Element) comments.item(0);
    return commentTemplate;
}

From source file:eidassaml.starterkit.EidasRequest.java

public static EidasRequest Parse(InputStream is, List<X509Certificate> authors)
        throws XMLParserException, UnmarshallingException, ErrorCodeException, IOException {
    EidasRequest eidasReq = new EidasRequest();
    BasicParserPool ppMgr = new BasicParserPool();
    ppMgr.setNamespaceAware(true);/*from ww w  .ja v  a2  s .  com*/

    Document inCommonMDDoc = ppMgr.parse(is);

    Element metadataRoot = inCommonMDDoc.getDocumentElement();
    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot);
    eidasReq.request = (AuthnRequest) unmarshaller.unmarshall(metadataRoot);

    if (authors != null) {
        CheckSignature(eidasReq.request.getSignature(), authors);
    }

    //isPassive SHOULD be false
    if (!eidasReq.request.isPassive()) {
        eidasReq.setPassive(eidasReq.request.isPassive());
    } else {
        throw new ErrorCodeException(ErrorCode.ILLEGAL_REQUEST_SYNTAX,
                "Unsupported IsPassive value:" + eidasReq.request.isPassive());
    }

    //forceAuthn MUST be true
    if (eidasReq.request.isForceAuthn()) {
        eidasReq.setIsForceAuthn(eidasReq.request.isForceAuthn());
    } else {
        throw new ErrorCodeException(ErrorCode.ILLEGAL_REQUEST_SYNTAX,
                "Unsupported ForceAuthn value:" + eidasReq.request.isForceAuthn());
    }

    eidasReq.id = eidasReq.request.getID();
    //there should be one AuthnContextClassRef
    AuthnContextClassRef ref = eidasReq.request.getRequestedAuthnContext().getAuthnContextClassRefs().get(0);
    if (null != ref) {
        eidasReq.authClassRef = EidasLoA.GetValueOf(ref.getDOM().getTextContent());
    } else {
        throw new ErrorCodeException(ErrorCode.ILLEGAL_REQUEST_SYNTAX, "No AuthnContextClassRef element.");
    }
    String namiIdformat = eidasReq.request.getNameIDPolicy().getFormat();
    eidasReq.nameIdPolicy = EidasNameIdType.GetValueOf(namiIdformat);

    eidasReq.issueInstant = SimpleDf.format(eidasReq.request.getIssueInstant().toDate());
    eidasReq.issuer = eidasReq.request.getIssuer().getDOM().getTextContent();
    eidasReq.destination = eidasReq.request.getDestination();

    if (null != eidasReq.request.getProviderName() && !eidasReq.request.getProviderName().isEmpty()) {
        eidasReq.providerName = eidasReq.request.getProviderName();
    } else {
        throw new ErrorCodeException(ErrorCode.ILLEGAL_REQUEST_SYNTAX, "No providerName attribute.");
    }

    eidasReq.selectorType = null;
    for (XMLObject extension : eidasReq.request.getExtensions().getOrderedChildren()) {
        if ("RequestedAttributes".equals(extension.getElementQName().getLocalPart())) {
            for (XMLObject attribute : extension.getOrderedChildren()) {
                Element el = attribute.getDOM();
                EidasPersonAttributes eidasPersonAttributes = getEidasPersonAttributes(el);
                if (null != eidasPersonAttributes) {
                    eidasReq.requestedAttributes.put(eidasPersonAttributes,
                            Boolean.parseBoolean(el.getAttribute("isRequired")));
                }
            }
        } else if ("SPType".equals(extension.getElementQName().getLocalPart())) {
            eidasReq.selectorType = EidasRequestSectorType.GetValueOf(extension.getDOM().getTextContent());
        }
    }
    if (!containsMinimumDataSet(eidasReq.requestedAttributes)) {
        throw new ErrorCodeException(ErrorCode.ILLEGAL_REQUEST_SYNTAX,
                "Request does not contain minimum dataset.");
    }
    return eidasReq;
}

From source file:com.viettel.ws.client.JDBCUtil.java

/**
 * Create document using DOM api//  w w w . j  a  v  a  2  s.c  o  m
 *
 * @param rs a result set
 * @param doc a input document for append content
 * @param rsName name of the appended element
 * @return a document after append content
 * @throws ParserConfigurationException If error when parse XML string
 * @throws SQLException If error when read data from database
 */
public static Document add2Document(List<Object> rs, Document doc, String rsName)
        throws ParserConfigurationException, SQLException {

    if (rs == null) {
        return doc;
    }

    //Get root element
    Element root = doc.getDocumentElement();
    Element rsElement = doc.createElement(rsName);
    root.appendChild(rsElement);

    for (Object object : rs) {
        Element row = createRowElement(object, doc);
        rsElement.appendChild(row);
    }

    return doc;
}

From source file:de.bund.bfr.knime.pmm.common.chart.ChartUtilities.java

public static SvgImageContent convertToSVGImageContent(JFreeChart chart, int width, int height) {
    SVGDOMImplementation domImpl = new SVGDOMImplementation();
    Document document = domImpl.createDocument(null, "svg", null);
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    svgGenerator.setSVGCanvasSize(new Dimension(width, height));

    if (chart != null) {
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height));
    }/*w w  w. j  a v a 2 s  . com*/

    svgGenerator.finalize();
    document.replaceChild(svgGenerator.getRoot(), document.getDocumentElement());

    return new SvgImageContent((SVGDocument) document, true);
}

From source file:com.google.enterprise.adaptor.experimental.Sim.java

/** Find all record urls in Adaptor created XML metadata-and-url feed file. */
static Set<URL> extractUrls(String xml) throws SAXException, ParserConfigurationException, BadFeed {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    /* to avoid blowing up on doctype line:
     * http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references */
    dbf.setValidating(false);// w  ww .j a va2 s.  co m
    dbf.setFeature("http://xml.org/sax/features/namespaces", false);
    dbf.setFeature("http://xml.org/sax/features/validation", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputStream xmlStream = new ByteArrayInputStream(xml.getBytes(UTF8));
    Document doc;
    try {
        doc = db.parse(xmlStream);
    } catch (IOException ie) {
        throw new BadFeed(ie.getMessage());
    }
    doc.getDocumentElement().normalize();
    NodeList nodes = doc.getElementsByTagName("record");
    Set<URL> tmpUrls = new HashSet<URL>();
    for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        String url = element.getAttribute("url");
        if (null == url || url.trim().isEmpty()) {
            throw new BadFeed("record without url attribute");
        } else {
            try {
                tmpUrls.add(new URL(url));
            } catch (MalformedURLException male) {
                throw new BadFeed("record with bad url attribute: " + url);
            }
        }
        log.info("accepting url: " + url);
    }
    return tmpUrls;
}

From source file:ambit.data.qmrf.QMRFConverter.java

public static ArrayList findNodeIDRef(String name_node, String ref_name, String catalog_name,
        org.w3c.dom.Document source) throws Exception {

    source.getDocumentElement();
    ArrayList return_list = new ArrayList();
    NodeList objCatNodes = source.getElementsByTagName(name_node);

    Node objNode = objCatNodes.item(0);
    NodeList objNodes = objNode.getChildNodes();
    for (int i = 0; i < objNodes.getLength(); i = i + 1) {

        if (objNodes.item(i).getNodeName().equals(ref_name)) {
            NamedNodeMap objAttributes = objNodes.item(i).getAttributes();
            Node attribute = objAttributes.getNamedItem("idref");
            //attribute.getNodeValue()
            NodeList objNodesAuthor = source.getElementsByTagName(catalog_name);
            for (int j = 0; j < objNodesAuthor.getLength(); j = j + 1) {
                String id = objNodesAuthor.item(j).getAttributes().getNamedItem("id").getNodeValue();
                if (id.equals(attribute.getNodeValue())) {
                    //Node name = objNodesAuthor.item(j).getAttributes().getNamedItem(xml_attribute_name);
                    return_list.add(objNodesAuthor.item(j));
                }/* w  w w  .j  a  v a 2  s.  co  m*/

            }

        }

    }
    return return_list;
}

From source file:at.ac.dbisinformatik.snowprofile.web.svgcreator.SVGCreator.java

/**
 * creates a SVG-Graph for given jsonDocument which includes ExtJS-SVG-Objects. The created SVG-Document will be converted in the given export type. 
 * // w  ww . j  a  v  a2s.  com
 * @param jsonDocument
 * @param exportType
 * @param profileID
 * @return
 * @throws TransformerException
 * @throws URISyntaxException
 * @throws TranscoderException
 * @throws IOException
 */
public static ByteArrayOutputStream svgDocument(JsonArray jsonDocument, String exportType, String profileID)
        throws TransformerException, URISyntaxException, TranscoderException, IOException {

    ByteArrayOutputStream ret = null;

    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
    Document doc = impl.createDocument(svgNS, "svg", null);

    // Get the root element (the 'svg' element).
    Element svgRoot = doc.getDocumentElement();

    // Set the width and height attributes on the root 'svg' element.
    svgRoot.setAttributeNS(null, "width", "1500");
    svgRoot.setAttributeNS(null, "height", "1500");
    JsonArray items = jsonDocument;

    for (int i = 0; i < items.size(); ++i) {
        String type = items.get(i).getAsJsonObject().get("type").getAsString();
        Element element = null;
        org.w3c.dom.Text test = null;
        String path = "";
        String width = "";
        String height = "";
        String x = "";
        String y = "";
        String fill = "";
        String text = "";
        String font = "";
        String fontFamily = "";
        String fontSize = "";
        String degrees = "";
        String stroke = "";
        String opacity = "";
        String src = "";
        switch (type) {
        case "rect":
            width = items.get(i).getAsJsonObject().get("width").getAsString();
            height = items.get(i).getAsJsonObject().get("height").getAsString();
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            stroke = items.get(i).getAsJsonObject().get("stroke").getAsString();
            opacity = items.get(i).getAsJsonObject().get("opacity").getAsString();

            // Create the rectangle.
            element = doc.createElementNS(svgNS, "rect");
            element.setAttributeNS(null, "width", width);
            element.setAttributeNS(null, "height", height);
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "stroke", stroke);
            element.setAttributeNS(null, "opacity", opacity);
            break;

        case "path":
            path = items.get(i).getAsJsonObject().get("path").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            stroke = items.get(i).getAsJsonObject().get("stroke").getAsString();

            // Create the path.
            element = doc.createElementNS(svgNS, "path");
            element.setAttributeNS(null, "d", path);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "stroke", stroke);
            break;

        case "image":
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();
            width = items.get(i).getAsJsonObject().get("width").getAsString();
            height = items.get(i).getAsJsonObject().get("height").getAsString();
            src = System.class.getResource("/at/ac/dbisinformatik/snowprofile/web/resources/"
                    + items.get(i).getAsJsonObject().get("src").getAsString()).toString();

            // Create the path.
            element = doc.createElementNS(svgNS, "image");
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            element.setAttributeNS(null, "width", width);
            element.setAttributeNS(null, "height", height);
            element.setAttributeNS(null, "xlink:href", src);
            break;

        case "text":
            text = items.get(i).getAsJsonObject().get("text").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            font = items.get(i).getAsJsonObject().get("font").getAsString();
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();

            // Transformation
            if (items.get(i).getAsJsonObject().get("rotate") != null) {
                JsonObject temp = items.get(i).getAsJsonObject().get("rotate").getAsJsonObject();
                degrees = temp.get("degrees").getAsString();
            }

            fontSize = font.split(" ")[0];
            fontFamily = font.split(" ")[1];

            // Create the text.
            test = doc.createTextNode(text);
            element = doc.createElementNS(svgNS, "text");
            element.setAttributeNS(null, "text", text);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "font-family", fontFamily);
            element.setAttributeNS(null, "font-size", fontSize);
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            if (!degrees.equals("")) {
                // element.setAttributeNS(null, "transform",
                // "rotate(270 "+500+","+80+")");
            }
            element.appendChild(test);
            break;

        default:
            break;
        }

        // Attach the rectangle to the root 'svg' element.
        svgRoot.appendChild(element);
    }

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

    DOMSource source = new DOMSource(doc);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(outputStream);
    transformer.transform(source, result);
    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

    switch (exportType) {
    case "png":
        ret = createPNG(inputStream);
        break;

    case "jpg":
        ret = createJPG(inputStream);
        break;

    case "pdf":
        ret = createPDF(inputStream);
        break;

    default:
        break;
    }
    return ret;
}