Example usage for org.w3c.dom Element getNodeName

List of usage examples for org.w3c.dom Element getNodeName

Introduction

In this page you can find the example usage for org.w3c.dom Element getNodeName.

Prototype

public String getNodeName();

Source Link

Document

The name of this node, depending on its type; see the table above.

Usage

From source file:eu.stratosphere.nephele.plugins.PluginManager.java

@SuppressWarnings("unchecked")
private Map<String, AbstractPluginLoader> loadPlugins(final File configFile,
        final PluginLookupService pluginLookupService) {

    final Map<String, AbstractPluginLoader> tmpPluginList = new LinkedHashMap<String, AbstractPluginLoader>();

    final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    // Ignore comments in the XML file
    docBuilderFactory.setIgnoringComments(true);
    docBuilderFactory.setNamespaceAware(true);

    try {// ww  w.j av a2s. c om

        final DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        final Document doc = builder.parse(configFile);

        if (doc == null) {
            LOG.error("Unable to load plugins: doc is null");
            return Collections.emptyMap();
        }

        final Element root = doc.getDocumentElement();
        if (root == null) {
            LOG.error("Unable to load plugins: root is null");
            return Collections.emptyMap();
        }

        if (!"plugins".equals(root.getNodeName())) {
            LOG.error("Unable to load plugins: unknown element " + root.getNodeName());
            return Collections.emptyMap();
        }

        final NodeList pluginNodes = root.getChildNodes();

        int pluginCounter = 0;
        for (int i = 0; i < pluginNodes.getLength(); ++i) {

            final Node pluginNode = pluginNodes.item(i);

            // Ignore text at this point
            if (pluginNode instanceof Text) {
                continue;
            }

            if (!"plugin".equals(pluginNode.getNodeName())) {
                LOG.error("Unable to load plugins: unknown element " + pluginNode.getNodeName());
                continue;
            }

            // Increase plugin counter
            ++pluginCounter;

            final NodeList pluginChildren = pluginNode.getChildNodes();
            String pluginName = null;
            String pluginClass = null;
            Configuration pluginConfiguration = null;

            for (int j = 0; j < pluginChildren.getLength(); ++j) {

                final Node pluginChild = pluginChildren.item(j);

                // Ignore text at this point
                if (pluginChild instanceof Text) {
                    continue;
                }

                if ("name".equals(pluginChild.getNodeName())) {
                    pluginName = getTextChild(pluginChild);
                    if (pluginName == null) {
                        LOG.error("Skipping plugin " + pluginCounter
                                + " from configuration because it does not provide a proper name");
                        continue;
                    }
                }

                if ("class".equals(pluginChild.getNodeName())) {
                    pluginClass = getTextChild(pluginChild);
                    if (pluginClass == null) {
                        LOG.error("Skipping plugin " + pluginCounter
                                + " from configuration because it does not provide a loader class");
                        continue;
                    }
                }

                if ("configuration".equals(pluginChild.getNodeName())) {

                    pluginConfiguration = new Configuration();

                    final NodeList configurationNodes = pluginChild.getChildNodes();
                    for (int k = 0; k < configurationNodes.getLength(); ++k) {

                        final Node configurationNode = configurationNodes.item(k);

                        // Ignore text at this point
                        if (configurationNode instanceof Text) {
                            continue;
                        }

                        if (!"property".equals(configurationNode.getNodeName())) {
                            LOG.error("Unexpected node " + configurationNode.getNodeName() + ", skipping...");
                            continue;
                        }

                        String key = null;
                        String value = null;

                        final NodeList properties = configurationNode.getChildNodes();
                        for (int l = 0; l < properties.getLength(); ++l) {

                            final Node property = properties.item(l);

                            // Ignore text at this point
                            if (configurationNode instanceof Text) {
                                continue;
                            }

                            if ("key".equals(property.getNodeName())) {
                                key = getTextChild(property);
                                if (key == null) {
                                    LOG.warn("Skipping configuration entry for plugin " + pluginName
                                            + " because of invalid key");
                                    continue;
                                }
                            }

                            if ("value".equals(property.getNodeName())) {
                                value = getTextChild(property);
                                if (value == null) {
                                    LOG.warn("Skipping configuration entry for plugin " + pluginName
                                            + " because of invalid value");
                                    continue;
                                }
                            }
                        }

                        if (key != null && value != null) {
                            pluginConfiguration.setString(key, value);
                        }
                    }

                }
            }

            if (pluginName == null) {
                LOG.error("Plugin " + pluginCounter + " does not provide a name, skipping...");
                continue;
            }

            if (pluginClass == null) {
                LOG.error("Plugin " + pluginCounter + " does not provide a loader class, skipping...");
                continue;
            }

            if (pluginConfiguration == null) {
                LOG.warn("Plugin " + pluginCounter
                        + " does not provide a configuration, using default configuration");
                pluginConfiguration = new Configuration();
            }

            Class<? extends AbstractPluginLoader> loaderClass;

            try {
                loaderClass = (Class<? extends AbstractPluginLoader>) Class.forName(pluginClass);
            } catch (ClassNotFoundException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            }

            if (loaderClass == null) {
                LOG.error("Unable to load plugin " + pluginName + ": loaderClass is null");
                continue;
            }

            Constructor<? extends AbstractPluginLoader> constructor;
            try {
                constructor = (Constructor<? extends AbstractPluginLoader>) loaderClass
                        .getConstructor(String.class, Configuration.class, PluginLookupService.class);
            } catch (SecurityException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            } catch (NoSuchMethodException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            }

            if (constructor == null) {
                LOG.error("Unable to load plugin " + pluginName + ": constructor is null");
                continue;
            }

            AbstractPluginLoader pluginLoader = null;

            try {
                pluginLoader = constructor.newInstance(pluginName, pluginConfiguration, pluginLookupService);
            } catch (IllegalArgumentException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            } catch (InstantiationException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            } catch (IllegalAccessException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            } catch (InvocationTargetException e) {
                LOG.error("Unable to load plugin " + pluginName + ": " + StringUtils.stringifyException(e));
                continue;
            }

            if (pluginLoader == null) {
                LOG.error("Unable to load plugin " + pluginName + ": pluginLoader is null");
                continue;
            }

            LOG.info("Successfully loaded plugin " + pluginName);
            tmpPluginList.put(pluginName, pluginLoader);
        }

    } catch (IOException e) {
        LOG.error("Error while loading plugins: " + StringUtils.stringifyException(e));
    } catch (SAXException e) {
        LOG.error("Error while loading plugins: " + StringUtils.stringifyException(e));
    } catch (ParserConfigurationException e) {
        LOG.error("Error while loading plugins: " + StringUtils.stringifyException(e));
    }

    return Collections.unmodifiableMap(tmpPluginList);
}

