Example usage for org.w3c.dom Node hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:org.apache.openaz.xacml.std.json.JSONResponse.java

/**
 * Read characters from the given <code>InputStream</code> and parse them into an XACML
 * {@link org.apache.openaz.xacml.api.Request} object.
 *
 * @param is/*from  w ww.  j  a  v a2s. c  om*/
 * @return
 * @throws JSONStructureException
 */
public static Response load(InputStream is) throws JSONStructureException {

    // TODO - ASSUME that order of members within an object does not matter (Different from XML, in JSON
    // everything is handled as Maps so order does not matter)

    // ensure shorthand map is set up
    if (shorthandMap == null) {
        initShorthandMap();
    }

    // ensure that we have an instance of the DataTypeFactory for generating AttributeValues by DataType
    if (dataTypeFactory == null) {
        try {
            dataTypeFactory = DataTypeFactory.newInstance();
            if (dataTypeFactory == null) {
                throw new NullPointerException("No DataTypeFactory found");
            }
        } catch (FactoryException e) {
            throw new JSONStructureException("Unable to find DataTypeFactory, e=" + e);
        }
    }

    // create a new Response object to be filled in
    StdMutableResponse stdMutableResponse = null;

    String json = null;
    ObjectMapper mapper = null;
    try {

        // read the inputStream into a buffer (trick found online scans entire input looking for
        // end-of-file)
        java.util.Scanner scanner = new java.util.Scanner(is);
        scanner.useDelimiter("\\A");
        json = scanner.hasNext() ? scanner.next() : "";
        scanner.close();

        mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

        // TODO - ASSUME that any duplicated component is a bad thing (probably indicating an error in the
        // incoming JSON)
        mapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true);

        Map<?, ?> root = mapper.readValue(json, Map.class);

        //
        // Does the Response exist?
        //
        List<?> resultList = (List<?>) root.remove("Response");
        if (resultList == null) {
            throw new JSONStructureException("No \"Response\" property found.");
        }

        checkUnknown("Top-level message", root);

        stdMutableResponse = new StdMutableResponse();

        // handle each Result object
        for (int resultIndex = 0; resultIndex < resultList.size(); resultIndex++) {
            // each item should be a Map<?,?> containing a Result, otherwise it is an error
            Object resultObj = resultList.get(resultIndex);
            if (resultObj == null || !(resultObj instanceof Map)) {
                throw new JSONStructureException(
                        "Response contains null Result or list instead of Result object");
            }

            StdMutableResult stdMutableResult = new StdMutableResult();

            Map<?, ?> resultMap = (Map<?, ?>) resultObj;

            // Must have a Decision
            Object decisionObject = resultMap.remove("Decision");
            if (decisionObject == null) {
                throw new JSONStructureException("Result must have Decision");
            }
            Decision decision = Decision.get(decisionObject.toString());
            if (decision == null) {
                throw new JSONStructureException(
                        "Unknown value for Decision: '" + decisionObject.toString() + "'");
            }
            stdMutableResult.setDecision(decision);

            // may have Status
            Object statusObject = resultMap.remove("Status");
            if (statusObject != null) {
                if (!(statusObject instanceof Map)) {
                    throw new JSONStructureException(
                            "Status must be an object, not type '" + statusObject.getClass().getName() + "'");
                }
                StdMutableStatus stdMutableStatus = new StdMutableStatus();
                Map<?, ?> statusMap = (Map<?, ?>) statusObject;

                // optional message
                Object messageObject = statusMap.remove("StatusMessage");
                if (messageObject != null) {
                    stdMutableStatus.setStatusMessage(messageObject.toString());
                }

                // optional detail
                Object detailObject = statusMap.remove("StatusDetail");
                if (detailObject != null) {
                    StdMutableStatusDetail statusDetail = new StdMutableStatusDetail();
                    // TODO - PROBLEM: The JSON spec says only that the status Detail is raw XML rather
                    // than a JSON object. Therefore we cannot discriminate what is inside the string we
                    // just got.
                    // TODO Fortunately there is only one thing it can be: a MissingAttributeDetail.
                    // TODO Unfortunately the MissingAttributeDetail contains multiple optional elements
                    // including 0 or more values, which makes it non-trivial to parse the XML
                    // representation.
                    // TODO Unfortunately the JSON spec does not say how the XML is formatted
                    // (with/without whitespace, etc).

                    //
                    // First of all, the String is possible escaped.
                    //
                    // The meaning of "escaped" is defined in section 4.2.3.1 in the JSON spec
                    //
                    String unescapedContent = detailObject.toString().replace("\\\"", "\"");
                    unescapedContent = unescapedContent.replace("\\\\", "\\");

                    // need to add a root element so that the MissingAttributeDetail elements are findable
                    unescapedContent = "<ROOT>" + unescapedContent + "</ROOT>";

                    // logger.info("Escaped content: \n" + unescapedContent);
                    Document doc = null;
                    try (InputStream bis = new ByteArrayInputStream(unescapedContent.getBytes("UTF-8"))) {
                        doc = DOMUtil.loadDocument(bis);
                    } catch (Exception ex) {
                        throw new JSONStructureException(
                                "Unable to parse Content '" + detailObject.toString() + "'");
                    }

                    // ASSUME that this can only be an array of MissingAttributeDetail. Example:
                    // <MissingAttributeDetail
                    // Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"
                    // AttributeId="urn:att:xacml:resource:application:motsid"
                    // DataType="http://www.w3.org/2001/XMLSchema#integer">
                    // <AttributeValue
                    // DataType="http://www.w3.org/2001/XMLSchema#integer">56</AttributeValue>
                    // </MissingAttributeDetail>"
                    Element docElement = doc.getDocumentElement();
                    NodeList missingAttributeDetailList = docElement
                            .getElementsByTagName("MissingAttributeDetail");
                    for (int madNodeIndex = 0; madNodeIndex < missingAttributeDetailList
                            .getLength(); madNodeIndex++) {
                        Node madNode = missingAttributeDetailList.item(madNodeIndex);
                        StdMutableMissingAttributeDetail mutableMAD = new StdMutableMissingAttributeDetail();

                        NamedNodeMap attributeMap = madNode.getAttributes();
                        Node attributeNode = attributeMap.getNamedItem("AttributeId");
                        if (attributeNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing AttributeId");
                        }
                        mutableMAD.setAttributeId(new IdentifierImpl(attributeNode.getNodeValue()));
                        Node categoryNode = attributeMap.getNamedItem("Category");
                        if (categoryNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing Category");
                        }
                        mutableMAD.setCategory(new IdentifierImpl(categoryNode.getNodeValue()));
                        Node dataTypeNode = attributeMap.getNamedItem("DataType");
                        if (dataTypeNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing DataType");
                        }
                        mutableMAD.setDataTypeId(new IdentifierImpl(dataTypeNode.getNodeValue()));
                        Node issuerNode = attributeMap.getNamedItem("Issuer");
                        if (issuerNode != null) {
                            mutableMAD.setIssuer(issuerNode.getNodeValue());
                        }

                        // get any value elements
                        NodeList childNodeList = madNode.getChildNodes();
                        for (int childIndex = 0; childIndex < childNodeList.getLength(); childIndex++) {
                            Node childNode = childNodeList.item(childIndex);
                            if (!childNode.getNodeName().equals("AttributeValue")) {
                                continue;
                            }
                            Node childDataTypeNode = childNode.getAttributes().getNamedItem("DataType");
                            if (childDataTypeNode == null) {
                                throw new JSONStructureException(
                                        "MissingAttributeDetail contains AttributeValue '"
                                                + childNode.getNodeValue() + "' with no DataType");
                            }
                            String dataType = childDataTypeNode.getNodeValue();
                            // this probably is not a shorthand, but look it up anyway. The full Ids are
                            // in the table too.
                            Identifier valueDataTypeId = shorthandMap.get(dataType);
                            if (valueDataTypeId == null) {
                                throw new JSONStructureException(
                                        "MissingAttibuteDetail contains AttributeValue with unknown DataType="
                                                + dataType);
                            }
                            // if Id is known then it is reasonable to do the following without checking
                            DataType<?> valueDataType = dataTypeFactory.getDataType(valueDataTypeId);
                            AttributeValue<?> attributeValue;
                            try {
                                // for some reason the value may be the value of a child of this node
                                // rather than the value of this node itself.
                                Node valueNode = childNode;
                                if (valueNode.hasChildNodes()) {
                                    valueNode = valueNode.getFirstChild();
                                }
                                attributeValue = valueDataType.createAttributeValue(valueNode.getNodeValue());
                            } catch (Exception ex) {
                                throw new JSONStructureException(
                                        "Unable to create AttributeValue from MissingAttributeDetail AttributeValue '"
                                                + childNode.getNodeValue() + "', error was: "
                                                + ex.getMessage());
                            }
                            mutableMAD.addAttributeValue(attributeValue);
                        }

                        statusDetail.addMissingAttributeDetail(mutableMAD);
                    }

                    stdMutableStatus.setStatusDetail(statusDetail);
                }

                // optional StatusCode which may contain recursive child StatusCode
                Object statusCodeObject = statusMap.remove("StatusCode");
                if (statusCodeObject != null) {
                    if (!(statusCodeObject instanceof Map)) {
                        throw new JSONStructureException("StatusCode must be object");
                    }
                    StatusCode statusCode = parseStatusCode((Map<?, ?>) statusCodeObject);
                    stdMutableStatus.setStatusCode(statusCode);
                }

                checkUnknown("Status", statusMap);

                stdMutableResult.setStatus(stdMutableStatus);
            }

            // may have Obligations
            Object obligationsObject = resultMap.remove("Obligations");
            if (obligationsObject != null) {
                parseObligationsOrAdvice(obligationsObject, stdMutableResult, true);
            }

            // may have Advice
            Object adviceObject = resultMap.remove("AssociatedAdvice");
            if (adviceObject != null) {
                parseObligationsOrAdvice(adviceObject, stdMutableResult, false);
            }

            // may have Category (a.k.a Attributes)
            // TODO - POSSIBLE NAME CHANGE - XML core calls this "Attributes", but name in JSON standard
            // is questionable.
            // TODO The variables here are named "Attributes" because that is the internal name in our
            // objects (based on the Core spec).
            Object attributesObject = resultMap.remove("Category");
            if (attributesObject != null) {
                if (!(attributesObject instanceof List)) {
                    throw new JSONStructureException("Category must be list");
                }
                List<?> attributesList = (List<?>) attributesObject;

                for (Object categoryObject : attributesList) {
                    if (categoryObject == null || !(categoryObject instanceof Map)) {
                        throw new JSONStructureException("Category array item must be object");
                    }
                    Map<?, ?> categoryMap = (Map<?, ?>) categoryObject;
                    StdMutableAttributeCategory stdMutableAttributeCategory = new StdMutableAttributeCategory();

                    // mandatory CategoryId
                    Object categoryIdObject = categoryMap.remove("CategoryId");
                    if (categoryIdObject == null) {
                        throw new JSONStructureException("Category array item must contain CategoryId");
                    }
                    Identifier categoryId = new IdentifierImpl(categoryIdObject.toString());

                    stdMutableAttributeCategory.setCategory(categoryId);

                    // optional Attributes
                    Object attributeListObject = categoryMap.remove("Attribute");
                    if (attributeListObject != null) {
                        if (!(attributeListObject instanceof List)) {
                            throw new JSONStructureException("Category memeber Attribute must be list");
                        }
                        List<?> attributeList = (List<?>) attributeListObject;
                        // get each attribute and add to category
                        for (Object attributeMapObject : attributeList) {
                            if (attributeMapObject == null || !(attributeMapObject instanceof Map)) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item must be object");
                            }
                            Map<?, ?> attributeMap = (Map<?, ?>) attributeMapObject;

                            StdMutableAttribute stdMutableAttribute = new StdMutableAttribute();

                            // optional IncludeInResult
                            // TODO - Odd situation!!: We are reading a string representing a Result which
                            // includes Attributes.
                            // TODO In this case, what does it mean if "IncludeInResult=false"?
                            // TODO The Attribute is obviously included in this Result because it is in
                            // the file/string we are reading.
                            // TODO Our choice: Always include the Attribute. If the IncludeInResult is
                            // included in the input, set it's value in the object as directed.
                            // TODO This may cause mismatches between a Result read in and a new text
                            // generated from the internal Result object.
                            Object includeInResultObject = attributeMap.remove("IncludeInResult");
                            // the fact that the attribute is in the input means this should be true
                            stdMutableAttribute.setIncludeInResults(true);
                            if (includeInResultObject != null) {
                                // need to check the value in the input
                                try {
                                    boolean include = DataTypes.DT_BOOLEAN.convert(includeInResultObject)
                                            .booleanValue();
                                    // set the value in the object exactly as directed, whether it makes
                                    // sense or not
                                    stdMutableAttribute.setIncludeInResults(include);
                                } catch (DataTypeException e) {
                                    throw new JSONStructureException(
                                            "Category member Attribute list item has IncludeInResult value '"
                                                    + includeInResultObject.toString()
                                                    + "' which is not boolean");
                                }
                            }

                            // category is not part of Attribute in spec - it is used internally to link
                            // attribute to Category
                            stdMutableAttribute.setCategory(categoryId);

                            // mandatory Id
                            Object aaIdObject = attributeMap.remove("AttributeId");
                            if (aaIdObject == null) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item missing AttributeId");
                            }
                            stdMutableAttribute.setAttributeId(new IdentifierImpl(aaIdObject.toString()));

                            // get the optional DataType so we know what to do with the mandatory value
                            Object dataTypeObject = attributeMap.remove("DataType");
                            Identifier dataTypeId = null;
                            if (dataTypeObject != null) {
                                dataTypeId = shorthandMap.get(dataTypeObject.toString());
                                // if there was a DataType given it must be a real one
                                if (dataTypeId == null) {
                                    throw new JSONStructureException(
                                            "Category member Attribute list item has unknown DataType='"
                                                    + dataTypeObject.toString() + "'");
                                }
                            } else {
                                // if DataType not given, use String
                                dataTypeId = DataTypes.DT_STRING.getId();
                            }

                            // mandatory Value
                            Object valueObject = attributeMap.remove("Value");
                            if (valueObject == null) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item missing Value");
                            }
                            AttributeValue<?> attributeValue = null;
                            try {
                                DataType<?> dataType = new StdDataTypeFactory().getDataType(dataTypeId);
                                if (dataType == DataTypes.DT_XPATHEXPRESSION) {
                                    // XPAthExpressions are complex data types that need special
                                    // translation from the JSON form to the internal form
                                    attributeValue = convertMapToXPathExpression(valueObject);

                                } else {
                                    // everything other than XPathExpressions are simple values that the
                                    // DataTypes know how to handle
                                    attributeValue = dataType.createAttributeValue(valueObject);
                                }
                            } catch (DataTypeException e) {
                                throw new JSONStructureException("Category member Attribute list item Value='"
                                        + valueObject.toString() + "' not of type '" + dataTypeId + "'");
                            }
                            stdMutableAttribute.addValue(attributeValue);

                            // optional Issuer
                            Object issuerObject = attributeMap.remove("Issuer");
                            if (issuerObject != null) {
                                stdMutableAttribute.setIssuer(issuerObject.toString());
                            }

                            checkUnknown("Category Attribute list item", attributeMap);
                            stdMutableAttributeCategory.add(stdMutableAttribute);
                        }
                    }

                    checkUnknown("Category", categoryMap);

                    // if none of the attributes are returned, do not return the category either
                    if (stdMutableAttributeCategory.getAttributes().size() > 0) {
                        stdMutableResult.addAttributeCategory(stdMutableAttributeCategory);
                    }
                }
            }

            // may have PolicyIdentifierList
            Object policyIdObject = resultMap.remove("PolicyIdentifier");
            if (policyIdObject != null) {
                if (!(policyIdObject instanceof Map)) {
                    throw new JSONStructureException("PolicyIdentifier must be object");
                }
                Map<?, ?> policyIdMap = (Map<?, ?>) policyIdObject;

                // optional PolicyIdReference list
                Object policyIdReferenceObject = policyIdMap.remove("PolicyIdReference");
                if (policyIdReferenceObject != null) {
                    parseIdReferences(policyIdReferenceObject, stdMutableResult, false);
                }

                // optional PolicySetIdReferenceList
                Object policySetIdReferenceObject = policyIdMap.remove("PolicySetIdReference");
                if (policySetIdReferenceObject != null) {
                    parseIdReferences(policySetIdReferenceObject, stdMutableResult, true);
                }

                checkUnknown("PolicyIdentifier", policyIdMap);

            }

            checkUnknown("Result", resultMap);

            // add this result to the Response
            stdMutableResponse.add(stdMutableResult);

        }

        return stdMutableResponse;

    } catch (JsonParseException e) {
        throw new JSONStructureException("Unable to parse JSON '" + json + "', exception: " + e, e);
    } catch (JsonMappingException e) {
        throw new JSONStructureException("Unable to map JSON '" + json + "', exception: " + e, e);
    } catch (IOException e) {
        throw new JSONStructureException("Unable to read JSON input, exception: " + e, e);
    }

    // all done
    // return new StdRequest(stdMutableRequest);

    // throw new JSONStructureException("JSONResponse load string and load from file not implemented");
}

