Example usage for org.w3c.dom NamedNodeMap getNamedItem

List of usage examples for org.w3c.dom NamedNodeMap getNamedItem

Introduction

In this page you can find the example usage for org.w3c.dom NamedNodeMap getNamedItem.

Prototype

public Node getNamedItem(String name);

Source Link

Document

Retrieves a node specified by name.

Usage

From source file:org.kuali.mobility.maps.service.LocationServiceImpl.java

private boolean isNotNullNotEmptyAttribute(NamedNodeMap nodeMap, String attributeName) {
    return nodeMap.getNamedItem(attributeName) != null
            && !"".equals(nodeMap.getNamedItem(attributeName).getNodeValue());
}

From source file:org.universAAL.itests.IntegrationTest.java

/**
 * This method processes configured eclipse launch configuration. Extracts
 * list of bundles and sets run arguments as system properties.
 *
 * @return Returns list of resources.//from  w w w .  j  ava  2  s  . c  om
 */
private List<Resource> processEclipseLaunhFile() {
    List<Resource> bundleResources = null;
    try {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new File(eclipseLaunchFile));
        Node root = doc.getFirstChild();
        NodeList nodes = root.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);
            String name = n.getNodeName();
            if (name != null && name.equals("listAttribute")) {
                NamedNodeMap attribs = n.getAttributes();
                Node keyAttrib = attribs.getNamedItem("key");
                String keyAttribStr = keyAttrib.getTextContent();
                if (keyAttribStr.equals("org.ops4j.pax.cursor.runArguments")) {
                    NodeList paxArgs = n.getChildNodes();
                    bundleResources = parsePaxArgs(paxArgs);
                }
            }
            if (name != null && name.equals("stringAttribute")) {
                NamedNodeMap attribs = n.getAttributes();
                Node keyAttrib = attribs.getNamedItem("key");
                String keyAttribStr = keyAttrib.getTextContent();
                if (keyAttribStr.equals("org.eclipse.jdt.launching.VM_ARGUMENTS")) {
                    String vmArgs = attribs.getNamedItem("value").getTextContent();
                    parseRunArgs(vmArgs);

                }
            }
        }
        return bundleResources;
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:com.zimbra.common.util.QuotedTextUtil.java

/**
 * Tries to determine the type of the node
 *
 * @param node/* w  w  w .j  ava 2s . com*/
 * @return {@link LineType} the type of the node
 */