From source file:com.meidusa.amoeba.context.ProxyRuntimeContext.java

private ProxyServerConfig loadConfigurationFile(String fileName, DocumentBuilder db) {
    Document doc = null;/*w  w  w .  ja  v a 2  s.c  om*/
    InputStream is = null;
    ProxyServerConfig config = new ProxyServerConfig();
    try {
        is = new FileInputStream(new File(fileName));

        if (is == null) {
            throw new Exception("Could not open file " + fileName);
        }

        doc = db.parse(is);
    } catch (Exception e) {
        final String s = "Caught exception while loading file " + fileName;
        logger.error(s, e);
        throw new ConfigurationException(s, e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                logger.error("Unable to close input stream", e);
            }
        }
    }
    Element rootElement = doc.getDocumentElement();
    NodeList children = rootElement.getChildNodes();
    int childSize = children.getLength();

    for (int i = 0; i < childSize; i++) {
        Node childNode = children.item(i);

        if (childNode instanceof Element) {
            Element child = (Element) childNode;

            final String nodeName = child.getNodeName();
            if (nodeName.equals("proxy")) {
                loadProxyConfig(child, config);
            } else if (nodeName.equals("connectionManagerList")) {
                loadConnectionManagers(child, config);
            } else if (nodeName.equals("dbServerLoader")) {
                loadDbServerLoader(rootElement, config);
            } else if (nodeName.equals("queryRouter")) {
                loadQueryRouter(rootElement, config);
            }
        }
    }

    if (logger.isInfoEnabled()) {
        logger.info("Loaded Amoeba Proxy configuration from: " + fileName);
    }
    return config;
}

