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.l2jfree.gameserver.document.DocumentBase.java

final void attachFunc(Node n, Object template, String name) {
    final NamedNodeMap attrs = n.getAttributes();

    final Stats stat = Stats.valueOfXml(attrs.getNamedItem("stat").getNodeValue());
    final int ord = Integer.decode(attrs.getNamedItem("order").getNodeValue());
    final double lambda = getLambda(n, template);

    final Condition applayCond = parseConditionIfExists(n.getFirstChild(), template);

    final FuncTemplate ft = new FuncTemplate(applayCond, name, stat, ord, lambda);

    if (template instanceof L2Equip)
        ((L2Equip) template).attach(ft);

    else if (template instanceof L2Skill)
        ((L2Skill) template).attach(ft);

    else if (template instanceof EffectTemplate)
        ((EffectTemplate) template).attach(ft);

    else//from  w  w w  . j a va  2 s. c o m
        throw new IllegalStateException("Invalid template for a Func");
}

From source file:com.nexmo.sns.sdk.NexmoSnsClient.java

public SnsServiceResult submit(final Request request) throws Exception {

    log.info("NEXMO-REST-SNS-SERVICE-CLIENT ... submit request [ " + request.toString() + " ] ");

    // Construct a query string as a list of NameValuePairs

    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("cmd", request.getCommand()));
    if (request.getQueryParameters() != null)
        for (Map.Entry<String, String> entry : request.getQueryParameters().entrySet())
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

    //String baseUrl = https ? this.baseUrlHttps : this.baseUrlHttp;

    // 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;//from  ww w  .j  a  va 2 s.  c  o  m
    HttpPost method = new HttpPost(this.baseUrl);
    method.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    String url = this.baseUrl + "?" + 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-HTTPS for url [ " + url + " ] ");
        response = new BasicResponseHandler().handleResponse(httpResponse);
        log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
    } catch (Exception e) {
        log.info("communication failure: " + e);
        method.abort();
        return new SnsServiceResult(request.getCommand(), SnsServiceResult.STATUS_COMMS_FAILURE,
                "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, null, null);
    }

    // parse the response doc ...

    /*
    We receive a response from the api that looks like this, parse the document
    and turn it into an instance of SnsServiceResult
            
        <nexmo-sns>
            <command>subscribe|publish</command>
            <resultCode>0</resultCode>
            <resultMessage>OK!</resultMessage>
            <transactionId>${transaction-id}</transactionId>
            <subscriberArn>${subscriber}</subscriberArn>
        </nexmo-sns>
            
    */

    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);
        }
    }

    String command = null;
    int resultCode = -1;
    String resultMessage = null;
    String transactionId = null;
    String subscriberArn = null;

    NodeList replies = doc.getElementsByTagName("nexmo-sns");
    for (int i = 0; i < replies.getLength(); i++) {
        Node reply = replies.item(i);
        NodeList nodes = reply.getChildNodes();

        for (int i2 = 0; i2 < nodes.getLength(); i2++) {
            Node node = nodes.item(i2);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;
            if (node.getNodeName().equals("command")) {
                command = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            } else if (node.getNodeName().equals("resultCode")) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                try {
                    resultCode = Integer.parseInt(str);
                } catch (Exception e) {
                    log.error("xml parser .. invalid value in <resultCode> node [ " + str + " ] ");
                    resultCode = SnsServiceResult.STATUS_INTERNAL_ERROR;
                }
            } else if (node.getNodeName().equals("resultMessage")) {
                resultMessage = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            } else if (node.getNodeName().equals("transactionId")) {
                transactionId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            } else if (node.getNodeName().equals("subscriberArn")) {
                subscriberArn = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            } else
                log.error("xml parser .. unknown node found in nexmo-sns [ " + node.getNodeName() + " ] ");
        }
    }

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

    return new SnsServiceResult(command, resultCode, resultMessage, transactionId, subscriberArn);
}

From source file:com.android.flickrbot.FlickrClient.java

