Example usage for org.w3c.dom Node getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:com.konakart.actions.gateways.AuthorizeNetBaseAction.java

/**
 * Common code to validate the gateway response.
 * /*ww w  .  j a  v a  2 s .c om*/
 * @param kkAppEng
 * @param msg
 * @param methodName
 * @param custId
 * @param profileId
 * @param doc
 * @return Returns true if there were no gateway errors
 */
protected boolean validateGatewayResponse(KKAppEng kkAppEng, StringBuffer msg, String methodName, int custId,
        String profileId, Document doc) {

    String resultCode = null;
    String code = null;
    String text = null;

    // get all elements
    int count = 0;
    NodeList list = doc.getElementsByTagName("*");
    for (int i = 0; i < list.getLength(); i++) {
        if (count == 3) {
            break;
        }
        Node node = list.item(i);
        String name = node.getNodeName();
        if (name != null) {
            if (name.equals("resultCode")) {
                Text datanode = (Text) node.getFirstChild();
                resultCode = datanode.getData();
                count++;
            } else if (name.equals("code")) {
                Text datanode = (Text) node.getFirstChild();
                code = datanode.getData();
                count++;
            } else if (name.equals("text")) {
                Text datanode = (Text) node.getFirstChild();
                text = datanode.getData();
                count++;
            }
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("AuthorizeNet " + methodName + " response data:"
                + "\n    resultCode                                   = " + resultCode
                + "\n    code                                         = " + code
                + "\n    text                                         = " + text);
    }

    if (resultCode != null && resultCode.equalsIgnoreCase("Error")) {
        String errorMsg = kkAppEng.getMsg("after.login.body.gateway.problem", new String[] { "" });
        addActionError(errorMsg);
        log.warn("AuthorizeNet " + methodName + " response data" + " for customer id : " + custId
                + ((profileId != null) ? (" profile id : " + profileId) : "")
                + "\n    resultCode                                   = " + resultCode
                + "\n    code                                         = " + code
                + "\n    text                                         = " + text);
        return false;
    }
    return true;
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderFE.java

private List<DownloadItem> retrieveList(String criterion) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    String url;/*  w w w  .jav a 2  s. c om*/
    if (validateEmail(criterion)) {
        url = FE_API_EMAIL;
    } else {
        url = FE_API_TAG;
    }
    url += URLEncoder.encode(criterion);
    Log.i(TAG, "Url: " + url);
    HttpGet httpget = new HttpGet(url);
    HttpResponse response;
    response = httpclient.execute(httpget);
    Log.i(TAG, "Response: " + response.getStatusLine().toString());
    HttpEntity entity = response.getEntity();

    if (entity == null) {
        throw new Exception("Null entity error");
    }

    InputStream instream = entity.getContent();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
    Document doc = documentBuilder.parse(instream);
    NodeList nodes = doc.getElementsByTagName("cardSet");
    nodes = doc.getElementsByTagName("error");

    if (nodes.getLength() > 0) {
        throw new Exception("Invalid user name or no such tag to search!");
    }

    List<DownloadItem> diList = new LinkedList<DownloadItem>();
    nodes = doc.getElementsByTagName("cardSet");

    int nodeNumber = nodes.getLength();
    for (int i = 0; i < nodeNumber; i++) {
        Node node = nodes.item(i);
        if (!node.hasChildNodes()) {
            continue;
        }
        NodeList childNodes = node.getChildNodes();

        int childNodeNumber = childNodes.getLength();
        DownloadItem di = new DownloadItem();
        for (int j = 0; j < childNodeNumber; j++) {
            Node childNode = childNodes.item(j);
            if (childNode.hasChildNodes()) {
                di.setType(DownloadItem.TYPE_DATABASE);
                if (childNode.getNodeName().equals("title")) {
                    di.setTitle(childNode.getFirstChild().getNodeValue());
                } else if (childNode.getNodeName().equals("cardSetId")) {
                    di.setAddress(FE_API_FLASHCARDS + childNode.getFirstChild().getNodeValue());
                } else if (childNode.getNodeName().equals("description")) {
                    di.setDescription(childNode.getFirstChild().getNodeValue());
                }
            }
        }
        if (!di.getTitle().equals("")) {
            diList.add(di);
        }
    }
    instream.close();
    return diList;
}

From source file:com.qwazr.extractor.parser.ImageParser.java

private void browseNodes(String path, final Node root, final ParserFieldsBuilder result) {
    if (root == null)
        return;/*w w w .j av a2 s  . c o m*/
    switch (root.getNodeType()) {
    case Node.TEXT_NODE:
        result.add(ParserField.newString(path, null), root.getNodeValue());
        break;
    case Node.ELEMENT_NODE:
        final NamedNodeMap nnm = root.getAttributes();
        if (nnm != null)
            for (int i = 0; i < nnm.getLength(); i++)
                browseNodes(path, nnm.item(i), result);
        Node child = root.getFirstChild();
        while (child != null) {
            browseNodes(path + "/" + child.getNodeName(), child, result);
            child = child.getNextSibling();
        }
        break;
    case Node.ATTRIBUTE_NODE:
        path = path + "#" + root.getNodeName();
        result.add(ParserField.newString(path, null), root.getNodeValue());
        break;
    default:
        throw new NotImplementedException("Unknown attribute: " + root.getNodeType());
    }
}

From source file:com.l2jfree.gameserver.datatables.MerchantPriceConfigTable.java

public void loadXML() throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);/*from w  w  w.  j a  v  a2 s  . c o m*/
    factory.setIgnoringComments(true);
    File file = new File(Config.DATAPACK_ROOT, "data/" + MPCS_FILE);
    if (file.exists()) {
        int defaultPriceConfigId;
        Document doc = factory.newDocumentBuilder().parse(file);

        Node n = doc.getDocumentElement();
        Node dpcNode = n.getAttributes().getNamedItem("defaultPriceConfig");
        if (dpcNode == null) {
            throw new IllegalStateException("merchantPriceConfig must define an 'defaultPriceConfig'");
        }

        defaultPriceConfigId = Integer.parseInt(dpcNode.getNodeValue());

        MerchantPriceConfig mpc;
        for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) {
            mpc = parseMerchantPriceConfig(n);
            if (mpc != null) {
                _mpcs.put(mpc.getId(), mpc);
            }
        }

        MerchantPriceConfig defaultMpc = this.getMerchantPriceConfig(defaultPriceConfigId);
        if (defaultMpc == null) {
            throw new IllegalStateException("'defaultPriceConfig' points to an non-loaded priceConfig");
        }
        _defaultMpc = defaultMpc;
    }
}