From source file:com.photon.phresco.framework.rest.api.BuildInfoService.java

private List<MinifyInfo> includesFiles(Element element, String appDirName) throws PhrescoException {
    List<MinifyInfo> consoldateInfo = new ArrayList<MinifyInfo>();
    String opFileLoc = "";
    try {//www . ja v a  2s.co m
        if (POM_AGGREGATIONS.equals(element.getNodeName())) {
            NodeList aggregationList = element.getElementsByTagName(POM_AGGREGATION);
            for (int i = 0; i < aggregationList.getLength(); i++) {
                MinifyInfo minifyInfo = new MinifyInfo();
                Element childNode = (Element) aggregationList.item(i);
                NodeList includeList = childNode.getElementsByTagName(POM_INCLUDES).item(0).getChildNodes();
                StringBuilder csvFileNames = new StringBuilder();
                String sep = "";
                for (int j = 0; j < includeList.getLength() - 1; j++) {//To convert select files to Comma seperated value
                    Element include = (Element) includeList.item(j);
                    String file = include.getTextContent()
                            .substring(include.getTextContent().lastIndexOf(FILE_SEPARATOR) + 1);
                    csvFileNames.append(sep);
                    csvFileNames.append(file);
                    sep = COMMA;
                }
                Element outputElement = (Element) childNode.getElementsByTagName(POM_OUTPUT).item(0);
                //To get compressed name with extension
                String opFileName = outputElement.getTextContent()
                        .substring(outputElement.getTextContent().lastIndexOf(FILE_SEPARATOR) + 1);
                String compressName = opFileName.substring(0, opFileName.indexOf("."));//To get only the compressed name without extension
                String compressedExtension = opFileName
                        .substring(opFileName.lastIndexOf(FrameworkConstants.DOT) + 1);//To get extension of compressed file
                opFileLoc = outputElement.getTextContent().substring(0,
                        outputElement.getTextContent().lastIndexOf(FILE_SEPARATOR) + 1);
                opFileLoc = opFileLoc.replace(MINIFY_OUTPUT_DIRECTORY,
                        FrameworkServiceUtil.getApplicationHome(appDirName).replace(File.separator,
                                FrameworkConstants.FORWARD_SLASH));

                if (JS.equals(compressedExtension)) {//if extension is js , add minified details to jsMap
                    minifyInfo.setFileType(JS);
                    minifyInfo.setCompressName(compressName);
                    minifyInfo.setCsvFileName(csvFileNames.toString().replace(HYPHEN_MIN, ""));
                    minifyInfo.setOpFileLoc(opFileLoc);
                } else {//if extension is CSS , add minified details to cssMap
                    minifyInfo.setFileType("css");
                    minifyInfo.setCompressName(compressName);
                    minifyInfo.setCsvFileName(csvFileNames.toString().replace(HYPHEN_MIN, ""));
                    minifyInfo.setOpFileLoc(opFileLoc);
                }
                consoldateInfo.add(minifyInfo);
            }
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return consoldateInfo;
}

From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java

public VerifyResult verify(final String number, final String brand, final String from, final int length,
        final Locale locale, final LineType type) throws IOException, SAXException {
    if (number == null || brand == null)
        throw new IllegalArgumentException("number and brand parameters are mandatory.");
    if (length > 0 && length != 4 && length != 6)
        throw new IllegalArgumentException("code length must be 4 or 6.");

    log.debug("HTTP-Number-Verify Client .. to [ " + number + " ] brand [ " + brand + " ] ");

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

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    params.add(new BasicNameValuePair("api_secret", this.apiSecret));

    params.add(new BasicNameValuePair("number", number));
    params.add(new BasicNameValuePair("brand", brand));

    if (from != null)
        params.add(new BasicNameValuePair("sender_id", from));

    if (length > 0)
        params.add(new BasicNameValuePair("code_length", String.valueOf(length)));

    if (locale != null)
        params.add(//from  www.j av  a 2  s  .c  o m
                new BasicNameValuePair("lg", (locale.getLanguage() + "-" + locale.getCountry()).toLowerCase()));

    if (type != null)
        params.add(new BasicNameValuePair("require_type", type.toString()));

    String verifyBaseUrl = this.baseUrl + PATH_VERIFY;

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

        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 ...
            return new VerifyResult(BaseResult.STATUS_COMMS_FAILURE, null,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true);
        }
    }

    Document doc;
    synchronized (this.documentBuilder) {
        doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
    }

    Element root = doc.getDocumentElement();
    if (!"verify_response".equals(root.getNodeName()))
        throw new IOException("No valid response found [ " + response + "] ");

    return parseVerifyResult(root);
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

private List<Element> getImportContent(Element importElement, PreparseContext context) throws Exception {
    String src = importElement.getAttribute("src");

    if (StringUtils.isNotEmpty(src)) {
        Expression expression = expressionHandler.compile(src);
        if (expression != null) {
            src = (String) expression.evaluate();
        }/*from   w ww .jav a2  s .c o m*/
    }

    if (StringUtils.isEmpty(src)) {
        throw new IllegalArgumentException("Import src undefined");
    }

    int i = src.lastIndexOf('#');
    if (i < 0) {
        throw new IllegalArgumentException("[groupId/componentId] missed");
    }

    String viewName = src.substring(0, i);
    String groupId = src.substring(i + 1);
    Assert.notEmpty(viewName, "Import viewName undefined.");
    Assert.notEmpty(groupId, "Import groupId/componentId undefined.");

    ViewConfigInfo viewConfigInfo = getViewConfigModelInfo(viewName);
    if (viewConfigInfo == null) {
        throw new XmlParseException("Import view not found [" + src + "].", context);
    }

    Document document = (Document) viewConfigInfo.getConfigModel();
    List<Element> importContent = null;
    Element groupStartElement = getGroupStartElement(document, groupId, context);
    if (groupStartElement != null) {
        importContent = new ArrayList<Element>();
        String nodeName = groupStartElement.getNodeName();
        if (nodeName.equals(XmlConstants.GROUP_START)) {
            boolean groupEndFound = false;
            Node node = groupStartElement.getNextSibling();
            while (true) {
                node = node.getNextSibling();
                if (node == null)
                    break;
                if (node instanceof Element) {
                    Element element = (Element) node;
                    nodeName = element.getNodeName();
                    if (nodeName.equals(XmlConstants.GROUP_END)) {
                        groupEndFound = true;
                        break;
                    } else if (nodeName.equals(XmlConstants.GROUP_START)) {
                        throw new IllegalArgumentException("Nesting <GroupStart> not supported.");
                    } else {
                        importContent.add(element);
                    }
                }
            }
            if (!groupEndFound) {
                throw new IllegalArgumentException("<GroupEnd> not found for [" + groupId + "].");
            }
        } else if (nodeName.equals(XmlConstants.GROUP_END) || nodeName.equals(XmlConstants.PLACE_HOLDER)
                || nodeName.equals(XmlConstants.PLACE_HOLDER_START)
                || nodeName.equals(XmlConstants.PLACE_HOLDER_END)) {
            // do nothing
        } else {
            importContent.add(groupStartElement);
        }
    }

    Resource dependentResource = viewConfigInfo.getResource();
    if (dependentResource != null) {
        context.getDependentResources().add(dependentResource);
    }
    return importContent;
}

From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java

public SearchResult[] search(String... requestIds) throws IOException, SAXException {
    if (requestIds == null || requestIds.length == 0)
        throw new IllegalArgumentException("request ID parameter is mandatory.");

    if (requestIds.length > MAX_SEARCH_REQUESTS)
        throw new IllegalArgumentException("too many request IDs. Max is " + MAX_SEARCH_REQUESTS);

    log.debug("HTTP-Number-Verify-Search Client .. for [ " + Arrays.toString(requestIds) + " ] ");

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

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    params.add(new BasicNameValuePair("api_secret", this.apiSecret));

    if (requestIds.length == 1) {
        params.add(new BasicNameValuePair("request_id", requestIds[0]));
    } else {//w w  w . j  ava 2  s.com
        for (String requestId : requestIds)
            params.add(new BasicNameValuePair("request_ids", requestId));
    }

    String verifySearchBaseUrl = this.baseUrl + PATH_VERIFY_SEARCH;

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

        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 ...
            return new SearchResult[] { new SearchResult(BaseResult.STATUS_COMMS_FAILURE, null, null, null,
                    null, 0, null, null, null, null, null, null, null,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true) };
        }
    }

    Document doc;
    synchronized (this.documentBuilder) {
        doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
    }

    Element root = doc.getDocumentElement();
    if ("verify_response".equals(root.getNodeName())) {
        // error response
        VerifyResult result = parseVerifyResult(root);
        return new SearchResult[] {
                new SearchResult(result.getStatus(), result.getRequestId(), null, null, null, 0, null, null,
                        null, null, null, null, null, result.getErrorText(), result.isTemporaryError()) };
    } else if (("verify_request").equals(root.getNodeName())) {
        return new SearchResult[] { parseSearchResult(root) };
    } else if ("verification_requests".equals(root.getNodeName())) {
        List<SearchResult> results = new ArrayList<>();

        NodeList fields = root.getChildNodes();
        for (int i = 0; i < fields.getLength(); i++) {
            Node node = fields.item(i);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;

            if ("verify_request".equals(node.getNodeName()))
                results.add(parseSearchResult((Element) node));
        }

        return results.toArray(new SearchResult[results.size()]);
    } else {
        throw new IOException("No valid response found [ " + response + "] ");
    }
}