From source file:org.apache.xml.security.encryption.XMLCipher.java

/**
 * Removes the contents of a <code>Node</code>.
 *
 * @param node the <code>Node</code> to clear.
 *///  w  w w. ja v a  2  s .c  o  m
private static void removeContent(Node node) {
    while (node.hasChildNodes()) {
        node.removeChild(node.getFirstChild());
    }
}

From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java

@Override
protected int saveStructure(Node node, PreparedStatement structStmt, PreparedStatement parmStmt)
        throws SQLException {
    if (node == null) { // No more
        return 0;
    }/*ww w  . j  a  v a2  s .  com*/
    if (node.getNodeName().equals("parameter")) {
        //parameter, skip it and go on to the next node
        return this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    }
    if (!(node instanceof Element)) {
        return 0;
    }

    final Element structure = (Element) node;

    if (logger.isDebugEnabled()) {
        logger.debug("saveStructure XML content: {}", XmlUtilitiesImpl.toString(node));
    }

    // determine the struct_id for storing in the db. For incorporated nodes in
    // the plf their ID is a system-wide unique ID while their struct_id for
    // storing in the db is cached in a dlm:plfID attribute.
    int saveStructId = -1;
    final String plfID = structure.getAttribute(Constants.ATT_PLF_ID);

    if (!plfID.equals("")) {
        saveStructId = Integer.parseInt(plfID.substring(1));
    } else {
        final String id = structure.getAttribute("ID");
        saveStructId = Integer.parseInt(id.substring(1));
    }

    int nextStructId = 0;
    int childStructId = 0;
    int chanId = -1;
    IPortletDefinition portletDef = null;
    final boolean isChannel = node.getNodeName().equals("channel");

    if (isChannel) {
        chanId = Integer.parseInt(node.getAttributes().getNamedItem("chanID").getNodeValue());
        portletDef = this.portletDefinitionRegistry.getPortletDefinition(String.valueOf(chanId));
        if (portletDef == null) {
            //Portlet doesn't exist any more, drop the layout node
            return 0;
        }
    }

    if (node.hasChildNodes()) {
        childStructId = this.saveStructure(node.getFirstChild(), structStmt, parmStmt);
    }
    nextStructId = this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    structStmt.clearParameters();
    structStmt.setInt(1, saveStructId);
    structStmt.setInt(2, nextStructId);
    structStmt.setInt(3, childStructId);

    final String externalId = structure.getAttribute("external_id");
    if (externalId != null && externalId.trim().length() > 0) {
        final Integer eID = new Integer(externalId);
        structStmt.setInt(4, eID.intValue());
    } else {
        structStmt.setNull(4, java.sql.Types.NUMERIC);

    }
    if (isChannel) {
        structStmt.setInt(5, chanId);
        structStmt.setNull(6, java.sql.Types.VARCHAR);
    } else {
        structStmt.setNull(5, java.sql.Types.NUMERIC);
        structStmt.setString(6, structure.getAttribute("name"));
    }
    final String structType = structure.getAttribute("type");
    structStmt.setString(7, structType);
    structStmt.setString(8, RDBMServices.dbFlag(xmlBool(structure.getAttribute("hidden"))));
    structStmt.setString(9, RDBMServices.dbFlag(xmlBool(structure.getAttribute("immutable"))));
    structStmt.setString(10, RDBMServices.dbFlag(xmlBool(structure.getAttribute("unremovable"))));
    logger.debug(structStmt.toString());
    structStmt.executeUpdate();

    // code to persist extension attributes for dlm
    final NamedNodeMap attribs = node.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        final Node attrib = attribs.item(i);
        final String name = attrib.getNodeName();

        if (name.startsWith(Constants.NS) && !name.equals(Constants.ATT_PLF_ID)
                && !name.equals(Constants.ATT_FRAGMENT) && !name.equals(Constants.ATT_PRECEDENCE)) {
            // a cp extension attribute. Push into param table.
            parmStmt.clearParameters();
            parmStmt.setInt(1, saveStructId);
            parmStmt.setString(2, name);
            parmStmt.setString(3, attrib.getNodeValue());
            logger.debug(parmStmt.toString());
            parmStmt.executeUpdate();
        }
    }
    final NodeList parameters = node.getChildNodes();
    if (parameters != null && isChannel) {
        for (int i = 0; i < parameters.getLength(); i++) {
            if (parameters.item(i).getNodeName().equals("parameter")) {
                final Element parmElement = (Element) parameters.item(i);
                final NamedNodeMap nm = parmElement.getAttributes();
                final String parmName = nm.getNamedItem("name").getNodeValue();
                final String parmValue = nm.getNamedItem("value").getNodeValue();
                final Node override = nm.getNamedItem("override");

                // if no override specified then default to allowed
                if (override != null && !override.getNodeValue().equals("yes")) {
                    // can't override
                } else {
                    // override only for adhoc or if diff from chan def
                    final IPortletDefinitionParameter cp = portletDef.getParameter(parmName);
                    if (cp == null || !cp.getValue().equals(parmValue)) {
                        parmStmt.clearParameters();
                        parmStmt.setInt(1, saveStructId);
                        parmStmt.setString(2, parmName);
                        parmStmt.setString(3, parmValue);
                        logger.debug(parmStmt.toString());
                        parmStmt.executeUpdate();
                    }
                }
            }
        }
    }
    return saveStructId;
}