From source file:com.adaptris.util.text.xml.XPath.java

/**
 * returns an array of string values taken from a list of elements returned by
 * an xpath/*  w w w.jav a2s  .  com*/
 *
 * @param context the node to apply the XPath to
 * @param xpath the xpath to apply
 * @return the strings extracted
 * @throws XPathExpressionException on error
 */
public String[] selectMultipleTextItems(Node context, String xpath) throws XPathExpressionException {
    NodeList list = selectNodeList(context, xpath);
    String[] retArray = new String[list.getLength()];

    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        if (node != null) {
            if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                retArray[i] = node.getNodeValue();
            } else if (node.getNodeType() == Node.TEXT_NODE) {
                retArray[i] = node.getNodeValue();
            } else {
                node.normalize();
                Node text = node.getFirstChild();
                if (text != null) {
                    retArray[i] = text.getNodeValue();
                }
            }
        }
    }
    return retArray;
}

From source file:com.box.androidlib.BoxFileUpload.java

/**
 * Execute a file upload.//www .  j a va 2 s.c  om
 * 
 * @param action
 *            Set to {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD} or {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}
 * @param sourceInputStream
 *            Input stream targeting the data for the file you wish to create/upload to Box.
 * @param filename
 *            The desired filename on Box after upload (just the file name, do not include the path)
 * @param destinationId
 *            If action is {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD}, then this is the folder id where the file will uploaded to. If action is
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}, then this is the file_id that
 *            is being overwritten, or copied.
 * @return A FileResponseParser with information about the upload.
 * @throws IOException
 *             Can be thrown if there is no connection, or if some other connection problem exists.
 * @throws FileNotFoundException
 *             File being uploaded either doesn't exist, is not a file, or cannot be read
 * @throws MalformedURLException
 *             Make sure you have specified a valid upload action
 */