From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java

public CheckResult check(final String requestId, final String code, final String ipAddress)
        throws IOException, SAXException {
    if (requestId == null || code == null)
        throw new IllegalArgumentException("request ID and code parameters are mandatory.");

    log.debug("HTTP-Number-Verify-Check Client .. for [ " + requestId + " ] code [ " + code + " ] ");

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

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    params.add(new BasicNameValuePair("api_secret", this.apiSecret));

    params.add(new BasicNameValuePair("request_id", requestId));
    params.add(new BasicNameValuePair("code", code));

    if (ipAddress != null)
        params.add(new BasicNameValuePair("ip_address", ipAddress));

    String verifyCheckBaseUrl = this.baseUrl + PATH_VERIFY_CHECK;

    // Now that we have generated a query string, we can instanciate a HttpClient,
    // construct a POST method and execute to submit the request
    String response = null;//from w  ww.ja va2 s .  c o  m
    for (int pass = 1; pass <= 2; pass++) {
        HttpPost httpPost = new HttpPost(verifyCheckBaseUrl);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpUriRequest method = httpPost;
        String url = verifyCheckBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8");

        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 ...
            return new CheckResult(BaseResult.STATUS_COMMS_FAILURE, null, 0, null,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true);
        }
    }

    Document doc;
    synchronized (this.documentBuilder) {
        doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
    }

    Element root = doc.getDocumentElement();
    if (!"verify_response".equals(root.getNodeName()))
        throw new IOException("No valid response found [ " + response + "] ");

    String eventId = null;
    int status = -1;
    float price = -1;
    String currency = null;
    String errorText = null;

    NodeList fields = root.getChildNodes();
    for (int i = 0; i < fields.getLength(); i++) {
        Node node = fields.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE)
            continue;

        String name = node.getNodeName();
        if ("event_id".equals(name)) {
            eventId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        } else if ("status".equals(name)) {
            String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            try {
                if (str != null)
                    status = Integer.parseInt(str);
            } catch (NumberFormatException e) {
                log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
                status = BaseResult.STATUS_INTERNAL_ERROR;
            }
        } else if ("price".equals(name)) {
            String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            try {
                if (str != null)
                    price = Float.parseFloat(str);
            } catch (NumberFormatException e) {
                log.error("xml parser .. invalid value in <price> node [ " + str + " ] ");
            }
        } else if ("currency".equals(name)) {
            currency = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        } else if ("error_text".equals(name)) {
            errorText = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
        }
    }

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

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

    return new CheckResult(status, eventId, price, currency, errorText, temporaryError);
}

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