private LineType checkNode(Node node) {
    if (node == null) {
        return null;
    }

    String nodeName = node.getNodeName().toLowerCase();
    NamedNodeMap attributes = node.getAttributes();
    String id = (attributes != null && attributes.getNamedItem("id") != null)
            ? attributes.getNamedItem("id").getNodeValue()
            : "";
    String size = (attributes != null && attributes.getNamedItem("size") != null)
            ? attributes.getNamedItem("size").getNodeValue()
            : "";
    String width = (attributes != null && attributes.getNamedItem("width") != null)
            ? attributes.getNamedItem("width").getNodeValue()
            : "";
    String align = (attributes != null && attributes.getNamedItem("align") != null)
            ? attributes.getNamedItem("align").getNodeValue()
            : "";
    String className = (attributes != null && attributes.getNamedItem("class") != null)
            ? attributes.getNamedItem("class").getNodeValue()
            : "";
    LineType type = null;

    // Text node: test against our regexes
    if ("#text".equals(nodeName)) {
        String content = node.getNodeValue().trim();
        if (!content.isEmpty()) {
            type = getLineType(content);
        }
    } else if ("hr".equals(nodeName)) {
        // HR: look for a couple different forms that are used to delimit
        // quoted content
        // see if the HR is ours, or one commonly used by other mail clients
        // such as Outlook
        if (HTML_SEP_ID.equals(id) || (size.equals("2") && width.equals("100%") && align.equals("center"))) {
            type = LineType.SEP_STRONG;
        } else {
            type = LineType.LINE;
        }
    } else if ("pre".equals(nodeName)) {
        // PRE: treat as one big line of text (should maybe go line by line)
        type = checkNodeContent(node);
    } else if ("div".equals(nodeName)) {
        // DIV: check for Outlook class used as delimiter, or a top border
        // used as a separator, and finally just
        // check the text content
        if (className.equals("OutlookMessageHeader")) {
            type = LineType.SEP_STRONG;
        }
        // TODO: identify separator using style attributes

        if (className.equals("gmail_quote")) {
            type = checkNodeContent(node);
        }
    } else if ("span".equals(nodeName)) {
        // SPAN: check text content
        if (type == null) {
            type = checkNodeContent(node);
        }
    } else if ("img".equals(nodeName)) {
        // IMG: treat as original content
        type = LineType.UNKNOWN;
    } else if ("blockquote".equals(nodeName)) {
        // BLOCKQUOTE: treat as quoted section
        type = LineType.QUOTED;
    }
    return type != null ? type : LineType.UNKNOWN;
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

private List<UniverseQueryPrompt> parseParameters(NodeList parametersNodeList) {
    List<UniverseQueryPrompt> parameters = new ArrayList<>();
    if (parametersNodeList != null) {
        int count = parametersNodeList.getLength();
        for (int i = 0; i < count; i++) {
            Node parameterNode = parametersNodeList.item(i);
            Node type = parameterNode.getAttributes().getNamedItem("type");
            if (type != null && type.getTextContent().equalsIgnoreCase("prompt")
                    && parameterNode.hasChildNodes()) {
                NodeList parameterInfoNodes = parameterNode.getChildNodes();
                int childNodesCount = parameterInfoNodes.getLength();
                String name = null;
                Integer id = null;
                String cardinality = null;
                String constrained = null;
                String valueType = null;
                String technicalName = null;
                String keepLastValues = null;
                for (int j = 0; j < childNodesCount; j++) {
                    Node childNode = parameterInfoNodes.item(j);
                    String childNodeName = childNode.getNodeName();
                    if (childNodeName.equalsIgnoreCase(EL_NAME)) {
                        name = childNode.getTextContent();
                        continue;
                    }//from   www .ja  v  a 2  s.  com
                    if (childNodeName.equalsIgnoreCase(EL_ID)) {
                        id = Integer.parseInt(childNode.getTextContent());
                        continue;
                    }
                    if (childNodeName.equalsIgnoreCase(EL_TECH_NAME)) {
                        technicalName = childNode.getTextContent();
                        continue;
                    }
                    if (childNodeName.equalsIgnoreCase(EL_ANSWER)) {
                        NamedNodeMap answerAttributes = childNode.getAttributes();
                        if (answerAttributes.getNamedItem("constrained") != null) {
                            constrained = answerAttributes.getNamedItem("constrained").getTextContent();
                        }
                        if (answerAttributes.getNamedItem("type") != null) {
                            valueType = answerAttributes.getNamedItem("type").getTextContent();
                        }
                        NodeList answerNodes = childNode.getChildNodes();
                        int answerCount = answerNodes.getLength();
                        for (int k = 0; k < answerCount; k++) {
                            Node answerChildNode = answerNodes.item(k);
                            String answerChildNodeName = answerChildNode.getNodeName();
                            if (answerChildNodeName.equalsIgnoreCase(EL_INFO)) {
                                NamedNodeMap infoAttributes = answerChildNode.getAttributes();
                                if (infoAttributes.getNamedItem("cardinality") != null) {
                                    cardinality = infoAttributes.getNamedItem("cardinality").getTextContent();
                                }
                                if (infoAttributes.getNamedItem("keepLastValues") != null) {
                                    keepLastValues = infoAttributes.getNamedItem("keepLastValues")
                                            .getTextContent();
                                }
                                break;
                            }
                        }
                        continue;
                    }
                }
                if (name != null && id != null && cardinality != null) {
                    parameters.add(new UniverseQueryPrompt(id, name, cardinality, constrained, valueType,
                            technicalName, keepLastValues));
                    break;
                }
            }
        }
    }

    return parameters;
}

From source file:com.fujitsu.dc.test.jersey.AbstractCase.java

/**
 * Node?????.// w ww  .j  ava  2  s . c  o  m
 * @param node ???(Node)
 * @param name ????
 * @return ???
 */
private String getAttributeValue(final Node node, final String name) {
    NamedNodeMap nnm = node.getAttributes();
    Node attr = nnm.getNamedItem(name);
    if (attr != null) {
        return attr.getNodeValue();
    } else {
        return "";
    }
}

From source file:hoot.services.models.osm.Relation.java

private RelationMember parseMember(final org.w3c.dom.Node nodeXml) throws Exception {
    final NamedNodeMap memberXmlAttributes = nodeXml.getAttributes();

    final long parsedMemberId = Long.parseLong(memberXmlAttributes.getNamedItem("ref").getNodeValue());
    long actualMemberId = parsedMemberId;
    final ElementType elementType = Element
            .elementTypeFromString(memberXmlAttributes.getNamedItem("type").getNodeValue());
    if (elementType == null) {
        throw new Exception(
                "Invalid relation member type: " + memberXmlAttributes.getNamedItem("type").getNodeValue());
    }/*  w w w . j av a2s  .  co  m*/

    if (elementType.equals(ElementType.Relation)) {
        checkForCircularReference(parsedMemberId);
    }

    final Map<Long, Element> parsedElements = parsedElementIdsToElementsByType.get(elementType);
    // if this is an element created within the same request that is referencing
    // this relation, it
    // won't exist in the database, but it will be in the element cache created
    // when parsing the
    // element from the request
    if (parsedMemberId < 0) {
        if (elementType.equals(ElementType.Relation)) {
            if (!parsedElements.containsKey(parsedMemberId)) {
                throw new Exception("Relation with ID: " + parsedMemberId + " does not exist for "
                        + "relation with ID: " + getId());
            }
        } else {
            assert (parsedElements.containsKey(parsedMemberId));
        }
    }

    Element memberElement = null;

    // The element is referenced somewhere else in this request, so get its info
    // from the request,
    // not the database b/c the database either won't have it or will have
    // outdated info for it.
    // Only get info from the request if the element is being created/modified,
    // because if it is
    // being deleted, we can just get the info from the database since the
    // element's bounds won't be
    // changing and its geo info isn't in the request (not required).
    if (parsedElements.containsKey(parsedMemberId)
            && !parsedElements.get(parsedMemberId).getEntityChangeType().equals(EntityChangeType.DELETE)) {
        memberElement = parsedElements.get(parsedMemberId);
        actualMemberId = memberElement.getId();
    }
    // element not referenced in this request, so should already exist in the db
    // and its info up
    // to date
    else {
        Set<Long> elementIds = new HashSet<Long>(Arrays.asList(new Long[] { actualMemberId }));
        if (!Element.allElementsExist(getMapId(), elementType, elementIds, conn)) {
            throw new Exception("Element with ID: " + actualMemberId + " and type: " + elementType.toString()
                    + " does not exist for relation.");
        }
        if (!Element.allElementsVisible(getMapId(), elementType, elementIds, conn)) {
            throw new Exception("Element with ID: " + actualMemberId + " and type: " + elementType.toString()
                    + " is not visible for relation.");
        }
        memberElement = ElementFactory.getInstance().create(getMapId(), elementType, conn);
    }
    assert (actualMemberId > 0);

    // role is allowed to be empty
    org.w3c.dom.Node roleXmlNode = memberXmlAttributes.getNamedItem("role");
    final String role = roleXmlNode == null ? null : roleXmlNode.getNodeValue();
    RelationMember member = new RelationMember(actualMemberId,
            Element.elementTypeFromString(memberXmlAttributes.getNamedItem("type").getNodeValue()), role);
    member.setOldId(parsedMemberId);
    return member;
}

From source file:com.nexmo.messaging.sdk.NexmoSmsClient.java

/**
 * submit a message submission request object.
 * This will use the supplied object to construct a request and post it to the Nexmo REST interface.<br>
 * This method will respond with an array of SmsSubmissionResult objects. Depending on the nature and length of the submitted message, Nexmo may automatically
 * split the message into multiple sms messages in order to deliver to the handset. For example, a long text sms of greater than 160 chars will need to be split
 * into multiple 'concatenated' sms messages. The Nexmo service will handle this automatically for you.<br>
 * The array of SmsSubmissionResult objects will contain a SmsSubmissionResult object for every actual sms that was required to submit the message.
 * each message can potentially have a different status result, and each message will have a different message id.
 * Delivery notifications will be generated for each sms message within this set and will be posted to your application containing the appropriate message id.
 *
 * @param message The message request object that describes the type of message and the contents to be submitted.
 * @param validityPeriod The validity period (Time-To-Live) for this message. Specifies the time before this mesage will be expired if not yet delivered
 * @param networkCode (Optional) use this parameter to force this message to be associated with and delivered on this network. Use this in cases where you want to over-ride
 *                               the automatic network detection provided by Nexmo. This value will be used in order to determine the pricing and routing for this message.<br>
 *                               (Note) This feature must be enabled and available on your account or else this value will be ignored.
 * @param performReachabilityCheck Flag to indicate wether a reachability check should be performed on this message before delivery is attempted. If the destination is
 *                                 not reachable, the message will be rejected and a reachability status will be returned in the response field smsSubmissionReachabilityStatus<br>
 *                                 (Note) This feature must be enabled and available on your account or else the message request will be rejected. There may be additional cost
 *                                 associated with the use of this feature.
 *
 * @return SmsSubmissionResult[] an array of results, 1 object for each sms message that was required to submit this message in its entirety
 *
 * @throws Exception There has been a general failure either within the Client class, or whilst attempting to communicate with the Nexmo service (eg, Network failure)
 *//* w w w. j  a  v a2s.  co  m*/
public SmsSubmissionResult[] submitMessage(final Message message, final ValidityPeriod validityPeriod,
        final String networkCode, final boolean performReachabilityCheck) throws Exception {

    log.debug("HTTP-Message-Submission Client .. from [ " + message.getFrom() + " ] to [ " + message.getTo()
            + " ] msg [ " + message.getMessageBody() + " ] ");

    // From the Message object supplied, construct an appropriate request to be submitted to the Nexmo REST Service.

    // Determine what 'product' type we are submitting, and select the appropriate endpoint path
    String submitPath = SUBMISSION_PATH_SMS;

    // Determine the type parameter based on the type of Message object.
    boolean binary = message.getType() == Message.MESSAGE_TYPE_BINARY;
    boolean unicode = message.isUnicode();
    boolean wapPush = message.getType() == Message.MESSAGE_TYPE_WAPPUSH;

    String mode = "text";

    if (binary)
        mode = "binary";

    if (unicode)
        mode = "unicode";

    if (wapPush)
        mode = "wappush";

    // Construct a query string as a list of NameValuePairs

    List<NameValuePair> params = new ArrayList<>();

    boolean doPost = false;

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    if (!this.signRequests)
        params.add(new BasicNameValuePair("api_secret", this.apiSecret));
    params.add(new BasicNameValuePair("from", message.getFrom()));
    params.add(new BasicNameValuePair("to", message.getTo()));
    params.add(new BasicNameValuePair("type", mode));
    if (wapPush) {
        params.add(new BasicNameValuePair("url", message.getWapPushUrl()));
        params.add(new BasicNameValuePair("title", message.getWapPushTitle()));
        if (message.getWapPushValidity() > 0)
            params.add(new BasicNameValuePair("validity", "" + message.getWapPushValidity()));
    } else if (binary) {
        // Binary Message
        if (message.getBinaryMessageUdh() != null)
            params.add(new BasicNameValuePair("udh", HexUtil.bytesToHex(message.getBinaryMessageUdh())));
        params.add(new BasicNameValuePair("body", HexUtil.bytesToHex(message.getBinaryMessageBody())));
    } else {
        // Text Message
        params.add(new BasicNameValuePair("text", message.getMessageBody()));
        if (message.getMessageBody() != null && message.getMessageBody().length() > 255)
            doPost = true;
    }

    if (message.getClientReference() != null)
        params.add(new BasicNameValuePair("client-ref", message.getClientReference()));

    params.add(new BasicNameValuePair("status-report-req", "" + message.getStatusReportRequired()));

    if (message.getMessageClass() != null)
        params.add(new BasicNameValuePair("message-class", "" + message.getMessageClass().getMessageClass()));

    if (message.getProtocolId() != null)
        params.add(new BasicNameValuePair("protocol-id", "" + message.getProtocolId()));

    if (validityPeriod != null) {
        if (validityPeriod.getTimeToLive() != null)
            params.add(new BasicNameValuePair("ttl", "" + validityPeriod.getTimeToLive().intValue()));
        if (validityPeriod.getValidityPeriodHours() != null)
            params.add(new BasicNameValuePair("ttl-hours",
                    "" + validityPeriod.getValidityPeriodHours().intValue()));
        if (validityPeriod.getValidityPeriodMinutes() != null)
            params.add(new BasicNameValuePair("ttl-minutes",
                    "" + validityPeriod.getValidityPeriodMinutes().intValue()));
        if (validityPeriod.getValidityPeriodSeconds() != null)
            params.add(new BasicNameValuePair("ttl-seconds",
                    "" + validityPeriod.getValidityPeriodSeconds().intValue()));
    }

    if (networkCode != null)
        params.add(new BasicNameValuePair("network-code", networkCode));

    if (performReachabilityCheck)
        params.add(new BasicNameValuePair("test-reachable", "true"));

    if (this.signRequests)
        RequestSigning.constructSignatureForRequestParameters(params, this.signatureSecretKey);

    String baseUrl = this.baseUrlHttps + submitPath;

    // Now that we have generated a query string, we can instanciate a HttpClient,
    // construct a POST or GET method and execute to submit the request
    String response = null;
    for (int pass = 1; pass <= 2; pass++) {
        HttpUriRequest method = null;
        doPost = true;
        String url = null;
        if (doPost) {
            HttpPost httpPost = new HttpPost(baseUrl);
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            method = httpPost;
            url = baseUrl + "?" + URLEncodedUtils.format(params, "utf-8");
        } else {
            String query = URLEncodedUtils.format(params, "utf-8");
            method = new HttpGet(baseUrl + "?" + query);
            url = method.getRequestLine().getUri();
        }

        try {
            if (this.httpClient == null)
                this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout)
                        .getNewHttpClient();
            HttpResponse httpResponse = this.httpClient.execute(method);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status != 200)
                throw new Exception(
                        "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] ");
            response = new BasicResponseHandler().handleResponse(httpResponse);
            log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
            break;
        } catch (Exception e) {
            method.abort();
            log.info("communication failure: " + e);
            String exceptionMsg = e.getMessage();
            if (exceptionMsg.indexOf("Read timed out") >= 0) {
                log.info(
                        "we're still connected, but the target did not respond in a timely manner ..  drop ...");
            } else {
                if (pass == 1) {
                    log.info("... re-establish http client ...");
                    this.httpClient = null;
                    continue;
                }
            }

            // return a COMMS failure ...
            SmsSubmissionResult[] results = new SmsSubmissionResult[1];
            results[0] = new SmsSubmissionResult(SmsSubmissionResult.STATUS_COMMS_FAILURE, null, null,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e,
                    message.getClientReference(), null, null, true, null, null);
            return results;
        }
    }

    // parse the response doc ...

    /*
    We receive a response from the api that looks like this, parse the document
    and turn it into an array of SmsSubmissionResult, one object per <message> node
            
        <mt-submission-response>
            <messages count='x'>
                <message>
                    <to>xxx</to>
                    <messageId>xxx</messageId>
                    <status>xx</status>
                    <errorText>ff</errorText>
                    <clientRef>xxx</clientRef>
                    <remainingBalance>##.##</remainingBalance>
                    <messagePrice>##.##</messagePrice>
                    <reachability status='x' description='xxx' />
                    <network>23410</network>
                </message>
            </messages>
        </mt-submission-response>
    */

    List<SmsSubmissionResult> results = new ArrayList<>();

    Document doc = null;
    synchronized (this.documentBuilder) {
        try {
            doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
        } catch (Exception e) {
            throw new Exception("Failed to build a DOM doc for the xml document [ " + response + " ] ", e);
        }
    }

    NodeList replies = doc.getElementsByTagName("mt-submission-response");
    for (int i = 0; i < replies.getLength(); i++) {
        Node reply = replies.item(i);
        NodeList messageLists = reply.getChildNodes();
        for (int i2 = 0; i2 < messageLists.getLength(); i2++) {
            Node messagesNode = messageLists.item(i2);
            if (messagesNode.getNodeType() != Node.ELEMENT_NODE)
                continue;
            if (messagesNode.getNodeName().equals("messages")) {
                NodeList messages = messagesNode.getChildNodes();
                for (int i3 = 0; i3 < messages.getLength(); i3++) {
                    Node messageNode = messages.item(i3);
                    if (messageNode.getNodeType() != Node.ELEMENT_NODE)
                        continue;

                    int status = -1;
                    String messageId = null;
                    String destination = null;
                    String errorText = null;
                    String clientReference = null;
                    BigDecimal remainingBalance = null;
                    BigDecimal messagePrice = null;
                    SmsSubmissionReachabilityStatus smsSubmissionReachabilityStatus = null;
                    String network = null;

                    NodeList nodes = messageNode.getChildNodes();
                    for (int i4 = 0; i4 < nodes.getLength(); i4++) {
                        Node node = nodes.item(i4);
                        if (node.getNodeType() != Node.ELEMENT_NODE)
                            continue;
                        if (node.getNodeName().equals("messageId")) {
                            messageId = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                        } else if (node.getNodeName().equals("to")) {
                            destination = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                        } else if (node.getNodeName().equals("status")) {
                            String str = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                            try {
                                status = Integer.parseInt(str);
                            } catch (NumberFormatException e) {
                                log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
                                status = SmsSubmissionResult.STATUS_INTERNAL_ERROR;
                            }
                        } else if (node.getNodeName().equals("errorText")) {
                            errorText = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                        } else if (node.getNodeName().equals("clientRef")) {
                            clientReference = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                        } else if (node.getNodeName().equals("remainingBalance")) {
                            String str = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                            try {
                                if (str != null)
                                    remainingBalance = new BigDecimal(str);
                            } catch (NumberFormatException e) {
                                log.error("xml parser .. invalid value in <remainingBalance> node [ " + str
                                        + " ] ");
                            }
                        } else if (node.getNodeName().equals("messagePrice")) {
                            String str = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                            try {
                                if (str != null)
                                    messagePrice = new BigDecimal(str);
                            } catch (NumberFormatException e) {
                                log.error(
                                        "xml parser .. invalid value in <messagePrice> node [ " + str + " ] ");
                            }
                        } else if (node.getNodeName().equals("reachability")) {
                            NamedNodeMap attributes = node.getAttributes();
                            Node attr = attributes.getNamedItem("status");
                            String str = attr == null
                                    ? "" + SmsSubmissionReachabilityStatus.REACHABILITY_STATUS_UNKNOWN
                                    : attr.getNodeValue();
                            int reachabilityStatus = SmsSubmissionReachabilityStatus.REACHABILITY_STATUS_UNKNOWN;
                            try {
                                reachabilityStatus = Integer.parseInt(str);
                            } catch (NumberFormatException e) {
                                log.error(
                                        "xml parser .. invalid value in 'status' attribute in <reachability> node [ "
                                                + str + " ] ");
                                reachabilityStatus = SmsSubmissionReachabilityStatus.REACHABILITY_STATUS_UNKNOWN;
                            }

                            attr = attributes.getNamedItem("description");
                            String description = attr == null ? "-UNKNOWN-" : attr.getNodeValue();

                            smsSubmissionReachabilityStatus = new SmsSubmissionReachabilityStatus(
                                    reachabilityStatus, description);
                        } else if (node.getNodeName().equals("network")) {
                            network = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                        } else
                            log.error(
                                    "xml parser .. unknown node found in status-return, expected [ messageId, to, status, errorText, clientRef, messagePrice, remainingBalance, reachability, network ] -- found [ "
                                            + node.getNodeName() + " ] ");
                    }

                    if (status == -1)
                        throw new Exception("Xml Parser - did not find a <status> node");

                    // Is this a temporary error ?
                    boolean temporaryError = (status == SmsSubmissionResult.STATUS_THROTTLED
                            || status == SmsSubmissionResult.STATUS_INTERNAL_ERROR
                            || status == SmsSubmissionResult.STATUS_TOO_MANY_BINDS);

                    results.add(new SmsSubmissionResult(status, destination, messageId, errorText,
                            clientReference, remainingBalance, messagePrice, temporaryError,
                            smsSubmissionReachabilityStatus, network));
                }
            }
        }
    }

    return results.toArray(new SmsSubmissionResult[results.size()]);
}