/**
 * Retrieves a URL that the user should browse to in order to authorize
 * their account with the program.  This stores a value in the class
 * variable frob, which is used in getAuthToken() later to complete the
 * authentication.//from   www .  ja v  a2  s  .com
 * 
 * @return URL that the program should redirect the user to, in order to complete authorization. 
 */
public String startAuthorization() throws Exception {
    m_database.deleteConfigValue(FROB_NAME);
    m_database.deleteConfigValue(AUTH_TOKEN_NAME);

    /**
     * Request a frob to identify the login session. This call requires 
     * a signature. The signature starts with your shared secret and
     * is followed by your API key and the method name. The API key and
     * method name are prepended by the words "api_key" and "method" as
     * shown in the following line.
    **/
    String methodGetFrob = "flickr.auth.getFrob";

    parameterList params = this.new parameterList();
    params.addParameter("api_key", KEY);
    params.addParameter("method", methodGetFrob);

    HttpClient client = new DefaultHttpClient();
    HttpGet getrequest = new HttpGet(REST_URL + params.getSignedList());

    // Send GET request
    HttpResponse response = client.execute(getrequest);
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode != HttpStatus.SC_OK) {
        throw new Exception("Method failed: " + response.getStatusLine());
    }
    InputStream rstream = null;

    // Get the response body
    rstream = response.getEntity().getContent();

    /**
     * Retrieve the XML response to the frob request and get the frob value.
     */
    Document parsedResponse = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(rstream);

    String frob;

    // Check if frob is in the response
    NodeList frobResponse = parsedResponse.getElementsByTagName("frob");
    Node frobNode = frobResponse.item(0);
    if (frobNode != null) {
        frob = frobNode.getFirstChild().getNodeValue();
        System.out.println("Successfully retrieved frob: " + frob);
        m_database.setConfigValue(FROB_NAME, frob);
    } else {
        // Get Flickr error code and msg
        NodeList error = parsedResponse.getElementsByTagName("err");
        String code = error.item(0).getAttributes().item(0).getNodeValue();
        String msg = error.item(0).getAttributes().item(1).getNodeValue();

        throw new Exception("Flickr request failed with error code: " + code + ", " + msg);
    }

    /**
     * Create a Flickr login link
     * http://www.flickr.com/services/auth/?api_key=[api_key]&perms=[perms]&frob=[frob]&api_sig=[api_sig] 
     */
    params.clear();
    params.addParameter("api_key", KEY);
    params.addParameter("frob", frob);
    params.addParameter("perms", "write");

    return AUTH_URL + params.getSignedList();
}

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

/**
 * Execute a file upload.//from   w  ww.  j a v  a 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 file
 *            A File resource pointing to the file you wish to upload. Make sure File.isFile() and File.canRead() are true for this resource.
 * @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 File file, final String filename,
        final long destinationId) throws IOException, MalformedURLException, FileNotFoundException {
    if (!file.isFile() || !file.canRead()) {
        throw new FileNotFoundException("Specified upload file is either not a file, or cannot be read");
    }

    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.authority(BoxConfig.getInstance().getUploadUrlAuthority());
    builder.path(BoxConfig.getInstance().getUploadUrlPath());
    builder.appendPath(action);
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(destinationId));
    builder.appendQueryParameter("file_name", filename);

    // Set up post body
    final HttpPost post = new HttpPost(builder.build().toString());
    final MultipartEntityWithProgressListener reqEntity = new MultipartEntityWithProgressListener(
            HttpMultipartMode.BROWSER_COMPATIBLE);
    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(filename, new FileBody(file) {

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

    // Send request
    final HttpResponse httpResponse;
    try {
        httpResponse = (new DefaultHttpClient()).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 (e.getMessage().equals(FileUploadListener.STATUS_CANCELLED)) {
            final FileResponseParser handler = new FileResponseParser();
            handler.setStatus(FileUploadListener.STATUS_CANCELLED);
            return handler;
        } else {
            throw e;
        }
    }

    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.panet.imeta.core.xml.XMLHandler.java

/**
 * Get the value of a tag in a node//w  ww . j  a v  a 2 s  .co m
 * 
 * @param n
 *            The node to look in
 * @param tag
 *            The tag to look for
 * @return The value of the tag or null if nothing was found.
 */