private static void jsonToXml(Object object, String objectKey, Element parentElement, boolean modifyElement,
        boolean includeDataType, boolean compactArray, String arrayChildrenTag) throws JSONException {
    Engine.logBeans.trace("Converting JSON to XML: object=" + object + "; objectKey=\"" + objectKey + "\"");

    Document doc = parentElement.getOwnerDocument();

    if ("_attachments".equals(parentElement.getNodeName()) && "item".equals(arrayChildrenTag)
            && object instanceof JSONObject) {
        // special case when retrieving attachments with Couch : attachment name is the object key
        ((JSONObject) object).put("name", objectKey);
        objectKey = "attachment";
    }//from  w  w  w.j av a2 s  .co m

    // Normalize object key
    String originalObjectKey = objectKey;
    if (objectKey != null) {
        objectKey = StringUtils.normalize(objectKey);
    }

    // JSON object value case
    if (object instanceof JSONObject) {
        JSONObject json = (JSONObject) object;

        Element element = doc.createElement(objectKey == null ? "object" : objectKey);
        if (objectKey != null && !objectKey.equals(originalObjectKey)) {
            element.setAttribute("originalKeyName", originalObjectKey);
        }

        if (compactArray || modifyElement) {
            if (objectKey == null) {
                element = parentElement;
            } else {
                parentElement.appendChild(element);
            }
        } else {
            parentElement.appendChild(element);
        }

        if (includeDataType) {
            element.setAttribute("type", "object");
        }

        String[] keys = new String[json.length()];

        int index = 0;
        for (Iterator<String> i = GenericUtils.cast(json.keys()); i.hasNext();) {
            keys[index++] = i.next();
        }

        Arrays.sort(keys);

        for (String key : keys) {
            jsonToXml(json.get(key), key, element, false, includeDataType, compactArray, arrayChildrenTag);
        }
    }
    // Array value case
    else if (object instanceof JSONArray) {
        JSONArray array = (JSONArray) object;
        int len = array.length();

        Element arrayElement = parentElement;
        String arrayItemObjectKey = arrayChildrenTag;
        if (!(compactArray || modifyElement)) {
            arrayElement = doc.createElement(objectKey == null ? "array" : objectKey);
            if (objectKey != null && !objectKey.equals(originalObjectKey)) {
                arrayElement.setAttribute("originalKeyName", originalObjectKey);
            }
            parentElement.appendChild(arrayElement);

            if (includeDataType) {
                arrayElement.setAttribute("type", "array");
                arrayElement.setAttribute("length", "" + len);
            }
        } else if (objectKey != null) {
            arrayItemObjectKey = objectKey;
        }

        for (int i = 0; i < len; i++) {
            Object itemArray = array.get(i);
            jsonToXml(itemArray, arrayItemObjectKey, arrayElement, false, includeDataType, compactArray,
                    arrayChildrenTag);
        }
    } else {
        Element element = doc.createElement(objectKey == null ? "value" : objectKey);
        if (objectKey != null && !objectKey.equals(originalObjectKey)) {
            element.setAttribute("originalKeyName", originalObjectKey);
        }

        parentElement.appendChild(element);

        if (JSONObject.NULL.equals(object)) {
            object = null;
        }

        if (object != null) {
            Text text = doc.createTextNode(object.toString());
            element.appendChild(text);
        }

        if (includeDataType) {
            String objectType = object == null ? "null" : object.getClass().getCanonicalName();
            if (objectType.startsWith("java.lang.")) {
                objectType = objectType.substring(10);
            }
            element.setAttribute("type", objectType.toLowerCase());
        }
    }

}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