public FileResponseParser execute(final String action, final InputStream sourceInputStream,
        final String filename, final long destinationId)
        throws IOException, MalformedURLException, FileNotFoundException {

    if (!action.equals(Box.UPLOAD_ACTION_UPLOAD) && !action.equals(Box.UPLOAD_ACTION_OVERWRITE)
            && !action.equals(Box.UPLOAD_ACTION_NEW_COPY)) {
        throw new MalformedURLException("action must be upload, overwrite or new_copy");
    }

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(BoxConfig.getInstance().getUploadUrlScheme());
    builder.encodedAuthority(BoxConfig.getInstance().getUploadUrlAuthority());
    builder.path(BoxConfig.getInstance().getUploadUrlPath());
    builder.appendPath(action);
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(destinationId));
    if (action.equals(Box.UPLOAD_ACTION_OVERWRITE)) {
        builder.appendQueryParameter("file_name", filename);
    } else if (action.equals(Box.UPLOAD_ACTION_NEW_COPY)) {
        builder.appendQueryParameter("new_file_name", filename);
    }

    List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters();
    if (customQueryParams != null && customQueryParams.size() > 0) {
        for (BasicNameValuePair param : customQueryParams) {
            builder.appendQueryParameter(param.getName(), param.getValue());
        }
    }

    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        //            DevUtils.logcat("Uploading : " + filename + "  Action= " + action + " DestinionID + " + destinationId);
        DevUtils.logcat("Upload URL : " + builder.build().toString());
    }
    // Set up post body
    final HttpPost post = new HttpPost(builder.build().toString());
    final MultipartEntityWithProgressListener reqEntity = new MultipartEntityWithProgressListener(
            HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8));

    if (mListener != null && mHandler != null) {
        reqEntity.setProgressListener(new MultipartEntityWithProgressListener.ProgressListener() {

            @Override
            public void onTransferred(final long bytesTransferredCumulative) {
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        mListener.onProgress(bytesTransferredCumulative);
                    }
                });
            }
        });
    }

    reqEntity.addPart("file_name", new InputStreamBody(sourceInputStream, filename) {

        @Override
        public String getFilename() {
            return filename;
        }
    });
    post.setEntity(reqEntity);

    // Send request
    final HttpResponse httpResponse;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpClient.getParams(), BoxConfig.getInstance().getUserAgent());
    post.setHeader("Accept-Language", BoxConfig.getInstance().getAcceptLanguage());
    try {
        httpResponse = httpClient.execute(post);
    } catch (final IOException e) {
        // Detect if the download was cancelled through thread interrupt. See CountingOutputStream.write() for when this exception is thrown.
        if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
            //                DevUtils.logcat("IOException Uploading " + filename + " Exception Message: " + e.getMessage() + e.toString());
            DevUtils.logcat(" Exception : " + e.toString());
            e.printStackTrace();
            DevUtils.logcat("Upload URL : " + builder.build().toString());
        }
        if ((e.getMessage() != null && e.getMessage().equals(FileUploadListener.STATUS_CANCELLED))
                || Thread.currentThread().isInterrupted()) {
            final FileResponseParser handler = new FileResponseParser();
            handler.setStatus(FileUploadListener.STATUS_CANCELLED);
            return handler;
        } else {
            throw e;
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            httpClient.getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS);
        }
    }
    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        DevUtils.logcat("HTTP Response Code: " + httpResponse.getStatusLine().getStatusCode());
        Header[] headers = httpResponse.getAllHeaders();
        //            DevUtils.logcat("User-Agent : " + HttpProtocolParams.getUserAgent(httpClient.getParams()));
        //            for (Header header : headers) {
        //                DevUtils.logcat("Response Header: " + header.toString());
        //            }
    }

    // Server returned a 503 Service Unavailable. Usually means a temporary unavailability.
    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) {
        final FileResponseParser handler = new FileResponseParser();
        handler.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE);
        return handler;
    }

    String status = null;
    BoxFile boxFile = null;
    final InputStream is = httpResponse.getEntity().getContent();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    httpResponse.getEntity().consumeContent();
    final String xml = sb.toString();

    try {
        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()));
        final Node statusNode = doc.getElementsByTagName("status").item(0);
        if (statusNode != null) {
            status = statusNode.getFirstChild().getNodeValue();
        }
        final Element fileEl = (Element) doc.getElementsByTagName("file").item(0);
        if (fileEl != null) {
            try {
                boxFile = Box.getBoxFileClass().newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < fileEl.getAttributes().getLength(); i++) {
                boxFile.parseAttribute(fileEl.getAttributes().item(i).getNodeName(),
                        fileEl.getAttributes().item(i).getNodeValue());
            }
        }

        // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        if (status == null) {
            status = xml;
        }
    } catch (final SAXException e) {
        // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        status = xml;
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
    }
    final FileResponseParser handler = new FileResponseParser();
    handler.setFile(boxFile);
    handler.setStatus(status);
    return handler;
}