public static final String getTagValueWithAttribute(Node n, String tag, String attribute) {
    NodeList children;
    Node childnode;

    if (n == null)
        return null;

    children = n.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        childnode = children.item(i);
        if (childnode.getNodeName().equalsIgnoreCase(tag)
                && childnode.getAttributes().getNamedItem(attribute) != null) {
            if (childnode.getFirstChild() != null)
                return childnode.getFirstChild().getNodeValue();
        }
    }
    return null;
}

From source file:org.exist.xquery.modules.jfreechart.Configuration.java

/**
 * Helper method for getting the value of the (first) node.
 *///from  www. j  a  v  a  2  s . c o  m
private String getValue(Node child) {
    return child.getFirstChild().getNodeValue();
}

From source file:com.axelor.data.xml.XMLBinder.java

private Object value(List<Node> nodes, final XMLBind bind) {
    List<Object> result = Lists.transform(nodes, new Function<Node, Object>() {
        @Override//  w  w  w . ja  v a2s  .  c  o  m
        public Object apply(@Nullable Node input) {
            if (bind.getBindings() != null) {
                return toMap(input, bind);
            }
            if (input.getNodeType() == Node.ELEMENT_NODE) {
                Node child = input.getFirstChild();
                if (child.getNodeType() == Node.TEXT_NODE) {
                    return child.getNodeValue();
                }
                return toMap(input, bind);
            }
            return input.getNodeValue();
        }
    });
    if (result.size() == 1) {
        return result.get(0);
    }
    return result.size() == 0 ? null : result;
}

From source file:org.powertac.samplebroker.core.BrokerTournamentService.java

private boolean loginMaybe(String tsUrl) {
    try {/*from  w ww  .j a v  a2s.  c  o m*/
        // Build proper connection string to tournament scheduler for
        // login
        String restAuthToken = "authToken=" + this.authToken;
        String restTourneyName = "requestJoin=" + this.tourneyName;
        String restResponseType = "type=" + this.responseType;
        String finalUrl = tsUrl + "?" + restAuthToken + "&" + restTourneyName + "&" + restResponseType;
        log.info("Connecting to TS with " + finalUrl);
        log.info("Tournament : " + this.tourneyName);

        URL url = new URL(finalUrl);
        URLConnection conn = url.openConnection();

        // Get the response
        InputStream input = conn.getInputStream();

        if (this.responseType.compareTo("xml") == 0) {
            System.out.println("Parsing message..");
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(input);

            doc.getDocumentElement().normalize();
            System.out.println("login response: " + doc.toString());

            // Three different message types
            Node retryNode = doc.getElementsByTagName("retry").item(0);
            Node loginNode = doc.getElementsByTagName("login").item(0);
            Node doneNode = doc.getElementsByTagName("done").item(0);

            if (retryNode != null) {
                String checkRetry = retryNode.getFirstChild().getNodeValue();
                log.info("Retry message received for : " + checkRetry + " seconds");
                System.out.println("Retry message received for : " + checkRetry + " seconds");
                // Received retry message spin and try again
                spin(Integer.parseInt(checkRetry));
                return false;
            } else if (loginNode != null) {
                System.out.println("Login response received!");
                log.info("Login response received! ");

                String checkJmsUrl = doc.getElementsByTagName("jmsUrl").item(0).getFirstChild().getNodeValue();
                jmsUrl = checkJmsUrl;
                log.info("jmsUrl=" + checkJmsUrl);

                String checkBrokerQueue = doc.getElementsByTagName("queueName").item(0).getFirstChild()
                        .getNodeValue();
                brokerQueueName = checkBrokerQueue;
                log.info("brokerQueueName=" + checkBrokerQueue);

                String checkServerQueue = doc.getElementsByTagName("serverQueue").item(0).getFirstChild()
                        .getNodeValue();
                serverQueueName = checkServerQueue;
                log.info("serverQueueName=" + checkServerQueue);

                System.out.printf("Login message receieved!\n  jmsUrl=%s\n  queueName=%s\n  serverQueue=%s\n",
                        checkJmsUrl, checkBrokerQueue, checkServerQueue);
                return true;
            } else if (doneNode != null) {
                System.out.println("Recieved Done Message no more games!");
                maxTry = 0;
                return false;
            } else {
                log.fatal("Invalid message type recieved");
                return false;
            }
        } else { // response type was json parse accordingly
            String jsonTxt = IOUtils.toString(input);

            JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonTxt);
            int retry = json.getInt("retry");
            System.out.println("Retry message received for : " + retry + " seconds");
            spin(retry);
            return false;

            // TODO: Good Json Parsing
            // JEC: not sure why this is important...
        }
    } catch (Exception e) { // exception hit return false
        maxTry--;
        System.out.println("Retries left: " + maxTry);
        e.printStackTrace();
        log.fatal("Error making connection to Tournament Scheduler");
        log.fatal(e.getMessage());
        // Sleep and wait for network
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            return false;
        }
        return false;
    }
}