public static final String[] getRegardingObjectInfo(final ScribeObject cADbject) {

    /* Iterate on the Element list and create SOAP object */
    for (final Element element : cADbject.getXmlContent()) {

        if (logger.isDebugEnabled()) {
            logger.debug(//w w w  .  j a va2s  .  c  o m
                    "----Inside getRegardingObjectInfo: node: '" + element.getNodeName() + "' with value : '"
                            + element.getTextContent() + "' & Type: '" + element.getAttribute("type") + "'");
        }

        /* Check for regardingobjectid node */
        if (element.getNodeName().equalsIgnoreCase(regardingObjectidConst)) {

            String schema = null;

            /* Find schema */
            if (MSCRMObjectType.Account.toString().equalsIgnoreCase(element.getAttribute("type"))) {

                schema = MSCRMSchemaType.Account_Tasks.toString();

            } else if (MSCRMObjectType.Contact.toString().equalsIgnoreCase(element.getAttribute("type"))) {

                schema = MSCRMSchemaType.Contact_Tasks.toString();

            } else if (MSCRMObjectType.Lead.toString().equalsIgnoreCase(element.getAttribute("type"))) {

                schema = MSCRMSchemaType.Lead_Tasks.toString();

            } else if (MSCRMObjectType.Opportunity.toString().equalsIgnoreCase(element.getAttribute("type"))) {

                schema = MSCRMSchemaType.Opportunity_Tasks.toString();

            } else {
                /* Throw user error */
                throw new ScribeException(ScribeResponseCodes._1003
                        + "Following object type is not supported for object association by Scribe");
            }
            return new String[] { element.getTextContent(), element.getAttribute("type"), schema };

        } else {

            /* Ignore other elements */
            continue;
        }
    }

    return null;
}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