From source file:hoot.services.models.osm.Element.java

protected Map<String, String> parseTags(final org.w3c.dom.Node elementXml) throws Exception {
    Map<String, String> tags = new HashMap<String, String>();
    try {//  w ww.ja  va 2s  .  c  om
        NodeList tagXmlNodes = XPathAPI.selectNodeList(elementXml, "tag");
        for (int i = 0; i < tagXmlNodes.getLength(); i++) {
            org.w3c.dom.Node tagXmlNode = tagXmlNodes.item(i);
            NamedNodeMap nodeTagAttributes = tagXmlNode.getAttributes();
            tags.put(nodeTagAttributes.getNamedItem("k").getNodeValue(),
                    nodeTagAttributes.getNamedItem("v").getNodeValue());
        }
    } catch (Exception e) {
        throw new Exception("Error parsing tag.");
    }
    return tags;
}

From source file:com.twinsoft.convertigo.beans.core.DatabaseObject.java

public static DatabaseObject read(Node node) throws EngineException {
    String objectClassName = "n/a";
    String childNodeName = "n/a";
    String propertyName = "n/a";
    String propertyValue = "n/a";
    DatabaseObject databaseObject = null;
    Element element = (Element) node;

    objectClassName = element.getAttribute("classname");

    // Migration to 4.x+ projects
    if (objectClassName.equals("com.twinsoft.convertigo.beans.core.ScreenClass")) {
        objectClassName = "com.twinsoft.convertigo.beans.screenclasses.JavelinScreenClass";
    }/*  w  w w  .j a  va2s.com*/

    String version = element.getAttribute("version");
    if ("".equals(version)) {
        version = node.getOwnerDocument().getDocumentElement().getAttribute("beans");
        if (!"".equals(version)) {
            element.setAttribute("version", version);
        }
    }
    // Verifying product version
    if (VersionUtils.compareProductVersion(Version.productVersion, version) < 0) {
        String message = "Unable to create an object of product version superior to the current beans product version ("
                + com.twinsoft.convertigo.beans.Version.version + ").\n" + "Object class: " + objectClassName
                + "\n" + "Object version: " + version;
        EngineException ee = new EngineException(message);
        throw ee;
    }

    try {
        Engine.logBeans.trace("Creating object of class \"" + objectClassName + "\"");
        databaseObject = (DatabaseObject) Class.forName(objectClassName).newInstance();
    } catch (Exception e) {
        String s = node.getNodeName();// XMLUtils.prettyPrintDOM(node);
        String message = "Unable to create a new instance of the object from the serialized XML data.\n"
                + "Object class: '" + objectClassName + "'\n" + "Object version: " + version + "\n"
                + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        // Performs custom configuration before object de-serialization
        databaseObject.preconfigure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data before its creation.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        long priority = new Long(element.getAttribute("priority")).longValue();
        databaseObject.priority = priority;

        Class<? extends DatabaseObject> databaseObjectClass = databaseObject.getClass();
        BeanInfo bi = CachedIntrospector.getBeanInfo(databaseObjectClass);
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();

        NodeList childNodes = element.getChildNodes();
        int len = childNodes.getLength();

        PropertyDescriptor pd;
        Object propertyObjectValue;
        Class<?> propertyType;
        NamedNodeMap childAttributes;
        boolean maskValue = false;

        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            Element childElement = (Element) childNode;

            childNodeName = childNode.getNodeName();

            Engine.logBeans.trace("Analyzing node '" + childNodeName + "'");

            if (childNodeName.equalsIgnoreCase("property")) {
                childAttributes = childNode.getAttributes();
                propertyName = childAttributes.getNamedItem("name").getNodeValue();
                Engine.logBeans.trace("  name = '" + propertyName + "'");
                pd = findPropertyDescriptor(pds, propertyName);
                if (pd == null) {
                    Engine.logBeans.warn(
                            "Unable to find the definition of property \"" + propertyName + "\"; skipping.");
                    continue;
                }
                propertyType = pd.getPropertyType();
                propertyObjectValue = XMLUtils
                        .readObjectFromXml((Element) XMLUtils.findChildNode(childNode, Node.ELEMENT_NODE));

                // Hides value in log trace if needed
                if ("false".equals(childElement.getAttribute("traceable"))) {
                    maskValue = true;
                }
                Engine.logBeans.trace("  value='"
                        + (maskValue ? Visibility.maskValue(propertyObjectValue) : propertyObjectValue) + "'");

                // Decrypts value if needed
                try {
                    if ("true".equals(childElement.getAttribute("ciphered"))) {
                        propertyObjectValue = decryptPropertyValue(propertyObjectValue);
                    }
                } catch (Exception e) {
                }

                propertyObjectValue = databaseObject.compileProperty(propertyType, propertyName,
                        propertyObjectValue);

                if (Enum.class.isAssignableFrom(propertyType)) {
                    propertyObjectValue = EnumUtils.valueOf(propertyType, propertyObjectValue);
                }

                propertyValue = propertyObjectValue.toString();

                Method setter = pd.getWriteMethod();
                Engine.logBeans.trace("  setter='" + setter.getName() + "'");
                Engine.logBeans.trace("  param type='" + propertyObjectValue.getClass().getName() + "'");
                Engine.logBeans.trace("  expected type='" + propertyType.getName() + "'");
                try {
                    setter.invoke(databaseObject, new Object[] { propertyObjectValue });
                } catch (InvocationTargetException e) {
                    Throwable targetException = e.getTargetException();
                    Engine.logBeans.warn("Unable to set the property '" + propertyName + "' for the object '"
                            + databaseObject.getName() + "' (" + objectClassName + "): ["
                            + targetException.getClass().getName() + "] " + targetException.getMessage());
                }

                if (Boolean.TRUE.equals(pd.getValue("nillable"))) {
                    Node nodeNull = childAttributes.getNamedItem("isNull");
                    String valNull = (nodeNull == null) ? "false" : nodeNull.getNodeValue();
                    Engine.logBeans.trace("  treats as null='" + valNull + "'");
                    try {
                        Method method = databaseObject.getClass().getMethod("setNullProperty",
                                new Class[] { String.class, Boolean.class });
                        method.invoke(databaseObject, new Object[] { propertyName, Boolean.valueOf(valNull) });
                    } catch (Exception ex) {
                        Engine.logBeans.warn("Unable to set the 'isNull' attribute for property '"
                                + propertyName + "' of '" + databaseObject.getName() + "' object");
                    }
                }
            }
        }
    } catch (Exception e) {
        String message = "Unable to set the object properties from the serialized XML data.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML analyzed node: " + childNodeName + "\n"
                + "Property name: " + propertyName + "\n" + "Property value: " + propertyValue;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        // Performs custom configuration
        databaseObject.configure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data after its creation.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    return databaseObject;
}

From source file:hoot.services.models.osm.Element.java

protected Timestamp parseTimestamp(final NamedNodeMap xmlAttributes) {
    Timestamp timestamp = null;//from  w  ww  .j a v  a 2 s. co  m
    org.w3c.dom.Node timestampXml = xmlAttributes.getNamedItem("timestamp");
    final Timestamp now = new Timestamp(Calendar.getInstance().getTimeInMillis());
    if (timestampXml != null) {
        try {
            timestamp = new Timestamp(
                    Element.getTimeFormatter().parseDateTime(timestampXml.getNodeValue()).getMillis());
        } catch (IllegalArgumentException e) {
        }
    }
    if (timestamp == null) {
        timestamp = now;
    }
    return timestamp;
}