Example usage for org.w3c.dom Document getChildNodes

List of usage examples for org.w3c.dom Document getChildNodes

Introduction

In this page you can find the example usage for org.w3c.dom Document getChildNodes.

Prototype

public NodeList getChildNodes();

Source Link

Document

A NodeList that contains all children of this node.

Usage

From source file:com.cloud.network.cisco.CiscoVnmcConnectionImpl.java

private Map<String, String> checkResponse(String xmlResponse, String... keys) throws ExecutionException {
    Document xmlDoc = getDocument(xmlResponse);
    Map<String, String> result = new HashMap<String, String>();
    Node topElement = xmlDoc.getChildNodes().item(0);
    if (topElement != null) {
        for (String key : keys) {
            Node valueNode = topElement.getAttributes().getNamedItem(key);
            result.put(key, valueNode == null ? null : valueNode.getNodeValue());
        }/* w w  w  .  j  av  a 2s  .  c  o  m*/
    }
    return result;
}

From source file:com.github.podd.resources.RestletPoddClientImpl.java

public Representation doSPARQL2(final String queryString, final Collection<InferredOWLOntologyID> artifactIds)
        throws PoddException {
    this.log.debug("cookies: {}", this.currentCookies);

    final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_SPARQL));
    resource.getCookies().addAll(this.currentCookies);

    final Form form = new Form();
    form.add(PoddWebConstants.KEY_SPARQLQUERY, queryString);

    // TODO: Parse query to make sure it is syntactically valid before sending query
    resource.addQueryParameter(PoddWebConstants.KEY_SPARQLQUERY, queryString);

    try {/* www .  j a  va2 s  . c  o m*/
        final Representation get = resource.get(MediaType.APPLICATION_ALL_XML);
        /*
        try {
        String d = get.getText().replaceAll("(.*)version=(.*)", "");
        String f = d.replaceAll("(.*)sparql(.*)", "").replaceAll("(.*)result(.*)", "");
        System.out.println(f);
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        */

        try {
            DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

            InputStream in = IOUtils.toInputStream(get.getText());
            Document doc = dBuilder.parse(in);
            System.out.println("\r\n" + "============================== \r\n" + " PODD Query Results \r\n"
                    + "==============================");

            if (doc.hasChildNodes()) {
                printNote(doc.getChildNodes());
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return get;

    } catch (final ResourceException e) {
        if (e.getStatus().equals(Status.CLIENT_ERROR_PRECONDITION_FAILED)) {
            System.out.println("");
            System.out.println("Error: Access denied in server " + this.serverUrl
                    + " with the login credentials provided in ~/poddclient.properties.");
            // Precondition failed indicates that they do not have access to any artifacts, so
            // return empty results set
            return null;
        }

        System.out.println(e.toString());
    } catch (final UnsupportedRDFormatException e) {
        // Attempt to retry the request once to avoid random restlet failures stopping the
        // entire process
        try {
            final Representation get = resource.post(form.getWebRepresentation(CharacterSet.UTF_8),
                    RestletUtilMediaType.APPLICATION_RDF_JSON);

            // Pass the desired format to the get method of the ClientResource
            // final Representation get =
            // resource.get(RestletUtilMediaType.APPLICATION_RDF_JSON);

            final StringWriter writer = new StringWriter(4096);

            get.write(writer);
            return null;
        } catch (final ResourceException e1) {
            if (e1.getStatus().equals(Status.CLIENT_ERROR_PRECONDITION_FAILED)) {
                System.out.println("");
                System.out.println("Error: Access denied in server " + this.serverUrl
                        + " with login credentials provided in ~/poddclient.properties.");
                // Precondition failed indicates that they do not have access to any artifacts,
                // so
                // return empty results set
                return null;
            } else {
                System.out.println(e.toString());
            }
        } catch (final IOException | UnsupportedRDFormatException e1) {
            System.out.println(e.toString());
        }
    }
    return null;
}

From source file:com.github.podd.resources.RestletPoddClientImpl.java

public Representation doSPARQL3(final String queryString, final Collection<InferredOWLOntologyID> artifactIds)
        throws PoddException {
    this.log.debug("cookies: {}", this.currentCookies);
    //final Context context = new Context();
    //context.getParameters().add("socketTimeout", "10000");
    //context.getParameters().add("connectionTimeout", "10000"); 
    final ClientResource resource = new ClientResource(this.getUrl(PATH_SPARQL2));

    resource.getCookies().addAll(this.currentCookies);

    final Form form = new Form();
    form.add(PoddWebConstants.KEY_SPARQLQUERY, queryString);

    // TODO: Parse query to make sure it is syntactically valid before sending query
    resource.addQueryParameter(PoddWebConstants.KEY_SPARQLQUERY, queryString);

    try {/*from   www  .  jav a  2  s .co m*/
        final Representation get = resource.get(MediaType.APPLICATION_ALL_XML);
        /*
        try {
         String d = get.getText().replaceAll("(.*)version=(.*)", "");
         String f = d.replaceAll("(.*)sparql(.*)", "").replaceAll("(.*)result(.*)", "");
         System.out.println(f);
        } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }
        */

        try {
            DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String d = get.getText().replaceAll("(.*)version=(.*)", "");
            String f = d.replaceAll("(.*)sparql(.*)", "");
            InputStream in = IOUtils
                    .toInputStream("<?xml version='1.0' encoding='UTF-8'?>" + " <r>" + f + " </r>", "UTF-8");
            Document doc = dBuilder.parse(in);
            System.out.println("\r\n" + "============================== \r\n" + " PODD Query Results \r\n"
                    + "==============================");

            if (doc.hasChildNodes()) {
                printNote3(doc.getChildNodes());
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return get;

    } catch (final ResourceException e) {
        if (e.getStatus().equals(Status.CLIENT_ERROR_PRECONDITION_FAILED)) {
            System.out.println("");
            System.out.println("Error: Access denied in server " + this.serverUrl
                    + " with the login credentials provided in ~/poddclient.properties.");
            // Precondition failed indicates that they do not have access to any artifacts, so
            // return empty results set
            return null;
        }

        System.out.println(e.toString());
    } catch (final UnsupportedRDFormatException e) {
        // Attempt to retry the request once to avoid random restlet failures stopping the
        // entire process
        try {
            final Representation get = resource.post(form.getWebRepresentation(CharacterSet.UTF_8),
                    RestletUtilMediaType.APPLICATION_RDF_JSON);

            // Pass the desired format to the get method of the ClientResource
            // final Representation get =
            // resource.get(RestletUtilMediaType.APPLICATION_RDF_JSON);

            final StringWriter writer = new StringWriter(4096);

            get.write(writer);
            return null;
        } catch (final ResourceException e1) {
            if (e1.getStatus().equals(Status.CLIENT_ERROR_PRECONDITION_FAILED)) {
                System.out.println("");
                System.out.println("Error: Access denied in server " + this.serverUrl
                        + " with login credentials provided in ~/poddclient.properties.");
                // Precondition failed indicates that they do not have access to any artifacts,
                // so
                // return empty results set
                return null;
            } else {
                System.out.println("Error: Unable to find the requested data in PODD");
                System.out.println(e.toString());
            }
        } catch (final IOException | UnsupportedRDFormatException e1) {
            System.out.println("Error: Unable to find the requested data in PODD");
            System.out.println(e.toString());
            return null;
        }

    }

    // Your database code here

    return null;
}

From source file:info.ajaxplorer.client.http.PydioClient.java

public Object applyAction(String method, String[] names, String[] types, Object[] values) throws Exception {

    String rules = "{\"listNodes\": {\"action\": \"ls\",\"params\": {\"dir\": {\"name\": \"dir\",\"type\": \"string\",\"mandatory\": false,\"default\": \"\"},\"file\": {\"name\": \"file\",\"type\": \"string\",\"mandatory\": false,\"default\": \"\"},\"nodes\": {\"name\": \"nodes\",\"type\": \"AJXP_NODE[]\",\"mandatory\": false,\"default\": \"\"},\"options\": {\"name\": \"options\",\"type\": \"string\",\"mandatory\": false,\"default\": \"al\"},\"recursive\": {\"name\": \"recursive\",\"type\": \"boolean\",\"mandatory\": false,\"default\": \"false\"},\"remote_order\": {\"name\": \"remote_order\",\"type\": \"boolean\",\"mandatory\": false,\"default\": \"false\"},\"order_column\": {\"name\": \"order_column\",\"type\": \"string\",\"mandatory\": false,\"default\": \"\"},\"order_direction\": {\"name\": \"order_direction\",\"type\": \"string\",\"mandatory\": false,\"default\": \"\"}},\"output\": \"AJXP_NODE[]\"},\"upload\": {\"action\": \"upload\",\"params\": {      \"node\": {\"name\": \"node\",\"type\": \"string\",\"mandatory\": false,\"default\": \"\"}},\"output\": \"xml\"},\"download\": {\"action\": \"download\",\"params\": {\"nodes\": {\"name\": \"nodes\",\"type\": \"AJXP_NODE[]\",\"mandatory\": true,\"default\": \"\"}},\"output\": \"stream\"},\"mkdir\": {\"action\": \"mkdir\",\"params\": {\"dir\": {\"name\": \"dir\",\"type\": \"AJXP_NODE\",\"mandatory\": true,\"default\": \"\"},\"dirname\": {\"name\": \"dirname\",\"type\": \"string\",\"mandatory\": true,\"default\": \"\"}},\"output\": \"xml\"},\"mkfile\": {\"action\": \"mkfile\",\"params\": {\"node\": {\"name\": \"node\",\"type\": \"AJXP_NODE\",\"mandatory\": false,\"default\": \"\"}},\"output\": \"xml\"},\"search\": {\"action\": \"search\",\"params\": {\"query\": {\"name\": \"query\",\"type\": \"string\",\"mandatory\": false,\"default\": \"\"}},\"output\": \"xml\"},\"searchByKeyword\": {\"action\": \"search_by_keyword\",\"params\": {\"query\": {\"name\": \"query\",\"type\": \"string\",\"mandatory\": false,\"default\": \"\"}},\"output\": \"xml\"}}";

    if (dictionary == null) {
        dictionary = new JSONObject(rules.replaceAll("\n", "\\n"));
    }//from w w  w .  j  a  v a  2 s .  c  om
    if (!dictionary.has(method)) {
        return null;
    }

    JSONObject m = dictionary.getJSONObject(method);
    String action = (String) m.get("action");
    JSONObject action_params = m.getJSONObject("params");
    String output = (String) m.get("output");

    int i = 0;
    Iterator it = action_params.keys();
    try {
        while (it.hasNext()) {
            JSONObject param = action_params.getJSONObject((String) it.next());
            if ((Boolean) param.get("mandatory")) {
                i++;
            }
        }
    } catch (Exception e) {

    }

    if (i > 0 && (values == null || types == null) || values.length < i || types.length < i)
        return null;

    Map<String, String> post_params = new HashMap<String, String>();
    post_params.put("action", action);

    i = 0;
    it = action_params.keys();
    while (it.hasNext()) {
        JSONObject param = action_params.getJSONObject((String) it.next());
        String name = (String) param.get("name");
        String type = (String) param.get("type");

        if (types[i].equals(type) && names[i].equals(name)) {
            if (type.equals("AJXP_NODE")) {
                post_params.put(name, ((Node) values[i]).getPath());
            }
            if (type.equals("AJXP_NODE[]")) {
                //
            } else {
                if (((String) values[i]).equals("")) {
                    post_params.put("action", "get_xml_registry");
                    post_params.put("xPath", "user/repositories");
                } else {
                    post_params.put(name, (String) values[i]);
                }
            }
            i++;
            if (names.length - 1 < i)
                break;
        } else {

        }

    }

    RestRequest rest = new RestRequest();
    URI uri = AjxpAPI.returnUriFromString(getAPIUrl());

    if (output.equals("xml")) {
        return rest.getDocumentContent(uri, post_params);

    } else if (output.equals("AJXP_NODE[]")) {

        Document doc = rest.getDocumentContent(uri, post_params);
        NodeList children = doc.getDocumentElement().getChildNodes();

        ArrayList<Node> nodes = new ArrayList<Node>();

        if (children.getLength() != 0) {
            NodeList repos = doc.getDocumentElement().getElementsByTagName("repositories");
            if (repos.getLength() != 0) {
                //get repositoriy list
                repos = repos.item(0).getChildNodes();
                for (int j = 0; j < repos.getLength(); j++) {
                    org.w3c.dom.Node xmlNode = repos.item(j);
                    Node repository = new Node(Node.NODE_TYPE_REPOSITORY, "", null);
                    repository.initFromXmlNode(xmlNode);
                    nodes.add(repository);
                }
            }

            if (doc.getDocumentElement().getNodeName().equals("tree")) {
                //dir list               
                NodeList entries = doc.getChildNodes();
                for (int j = 0; j < entries.getLength(); j++) {
                    org.w3c.dom.Node xmlNode = entries.item(j);
                    Node ajxpNode = new Node(Node.NODE_TYPE_ENTRY, "", null);
                    ajxpNode.initFromXmlNode(xmlNode);
                    nodes.add(ajxpNode);
                }
            }
        }

        return nodes;

    } else if (output.equals("json")) {
        return rest.getJSonContent(uri, post_params);
    } else if (output.equals("stream")) {

    }

    return null;
}

From source file:org.openremote.android.test.console.net.ORConnectionTest.java

private void assertOpenRemoteRootElement(Document doc) {
    NodeList list = doc.getElementsByTagName("openremote");

    assertTrue("Expected to find exactly one <openremote> element, got " + list.getLength(),
            list.getLength() == 1);//from   w  w  w  .j ava2 s  .  co m

    list = doc.getChildNodes();
    int foundRootElement = 0;

    for (int cindex = 0; cindex < list.getLength(); cindex++) {
        if (list.item(cindex).getNodeType() == Node.ELEMENT_NODE)
            ++foundRootElement;
    }

    assertTrue("Expected exactly one child element on document, got " + foundRootElement,
            foundRootElement == 1);
}

From source file:ffx.ui.ModelingPanel.java

private void initialize() {
    // Command Description
    descriptTextArea = new JTextArea();
    descriptTextArea.setEditable(false);
    descriptTextArea.setLineWrap(true);// w w w  .  j av a 2 s. c  o  m
    descriptTextArea.setWrapStyleWord(true);
    descriptTextArea.setDoubleBuffered(true);
    Insets insets = descriptTextArea.getInsets();
    insets.set(5, 5, 5, 5);
    descriptTextArea.setMargin(insets);
    descriptScrollPane = new JScrollPane(descriptTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    descriptScrollPane.setBorder(etchedBorder);
    // Command Input
    commandTextArea = new JTextArea();
    commandTextArea.setEditable(false);
    commandTextArea.setLineWrap(true);
    commandTextArea.setWrapStyleWord(true);
    commandTextArea.setDoubleBuffered(true);
    commandTextArea.setMargin(insets);
    // Command Options
    optionsTabbedPane = new JTabbedPane();
    statusLabel = new JLabel();
    statusLabel.setBorder(etchedBorder);
    statusLabel.setToolTipText("  Modeling command that will be executed");
    commandPanel = new JPanel(flowLayout);
    commandPanel.add(optionsTabbedPane);
    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, commandPanel, descriptScrollPane);
    splitPane.setContinuousLayout(true);
    splitPane.setResizeWeight(1.0d);
    splitPane.setOneTouchExpandable(true);
    setLayout(new BorderLayout());
    add(splitPane, BorderLayout.CENTER);
    add(statusLabel, BorderLayout.SOUTH);
    // Initialize the Amino/Nucleic Acid ComboBox.
    acidComboBox.setEditable(false);
    acidComboBox.setMaximumSize(sizer.getPreferredSize());
    acidComboBox.setPreferredSize(sizer.getPreferredSize());
    acidComboBox.setMinimumSize(sizer.getPreferredSize());
    acidComboBox.setFont(Font.decode("Monospaced"));
    acidTextField.setMaximumSize(sizer.getPreferredSize());
    acidTextField.setMinimumSize(sizer.getPreferredSize());
    acidTextField.setPreferredSize(sizer.getPreferredSize());
    acidTextArea.setEditable(false);
    acidTextArea.setWrapStyleWord(true);
    acidTextArea.setLineWrap(true);
    acidTextArea.setFont(Font.decode("Monospaced"));
    acidScrollPane = new JScrollPane(acidTextArea);
    Dimension d = new Dimension(300, 400);
    acidScrollPane.setPreferredSize(d);
    acidScrollPane.setMaximumSize(d);
    acidScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    // Load the FFX commands.xml file that defines FFX commands.
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new DTDResolver());
        URL comURL = getClass().getClassLoader().getResource("ffx/ui/commands/commands.xml");
        Document doc = db.parse(comURL.openStream());
        NodeList nodelist = doc.getChildNodes();
        Node commandroot = null;
        for (int i = 0; i < nodelist.getLength(); i++) {
            commandroot = nodelist.item(i);
            if (commandroot.getNodeName().equals("FFXCommands") && commandroot instanceof Element) {
                break;
            }
        }
        if (commandroot == null || !(commandroot instanceof Element)) {
            commandList = null;
        }
        commandList = ((Element) commandroot).getElementsByTagName("Command");
    } catch (ParserConfigurationException | SAXException | IOException e) {
        System.err.println(e);
    } finally {
        if (commandList == null) {
            System.out.println("Force Field X commands.xml could not be parsed.");
            logger.severe("Force Field X will exit.");
            System.exit(-1);
        }
    }
    // Create a ComboBox with commands specific to each type of coordinate
    // file.
    xyzCommands = new JComboBox<>();
    intCommands = new JComboBox<>();
    arcCommands = new JComboBox<>();
    pdbCommands = new JComboBox<>();
    anyCommands = new JComboBox<>();
    Element command;
    String name;
    int numcommands = commandList.getLength();
    for (int i = 0; i < numcommands; i++) {
        command = (Element) commandList.item(i);
        name = command.getAttribute("name");
        String temp = command.getAttribute("fileType");
        if (temp.contains("ANY")) {
            temp = "XYZ INT ARC PDB";
            anyCommands.addItem(name);
        }
        String[] types = temp.split(" +");
        for (String type : types) {
            if (type.contains("XYZ")) {
                xyzCommands.addItem(name);
            }
            if (type.contains("INT")) {
                intCommands.addItem(name);
            }
            if (type.contains("ARC")) {
                arcCommands.addItem(name);
            }
            if (type.contains("PDB")) {
                pdbCommands.addItem(name);
            }
        }
    }
    initCommandComboBox(xyzCommands);
    initCommandComboBox(intCommands);
    initCommandComboBox(arcCommands);
    initCommandComboBox(pdbCommands);
    initCommandComboBox(anyCommands);
    currentCommandBox = anyCommands;
    activeCommand = (String) anyCommands.getSelectedItem();
    // Load the default Command.
    loadCommand();
    // Load the default Log File Settings.
    logSettings.setActionCommand("LogSettings");
    loadLogSettings();

    // Create the Toolbar.
    toolBar = new JToolBar("Modeling Commands", JToolBar.HORIZONTAL);
    toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
    jbLaunch = new JButton(new ImageIcon(getClass().getClassLoader().getResource("ffx/ui/icons/cog_go.png")));
    jbLaunch.setActionCommand("Launch");
    jbLaunch.setToolTipText("Launch the Force Field X Command");
    jbLaunch.addActionListener(this);
    insets.set(2, 2, 2, 2);
    jbLaunch.setMargin(insets);
    toolBar.add(jbLaunch);
    jbStop = new JButton(new ImageIcon(getClass().getClassLoader().getResource("ffx/ui/icons/stop.png")));
    jbStop.setActionCommand("End");
    jbStop.setToolTipText("Terminate the Current Force Field X Command");
    jbStop.addActionListener(this);
    jbStop.setMargin(insets);
    jbStop.setEnabled(false);
    toolBar.add(jbStop);
    toolBar.addSeparator();
    toolBar.add(anyCommands);
    currentCommandBox = anyCommands;
    toolBar.addSeparator();
    /*
     toolBar.add(logSettings);
     JButton jbdelete = new JButton(new ImageIcon(getClass().getClassLoader().getResource("ffx/ui/icons/page_delete.png")));
     jbdelete.setActionCommand("Delete");
     jbdelete.setToolTipText("Delete Log Files");
     jbdelete.addActionListener(this);
     jbdelete.setMargin(insets);
     toolBar.add(jbdelete);
     toolBar.addSeparator();
     */
    ImageIcon icinfo = new ImageIcon(getClass().getClassLoader().getResource("ffx/ui/icons/information.png"));
    descriptCheckBox = new JCheckBoxMenuItem(icinfo);
    descriptCheckBox.addActionListener(this);
    descriptCheckBox.setActionCommand("Description");
    descriptCheckBox.setToolTipText("Show/Hide Modeling Command Descriptions");
    descriptCheckBox.setMargin(insets);
    toolBar.add(descriptCheckBox);
    toolBar.add(new JLabel(""));
    toolBar.setBorderPainted(false);
    toolBar.setFloatable(false);
    toolBar.setRollover(true);
    add(toolBar, BorderLayout.NORTH);
    // Load ModelingPanel preferences.
    Preferences prefs = Preferences.userNodeForPackage(ffx.ui.ModelingPanel.class);
    descriptCheckBox.setSelected(!prefs.getBoolean("JobPanel_description", true));
    descriptCheckBox.doClick();
}

From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java

/**
 * /*from  ww  w .  ja v a 2 s  . com*/
 * 
 * @param limit
 *             
 * @param marker
 *             
 * 
 * @return 0 
 * @throws IOException
 *              IO
 * @throws HttpException
 *              Http
 * @throws FilesExcepiton
 *              
 * @throws FilesAuthorizationException
 *              
 */
public List<FilesContainerInfo> listContainersInfo(int limit, String marker)
        throws IOException, HttpException, FilesAuthorizationException, FilesException {
    if (!this.isLoggedin()) {
        throw new FilesAuthorizationException("You must be logged in", null, null);
    }
    HttpGet method = null;
    try {
        LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();
        if (limit > 0) {
            parameters.add(new BasicNameValuePair("limit", String.valueOf(limit)));
        }
        if (marker != null) {
            parameters.add(new BasicNameValuePair("marker", marker));
        }
        parameters.add(new BasicNameValuePair("format", "xml"));
        String uri = makeURI(storageURL, parameters);
        method = new HttpGet(uri);
        method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
        method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
        FilesResponse response = new FilesResponse(client.execute(method));

        if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            method.removeHeaders(FilesConstants.X_AUTH_TOKEN);
            if (login()) {
                method = new HttpGet(uri);
                method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
                method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
                response = new FilesResponse(client.execute(method));
            } else {
                throw new FilesAuthorizationException("Re-login failed", response.getResponseHeaders(),
                        response.getStatusLine());
            }
        }

        if (response.getStatusCode() == HttpStatus.SC_OK) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(response.getResponseBodyAsStream());

            NodeList nodes = document.getChildNodes();
            Node accountNode = nodes.item(0);
            if (!"account".equals(accountNode.getNodeName())) {
                logger.error("Got unexpected type of XML");
                return null;
            }
            ArrayList<FilesContainerInfo> containerList = new ArrayList<FilesContainerInfo>();
            NodeList containerNodes = accountNode.getChildNodes();
            for (int i = 0; i < containerNodes.getLength(); ++i) {
                Node containerNode = containerNodes.item(i);
                if (!"container".equals(containerNode.getNodeName()))
                    continue;
                String name = null;
                int count = -1;
                long size = -1;
                NodeList objectData = containerNode.getChildNodes();
                for (int j = 0; j < objectData.getLength(); ++j) {
                    Node data = objectData.item(j);
                    if ("name".equals(data.getNodeName())) {
                        name = data.getTextContent();
                    } else if ("bytes".equals(data.getNodeName())) {
                        size = Long.parseLong(data.getTextContent());
                    } else if ("count".equals(data.getNodeName())) {
                        count = Integer.parseInt(data.getTextContent());
                    } else {
                        logger.debug("Unexpected container-info tag:" + data.getNodeName());
                    }
                }
                if (name != null) {
                    FilesContainerInfo obj = new FilesContainerInfo(name, count, size);
                    containerList.add(obj);
                }
            }
            return containerList;
        } else if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            return new ArrayList<FilesContainerInfo>();
        } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new FilesNotFoundException("Account not Found", response.getResponseHeaders(),
                    response.getStatusLine());
        } else {
            throw new FilesException("Unexpected Return Code", response.getResponseHeaders(),
                    response.getStatusLine());
        }
    } catch (Exception ex) {
        throw new FilesException("Unexpected problem, probably in parsing Server XML", ex);
    } finally {
        if (method != null)
            method.abort();
    }
}