From source file:org.automagic.deps.doctor.editor.PomWriterImpl.java

private Optional<Node> getInsertionPoint(Node node) {

    if (!node.hasChildNodes()) {
        return Optional.absent();
    }/* ww w. j a  v  a2 s.  com*/

    Node point = null;
    for (int i = node.getChildNodes().getLength() - 1; i >= 0; i--) {
        Node blankNode = node.getChildNodes().item(i);
        if (blankNode.getNodeType() == Node.TEXT_NODE) {
            String nodeValue = blankNode.getNodeValue();
            if (StringUtils.isBlank(nodeValue)) {
                point = blankNode;
            }
        } else {
            break;
        }
    }

    if (point != null) {
        return Optional.of(point);
    }

    return Optional.absent();
}

From source file:org.bibsonomy.scraper.url.kde.ieee.IEEEXploreBookScraper.java

/**
 * @param sc/*from   w  w w .j  a  va  2s  .c om*/
 * @return bibtex
 * @throws ScrapingException
 */
public String ieeeBookScrape(ScrapingContext sc) throws ScrapingException {
    try {
        //-- init all NodeLists and Node
        NodeList pres = null;
        Node currNode = null;
        NodeList temp = null;

        //-- init String map for bibtex entries
        String type = IEEE_BOOK;
        String url = sc.getUrl().toString();
        String authors = "";
        String numpages = "";
        String title = "";
        String isbn = "";
        String publisher = "";
        String month = "";
        String year = "";
        String edition = "";
        String abstr = "";

        String bibtexkey = null;
        String _tempabs = null;
        String ident1 = null;
        String ident2 = null;

        //-- get the html doc and parse the DOM
        final Document doc = XmlUtils.getDOM(sc.getPageContent());

        /*
         * -- Search title and extract --
         * The title has always the css-class "headNavBlueXLarge".
         *
         * FIXME: this part could be deprecated. don't knot it at all...
         *
        pres = null;
        pres = doc.getElementsByTagName("span"); //get all <span>-Tags
        for (int i = 0; i < pres.getLength(); i++) {
           Node curr = pres.item(i);
           Element g = (Element)curr;
           Attr own = g.getAttributeNode("class");         
                
           //-- Extract the title
           if ("headNavBlueXLarge".equals(own.getValue())){
              title = curr.getFirstChild().getNodeValue();
           }
        } */

        if (title == null || title.equals("")) {
            ident1 = "<title>";
            ident2 = "</title>";
            if (sc.getPageContent().contains(ident1) && sc.getPageContent().contains(ident2)) {
                int _startIndex = sc.getPageContent().indexOf(ident1) + ident1.length();
                int _endIndex = sc.getPageContent().indexOf(ident2);
                title = sc.getPageContent().substring(_startIndex, _endIndex);
                title = title.replaceAll("IEEEXplore#\\s", "");
            }
        }

        /* 
         * get the abstract block
         * 
         * FIXME: this part could be deprecated. don't knot it at all...
         * 
        ident1 = "<strong>Abstract</strong>";
        ident2 = "<strong>Table of Contents </strong>";
        if (sc.getPageContent().indexOf(ident1) != -1 && sc.getPageContent().indexOf(ident2) != -1 ){
           _tempabs = sc.getPageContent().substring(sc.getPageContent().indexOf(ident1)+ident1.length(),sc.getPageContent().indexOf(ident2)).replaceAll("\\s\\s+", "").replaceAll("(<.+?>)", "").trim();
           abstr = _tempabs;         
        } */

        ident1 = "<span class=\"sectionHeaders\">Abstract</span>";
        ident2 = "<td class=\"bodyCopyGrey\"><p class=\"bodyCopyGreySpaced\"><strong>";
        if (sc.getPageContent().contains(ident1) && sc.getPageContent().contains(ident2)) {
            int _startIndex = sc.getPageContent().indexOf(ident1) + ident1.length();
            int _endIndex = sc.getPageContent().indexOf(ident2);
            _tempabs = sc.getPageContent().substring(_startIndex, _endIndex);
            abstr = _tempabs.replaceAll("\\s\\s+", "").replaceAll("(<.+?>)", "").trim();
        }

        /* 
         * get the book formats like hardcover
         * 
         * FIXME: this part could be deprecated. don't knot it at all...
         * 
         *
        ident1 = "<td class=\"bodyCopyBlackLarge\" nowrap>Hardcover</td>";
        ident2 = "<td class=\"bodyCopyBlackLarge\" nowrap><span class=\"sectionHeaders\">&raquo;</span>";
        if (sc.getPageContent().indexOf(ident1) != -1){
           _format = sc.getPageContent().substring(sc.getPageContent().indexOf(ident1),sc.getPageContent().indexOf(ident2)).replaceAll("\\s\\s+", "").replaceAll("(<.+?>)", "");
                
           _format = _format.substring(_format.indexOf(CONST_ISBN) + CONST_ISBN.length());
           isbn = _format.substring(0,_format.indexOf("&nbsp;"));
        }*/

        /*-- get all <p>-Tags to extract the standard informations
         *  In every standard page the css-class "bodyCopyBlackLargeSpaced"
         *  indicates the collection of all informations.
         * */
        pres = null;
        pres = doc.getElementsByTagName("p"); //get all <p>-Tags
        for (int i = 0; i < pres.getLength(); i++) {
            currNode = pres.item(i);

            if (currNode.hasAttributes()) {
                Element g = (Element) currNode;
                Attr own = g.getAttributeNode("class");
                if ("bodyCopyBlackLargeSpaced".equals(own.getValue()) && currNode.hasChildNodes()) {
                    temp = currNode.getChildNodes();

                    for (int j = 0; j < temp.getLength(); j++) {
                        if (temp.item(j).getNodeValue().indexOf(CONST_DATE) != -1) {
                            String date = temp.item(j).getNodeValue().substring(18);
                            year = date.substring(date.length() - 5).trim();
                            month = date.substring(0, date.length() - 4).trim();
                            // not correct in all cases
                            // publisher = temp.item(j+2).getNodeValue().trim();
                        }
                        if (temp.item(j).getNodeValue().indexOf(CONST_PAGES) != -1) {
                            numpages = temp.item(j).getNodeValue().substring(CONST_PAGES.length()).trim();
                        } else if (temp.item(j).getNodeValue().indexOf(CONST_ON_PAGES) != -1) {
                            numpages = temp.item(j).getNodeValue().substring(CONST_ON_PAGES.length()).trim();
                        }
                        if (temp.item(j).getNodeValue().indexOf(CONST_EDITION) != -1) {
                            edition = temp.item(j).getNodeValue().substring(CONST_EDITION.length()).trim();
                        } else if (temp.item(j).getNodeValue().indexOf(CONST_VOLUME) != -1) {
                            edition = temp.item(j).getNodeValue().substring(CONST_VOLUME.length()).trim();
                        }
                        if (isbn == "" && temp.item(j).getNodeValue().indexOf(CONST_ISBN) != -1) {
                            isbn = temp.item(j).getNodeValue().substring(CONST_ISBN.length()).trim();
                        }
                    }
                    break;
                }
            }
        }

        /*-- Search authors and save them --
         * 
         * FIXME: this part could be deprecated. don't knot it at all...
         * 
        pres = null;
        pres = doc.getElementsByTagName("a"); //get all <a>-Tags
                
        //init vars to count authors to form a bibtex String
        int numaut = 0;
                
         *
         * iterate through the a tags and search the attribute value "<in>aud)" 
         * to identify the authors in the source of the ieeexplore page
         * 
        for (int i = 39; i < pres.getLength(); i++) {
           Node curr = pres.item(i);
           Element g = (Element)curr;
           Attr own = g.getAttributeNode("href");
                
           if (own.getValue().indexOf("<in>au)") != -1){
              //Form Bibtex String by counting authors
              if (numaut > 0 ){
          authors += " and " + curr.getFirstChild().getNodeValue(); 
              }
              if (numaut == 0) {
          numaut=i;
          authors += curr.getFirstChild().getNodeValue();
                
          if (curr.getFirstChild().getNodeValue().indexOf(",") != -1 && bibtexkey == null){
             bibtexkey = curr.getFirstChild().getNodeValue().substring(0,curr.getFirstChild().getNodeValue().trim().indexOf(","));
          } else if (curr.getFirstChild().getNodeValue().trim().indexOf(" ") != -1 && bibtexkey == null){
             bibtexkey = curr.getFirstChild().getNodeValue().trim().substring(0,curr.getFirstChild().getNodeValue().trim().indexOf(" "));
          } else if (bibtexkey == null){
             bibtexkey = curr.getFirstChild().getNodeValue().trim();
          }
              }
           }
        } */

        /*
         * get authors
         */
        if (authors == null || authors.equals("")) {
            ident1 = "<font color=990000><b>";
            ident2 = "<br>";
            int _startIndex = sc.getPageContent().indexOf(ident1) + ident1.length();
            if (sc.getPageContent().contains(ident1)
                    && sc.getPageContent().indexOf(ident2, _startIndex) != -1) {
                int _endIndex = sc.getPageContent().indexOf(ident2, _startIndex);
                authors = sc.getPageContent().substring(_startIndex, _endIndex);
                authors = authors.replaceAll("\\s\\s+", "").replaceAll("(<.+?>)", "").trim();
                authors = authors.replaceAll("&nbsp;&nbsp;", " and ");

                if (authors.endsWith(" and ")) {
                    authors = authors.substring(0, authors.length() - 5);
                }
            }
        }

        //-- kill special chars and add the year to bibtexkey
        if ((isbn == null || !isbn.equals("")) && (year == null || !year.equals(""))) {
            bibtexkey = isbn.replaceAll("-", "");
            bibtexkey = bibtexkey.replaceAll("[^0-9A-Za-z]", "") + ":" + year;
        }

        //create the book-bibtex
        return type + " { " + bibtexkey + ", \n" + "author = {" + authors + "}, \n" + "title = {" + title
                + "}, \n" + "year = {" + year + "}, \n" + "url = {" + url + "}, \n" + "pages = {" + numpages
                + "}, \n" + "edition = {" + edition + "}, \n" + "publisher = {" + publisher + "}, \n"
                + "isbn = {" + isbn + "}, \n" + "abstract = {" + abstr + "}, \n" + "month = {" + month + "}\n}";

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

From source file:org.carewebframework.shell.layout.UILayout.java

/**
 * Returns the class of the element at the root of the layout.
 * //from   w  w w . j  av  a  2s  .com
 * @return Class of the element at the root of the layout, or null if none.
 */
public Class<? extends UIElementBase> getRootClass() {
    Node node = document.getDocumentElement();
    node = node.hasChildNodes() ? node.getFirstChild() : null;
    String id = node == null ? null : node.getNodeName();
    PluginDefinition def = id == null ? null : PluginDefinition.getDefinition(id);
    return def == null ? null : def.getClazz();
}

From source file:org.carewebframework.shell.layout.UILayout.java

/**
 * Returns true if the layout has no content.
 * /*from   ww w  .  ja va2s .  com*/
 * @return True if the layout has no content.
 */
public boolean isEmpty() {
    Node root = document == null ? null : document.getElementsByTagName(LayoutConstants.LAYOUT_ROOT).item(0);
    return root == null || !root.hasChildNodes();
}

From source file:org.culturegraph.mf.morph.MorphVisualizer.java

@Override
protected void handleFunction(final Node functionNode) {
    final String identifier = getNewId();
    final Map<String, String> attributes = resolvedAttributeMap(functionNode);

    //for lookups TODO: find generic solution and get rid of the ifs.
    attributes.remove("default");
    String inAttr = attributes.remove("in");
    if (inAttr == null) {
        inAttr = attributes.remove("map");
    }/* ww w .  j av  a2  s. c  o m*/
    if (inAttr != null) {
        addIncludeEdge(inAttr, identifier);
    }
    writer.println(buildRecord(identifier, functionNode.getLocalName(), "white", attributes));

    if (functionNode.hasChildNodes()) {
        final Map<String, String> map = getMap(functionNode);
        final String mapId = identifier + "M";
        addIncludeEdge(mapId, identifier);
        writer.println(buildMap(mapId, null, map));
    }

    addEdge(lastProcessorStack.pop(), identifier);
    lastProcessorStack.push(identifier);
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

@Override
public @Nonnull String getConsoleOutput(@Nonnull String instanceId) throws InternalException, CloudException {
    APITrace.begin(getProvider(), "getConsoleOutput");
    try {//from ww  w  . j a v a  2s  .c o  m
        Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(),
                EC2Method.GET_CONSOLE_OUTPUT);
        String output = null;
        EC2Method method;
        NodeList blocks;
        Document doc;

        parameters.put("InstanceId", instanceId);
        method = new EC2Method(getProvider(), parameters);
        try {
            doc = method.invoke();
        } catch (EC2Exception e) {
            String code = e.getCode();

            if (code != null && code.startsWith("InvalidInstanceID")) {
                return "";
            }
            logger.error(e.getSummary());
            throw new CloudException(e);
        }
        blocks = doc.getElementsByTagName("timestamp");
        for (int i = 0; i < blocks.getLength(); i++) {
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            fmt.setCalendar(UTC_CALENDAR);
            String ts = blocks.item(i).getFirstChild().getNodeValue();
            long timestamp;

            try {
                timestamp = fmt.parse(ts).getTime();
            } catch (ParseException e) {
                logger.error(e);
                throw new CloudException(e);
            }
            if (timestamp > -1L) {
                break;
            }
        }
        blocks = doc.getElementsByTagName("output");
        for (int i = 0; i < blocks.getLength(); i++) {
            Node item = blocks.item(i);

            if (item.hasChildNodes()) {
                output = item.getFirstChild().getNodeValue().trim();
                break;
            }
        }
        if (output != null) {
            try {
                return new String(Base64.decodeBase64(output.getBytes("utf-8")), "utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.error(e);
                throw new InternalException(e);
            }
        }
        return "";
    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

@Override
public @Nonnull Iterable<String> listFirewalls(@Nonnull String instanceId)
        throws InternalException, CloudException {
    APITrace.begin(getProvider(), "listFirewallsForVM");
    try {//w  w  w. ja va2  s.c o m
        Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(),
                EC2Method.DESCRIBE_INSTANCES);
        List<String> firewalls = new ArrayList<String>();
        EC2Method method;
        NodeList blocks;
        Document doc;

        parameters.put("InstanceId.1", instanceId);
        method = new EC2Method(getProvider(), parameters);
        try {
            doc = method.invoke();
        } catch (EC2Exception e) {
            String code = e.getCode();

            if (code != null && code.startsWith("InvalidInstanceID")) {
                return firewalls;
            }
            logger.error(e.getSummary());
            throw new CloudException(e);
        }
        blocks = doc.getElementsByTagName("groupSet");
        for (int i = 0; i < blocks.getLength(); i++) {
            NodeList items = blocks.item(i).getChildNodes();

            for (int j = 0; j < items.getLength(); j++) {
                Node item = items.item(j);

                if (item.getNodeName().equals("item")) {
                    NodeList sub = item.getChildNodes();

                    for (int k = 0; k < sub.getLength(); k++) {
                        Node id = sub.item(k);

                        if (id.getNodeName().equalsIgnoreCase("groupId") && id.hasChildNodes()) {
                            firewalls.add(id.getFirstChild().getNodeValue().trim());
                            break;
                        }
                    }
                }
            }
        }
        return firewalls;
    } finally {
        APITrace.end();
    }
}