/**
 * /* www.j  a  v a 2s. co  m*/
 * @param account
 * @param accountId
 * @param cADbject
 * @return
 * @throws Exception
 */
public static final Lead createCRMObjectTypeLead(final ScribeObject cADbject,
        final String crmFieldIntraSeparator) throws Exception {

    /* Create xml beans object */
    final Lead lead = Lead.Factory.newInstance();

    /* Create new cursor */
    XmlCursor cursor = null;
    try {
        cursor = lead.newCursor();
        cursor.toFirstContentToken();
        final Node node = cursor.getDomNode();

        /* Get main namespace URl */
        if (node != null) {

            final String nsURL = node.getNamespaceURI();

            /* Iterate on the Element list and create SOAP object */
            for (final Element element : cADbject.getXmlContent()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("----Inside createCRMObject_Lead: adding node : " + element.getNodeName()
                            + " with value : " + element.getTextContent());
                }

                /* Get crm field */
                final String crmField = element.getNodeName();

                String crmFieldName = null;

                /* If field contains the type information */
                if (crmField != null && crmField.contains(crmFieldIntraSeparator)) {

                    /* Split the field and get name */
                    crmFieldName = crmField.split(crmFieldIntraSeparator)[0];
                } else {
                    crmFieldName = crmField;
                }

                /* Add all new nodes */
                cursor.beginElement(new QName(nsURL, crmFieldName));

                /* Set node attributes */
                if (element.getAttributes() != null) {

                    /* Get attribute map */
                    final NamedNodeMap namedNodeMap = element.getAttributes();

                    /* Interate over map */
                    for (int i = 0; i < namedNodeMap.getLength(); i++) {

                        /* Get respective item */
                        final Node namedNode = namedNodeMap.item(i);

                        if (logger.isDebugEnabled()) {
                            logger.debug("----Inside createCRMObject_Lead: adding attribute name : "
                                    + namedNode.getNodeName() + " with value: " + namedNode.getNodeValue());
                        }

                        /* Set node attribute */
                        cursor.insertAttributeWithValue(namedNode.getNodeName(), namedNode.getNodeValue());
                    }
                }

                /* Set node value */
                cursor.insertChars(element.getTextContent());

                /* Jump to next token */
                cursor.toNextToken();
            }
        }
    } finally {
        if (cursor != null) {
            cursor.dispose();
        }
    }
    return lead;
}