From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java

/**
 * //from w w  w  .  j  a va  2s.c  om
 * 
 * @param container
 *             
 * @param startsWith
 *             
 * @param path
 *             
 * @param limit
 *             
 * @param marker
 *             markerlimit
 * @param delimter
 *             
 * 
 * @return A list of FilesObjects starting with the given string
 * @throws IOException
 *              IO
 * @throws HttpException
 *              Http
 * @throws FilesExcepiton
 *              
 * @throws FilesAuthorizationException
 *              
 */
public List<FilesObject> listObjectsStartingWith(String container, String startsWith, String path, int limit,
        String marker, Character delimiter) throws IOException, FilesException {
    if (!this.isLoggedin()) {
        throw new FilesAuthorizationException("You must be logged in", null, null);
    }
    if (!isValidContainerName(container)) {
        throw new FilesInvalidNameException(container);
    }
    HttpGet method = null;
    try {
        LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();
        parameters.add(new BasicNameValuePair("format", "xml"));
        if (startsWith != null) {
            parameters.add(new BasicNameValuePair(FilesConstants.LIST_CONTAINER_NAME_QUERY, startsWith));
        }
        if (path != null) {
            parameters.add(new BasicNameValuePair("path", path));
        }
        if (limit > 0) {
            parameters.add(new BasicNameValuePair("limit", String.valueOf(limit)));
        }
        if (marker != null) {
            parameters.add(new BasicNameValuePair("marker", marker));
        }
        if (delimiter != null) {
            parameters.add(new BasicNameValuePair("delimiter", delimiter.toString()));
        }

        String uri = parameters.size() > 0 ? makeURI(storageURL + "/" + sanitizeForURI(container), parameters)
                : storageURL;
        method = new HttpGet(uri);
        method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
        method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
        FilesResponse response = new FilesResponse(client.execute(method));

        if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            method.removeHeaders(FilesConstants.X_AUTH_TOKEN);
            if (login()) {
                method = new HttpGet(uri);
                method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
                method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
                response = new FilesResponse(client.execute(method));
            } else {
                throw new FilesAuthorizationException("Re-login failed", response.getResponseHeaders(),
                        response.getStatusLine());
            }
        }

        if (response.getStatusCode() == HttpStatus.SC_OK) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(response.getResponseBodyAsStream());

            NodeList nodes = document.getChildNodes();
            Node containerList = nodes.item(0);
            if (!"container".equals(containerList.getNodeName())) {
                logger.error("Got unexpected type of XML");
                return null;
            }
            ArrayList<FilesObject> objectList = new ArrayList<FilesObject>();
            NodeList objectNodes = containerList.getChildNodes();
            for (int i = 0; i < objectNodes.getLength(); ++i) {
                Node objectNode = objectNodes.item(i);
                String nodeName = objectNode.getNodeName();
                if (!("object".equals(nodeName) || "subdir".equals(nodeName)))
                    continue;
                String name = null;
                String eTag = null;
                long size = -1;
                String mimeType = null;
                String lastModified = null;
                NodeList objectData = objectNode.getChildNodes();
                if ("subdir".equals(nodeName)) {
                    size = 0;
                    mimeType = "application/directory";
                    name = objectNode.getAttributes().getNamedItem("name").getNodeValue();
                }
                for (int j = 0; j < objectData.getLength(); ++j) {
                    Node data = objectData.item(j);
                    if ("name".equals(data.getNodeName())) {
                        name = data.getTextContent();
                    } else if ("content_type".equals(data.getNodeName())) {
                        mimeType = data.getTextContent();
                    } else if ("hash".equals(data.getNodeName())) {
                        eTag = data.getTextContent();
                    } else if ("bytes".equals(data.getNodeName())) {
                        size = Long.parseLong(data.getTextContent());
                    } else if ("last_modified".equals(data.getNodeName())) {
                        lastModified = data.getTextContent();
                    } else {
                        logger.warn("Unexpected tag:" + data.getNodeName());
                    }
                }
                if (name != null) {
                    FilesObject obj = new FilesObject(name, container, this);
                    if (eTag != null)
                        obj.setMd5sum(eTag);
                    if (mimeType != null)
                        obj.setMimeType(mimeType);
                    if (size >= 0)
                        obj.setSize(size);
                    if (lastModified != null)
                        obj.setLastModified(lastModified);
                    objectList.add(obj);
                }
            }
            return objectList;
        } else if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            logger.debug("Container " + container + " has no Objects");
            return new ArrayList<FilesObject>();
        } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new FilesNotFoundException("Container was not found", response.getResponseHeaders(),
                    response.getStatusLine());
        } else {
            throw new FilesException("Unexpected Server Result", response.getResponseHeaders(),
                    response.getStatusLine());
        }
    } catch (FilesNotFoundException fnfe) {
        throw fnfe;
    } catch (Exception ex) {
        logger.error("Error parsing xml", ex);
        throw new FilesException("Error parsing server resposne", ex);
    } finally {
        if (method != null)
            method.abort();
    }
}