From source file:com.daneshzaki.tumblej.TumbleJ.java

/**
 * This method gets the posts from the tumblelog and returns an array of
 * Posts//from  www  .  j a  va2  s .  com
 */

public Post[] readPosts() throws Exception {

    // setup parser
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    // get posts at URL
    Document document = builder.parse(baseHostname + "/api/read");
    NodeList postNodes = document.getElementsByTagName("post");

    // create a post array to store posts
    Post[] posts = new Post[postNodes.getLength()];

    // get each post
    for (int i = 0; i < postNodes.getLength(); i++) {

        // parse post nodes to get contents
        Node node = postNodes.item(i);
        NodeList nodes = node.getChildNodes();

        posts[i] = new Post();

        // get post contents
        for (int k = 0; k < nodes.getLength(); k++) {
            Node topNode = nodes.item(k);

            if (topNode.getNodeName().equals("regular-title")) {
                posts[i].setTitle(topNode.getFirstChild().getNodeValue());

            } else if (topNode.getNodeName().equals("regular-body")) {
                // set post body
                posts[i].setBody(topNode.getFirstChild().getNodeValue());

            }

        }
    }

    return posts;

}

From source file:com.zoho.creator.jframework.XMLParser.java

static int getIntValue(Node node, int defaultValue) {
    if (node != null && node.getFirstChild() != null) {
        return Integer.parseInt(node.getFirstChild().getNodeValue());
    }//from  w w  w. j a  v  a 2s.  c o  m

    return defaultValue;
}

From source file:com.zoho.creator.jframework.XMLParser.java

private static long getLongValue(Node node, long defaultValue) {
    if (node != null && node.getFirstChild() != null) {
        return Long.parseLong(node.getFirstChild().getNodeValue());
    }/*w  w  w  . j  a  v a 2 s. co m*/
    return defaultValue;
}

From source file:cm.aptoide.pt.Aptoide.java

private String getXmlElement(String name)
        throws ParserConfigurationException, MalformedURLException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(new InputSource(new URL(LATEST_VERSION_CODE_URI).openStream()));
    dom.getDocumentElement().normalize();
    NodeList items = dom.getElementsByTagName(name);
    if (items.getLength() > 0) {
        Node item = items.item(0);
        Log.d("Aptoide-XmlElement Name", item.getNodeName());
        Log.d("Aptoide-XmlElement Value", item.getFirstChild().getNodeValue().trim());
        return item.getFirstChild().getNodeValue().trim();
    }/*from   w ww  .  j a  va2 s . c om*/
    return "0";
}