From source file:net.java.sen.StringTagger.java

/**
 * Read configuration file./*from w  w w .ja  va  2 s .com*/
 * 
 * @param confFile
 *            configuration file
 */
private void readConfig(String confFile) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        File cf = new File(confFile);
        String parent = cf.getParentFile().getParent();
        if (parent == null)
            parent = ".";
        Document doc = builder.parse(new InputSource(confFile));
        NodeList nl = doc.getFirstChild().getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            org.w3c.dom.Node n = nl.item(i);
            if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                String nn = n.getNodeName();
                String value = n.getFirstChild().getNodeValue();

                if (nn.equals("charset")) {
                    charset = value;
                } else if (nn.equals("unknown-pos")) {
                    unknownPos = value;
                } else if (nn.equals("tokenizer")) {
                    tokenizerClass = value;
                }

                if (nn.equals("dictionary")) {
                    // read nested tag in <dictinary>
                    NodeList dnl = n.getChildNodes();
                    for (int j = 0; j < dnl.getLength(); j++) {
                        org.w3c.dom.Node dn = dnl.item(j);
                        if (dn.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {

                            String dnn = dn.getNodeName();
                            if (dn.getFirstChild() == null) {
                                throw new IllegalArgumentException("element '" + dnn + "' is empty");
                            }
                            String dvalue = dn.getFirstChild().getNodeValue();

                            if (dnn.equals("connection-cost")) {
                                connectFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("double-array-trie")) {
                                doubleArrayFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("token")) {
                                tokenFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("pos-info")) {
                                posInfoFile = SenUtils.getPath(dvalue, parent);
                            } else if (dnn.equals("compound")) {
                                // do nothing
                            } else {
                                throw new IllegalArgumentException("element '" + dnn + "' is invalid");
                            }
                        }
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        throw new IllegalArgumentException(e.getMessage());
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException(e.getMessage());
    } catch (SAXException e) {
        throw new IllegalArgumentException(e.getMessage());
    } catch (IOException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}

From source file:com.l2jfree.gameserver.model.skills.conditions.ConditionParser.java

public final Condition parseConditionWithMessage(Node n, Object template) {
    Condition cond = parseExistingCondition(n.getFirstChild(), template);

    Node msg = n.getAttributes().getNamedItem("msg");
    if (msg != null)
        cond.setMessage(msg.getNodeValue());

    Node msgId = n.getAttributes().getNamedItem("msgId");
    if (msgId != null)
        cond.setMessageId(Integer.decode(msgId.getNodeValue()));

    return cond;//from   ww w  .  j  a v a  2s .co m
}