Example usage for org.w3c.dom Element getAttributes

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

Introduction

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

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

From source file:com.nridge.core.base.io.xml.DataFieldXML.java

public DataField load(Element anElement) throws IOException {
    Attr nodeAttr;/*from  w w  w . j a  va2 s  . c o m*/
    Node nodeItem;
    DataField dataField;
    Element nodeElement;
    Field.Type fieldType;
    String nodeName, nodeValue;

    String attrValue = anElement.getAttribute("name");
    if (StringUtils.isNotEmpty(attrValue)) {
        String fieldName = attrValue;
        attrValue = anElement.getAttribute("type");
        if (StringUtils.isNotEmpty(attrValue))
            fieldType = Field.stringToType(attrValue);
        else
            fieldType = Field.Type.Text;
        dataField = new DataField(fieldType, fieldName);

        NamedNodeMap namedNodeMap = anElement.getAttributes();
        int attrCount = namedNodeMap.getLength();
        for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
            nodeAttr = (Attr) namedNodeMap.item(attrOffset);
            nodeName = nodeAttr.getNodeName();
            nodeValue = nodeAttr.getNodeValue();

            if (StringUtils.isNotEmpty(nodeValue)) {
                if ((StringUtils.equalsIgnoreCase(nodeName, "name"))
                        || (StringUtils.equalsIgnoreCase(nodeName, "type"))
                        || (StringUtils.equalsIgnoreCase(nodeName, "rangeType")))
                    continue;
                else if (StringUtils.equalsIgnoreCase(nodeName, "title"))
                    dataField.setTitle(nodeValue);
                else if (StringUtils.equalsIgnoreCase(nodeName, "isMultiValue"))
                    dataField.setMultiValueFlag(StrUtl.stringToBoolean(nodeValue));
                else if (StringUtils.equalsIgnoreCase(nodeName, "displaySize"))
                    dataField.setDisplaySize(Field.createInt(nodeValue));
                else if (StringUtils.equalsIgnoreCase(nodeName, "sortOrder"))
                    dataField.setSortOrder(Field.Order.valueOf(nodeValue));
                else if (StringUtils.equalsIgnoreCase(nodeName, "defaultValue"))
                    dataField.setDefaultValue(nodeValue);
                else
                    dataField.addFeature(nodeName, nodeValue);
            }
        }
        String rangeType = anElement.getAttribute("rangeType");
        if (StringUtils.isNotEmpty(rangeType)) {
            NodeList nodeList = anElement.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                nodeItem = nodeList.item(i);

                if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
                    continue;

                nodeName = nodeItem.getNodeName();
                if (StringUtils.equalsIgnoreCase(nodeName, "Range")) {
                    nodeElement = (Element) nodeItem;
                    dataField.setRange(mRangeXML.load(nodeElement));
                } else if (StringUtils.equalsIgnoreCase(nodeName, "Value")) {
                    nodeValue = XMLUtl.getNodeStrValue(nodeItem);
                    String mvDelimiter = dataField.getFeature(Field.FEATURE_MV_DELIMITER);
                    if (StringUtils.isNotEmpty(mvDelimiter))
                        dataField.expand(nodeValue, mvDelimiter.charAt(0));
                    else
                        dataField.expand(nodeValue);
                }
            }
        } else {
            nodeItem = (Node) anElement;
            if (dataField.isFeatureTrue(Field.FEATURE_IS_CONTENT))
                nodeValue = XMLUtl.getNodeCDATAValue(nodeItem);
            else
                nodeValue = XMLUtl.getNodeStrValue(nodeItem);
            if (dataField.isMultiValue()) {
                String mvDelimiter = dataField.getFeature(Field.FEATURE_MV_DELIMITER);
                if (StringUtils.isNotEmpty(mvDelimiter))
                    dataField.expand(nodeValue, mvDelimiter.charAt(0));
                else
                    dataField.expand(nodeValue);
            } else
                dataField.setValue(nodeValue);
        }
    } else
        dataField = null;

    return dataField;
}

From source file:com.amalto.core.history.accessor.UnaryFieldAccessor.java

@Override
public void markModified(Marker marker) {
    Document domDocument = document.asDOM();
    Element element = getElement();
    if (element != null) {
        Attr newAttribute = domDocument.createAttribute(MODIFIED_MARKER_ATTRIBUTE);
        switch (marker) {
        case ADD:
            newAttribute.setValue(FieldUpdateAction.MODIFY_ADD_MARKER_VALUE);
            break;
        case UPDATE:
            newAttribute.setValue(FieldUpdateAction.MODIFY_UPDATE_MARKER_VALUE);
            break;
        case REMOVE:
            newAttribute.setValue(FieldUpdateAction.MODIFY_REMOVE_MARKER_VALUE);
            break;
        default:// w  w w .  j av  a  2s  .  c om
            throw new IllegalArgumentException("No support for marker " + marker); //$NON-NLS-1$
        }
        element.getAttributes().setNamedItem(newAttribute);
    }
}

From source file:fr.gouv.finances.dgfip.xemelios.utils.TextWriter.java

private void element(Writer writer, Element elem) throws IOException {
    if (prettyPrint) {
        checkTextBuffer(writer);/* ww w  .  j av  a  2 s . c o  m*/
        indent(writer);
    }

    String n = elem.getTagName();
    writer.write('<');
    writeText(writer, n);

    NamedNodeMap a = elem.getAttributes();
    int size = a.getLength();
    for (int i = 0; i < size; i++) {
        Attr att = (Attr) a.item(i);
        writer.write(' ');
        writeNode(writer, att);
    }

    if (elem.hasChildNodes()) {
        writer.write('>');

        if (prettyPrint) {
            String text = getChildText(elem);
            if (text != null)
                writeEscapedText(writer, normalizeString(text), false);
            else {
                writer.write('\n');
                indentLevel++;
                writeChildren(writer, elem);
                checkTextBuffer(writer);
                indentLevel--;
                indent(writer);
            }
        } else
            writeChildren(writer, elem);

        writer.write("</");
        writeText(writer, n);
        writer.write('>');
    } else {
        if (produceHTML)
            writer.write(">");
        else
            writer.write("/>");
    }

    if (prettyPrint)
        writer.write('\n');
}

From source file:com.microsoft.exchange.impl.ExchangeResponseUtilsImpl.java

private String parseInnerResponse(ResponseMessageType responseMessage) {
    StringBuilder responseBuilder = new StringBuilder("Response[");

    ResponseCodeType responseCode = responseMessage.getResponseCode();
    if (null != responseCode) {
        responseBuilder.append("code=" + responseCode + ", ");
    }//from w ww .j a  va 2s.  co m
    ResponseClassType responseClass = responseMessage.getResponseClass();
    if (null != responseClass) {
        responseBuilder.append("class=" + responseClass + ", ");
    }
    String messageText = responseMessage.getMessageText();
    if (StringUtils.isNotBlank(messageText)) {
        responseBuilder.append("txt=" + messageText + ", ");
    }
    MessageXml messageXml = responseMessage.getMessageXml();
    if (null != messageXml) {
        StringBuilder xmlStringBuilder = new StringBuilder("messageXml=");
        List<Element> anies = messageXml.getAnies();
        if (!CollectionUtils.isEmpty(anies)) {
            for (Element element : anies) {
                String elementNameString = element.getNodeName();
                String elementValueString = element.getNodeValue();
                xmlStringBuilder.append(elementNameString + "=" + elementValueString + ";");

                if (null != element.getAttributes()) {
                    NamedNodeMap attributes = element.getAttributes();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        Node item = attributes.item(i);
                        String nodeName = item.getNodeName();
                        String nodeValue = item.getNodeValue();
                        xmlStringBuilder.append(nodeName + "=" + nodeValue + ",");
                    }
                }
            }
        }
        responseBuilder.append("xml=" + xmlStringBuilder.toString() + ", ");
    }
    Integer descriptiveLinkKey = responseMessage.getDescriptiveLinkKey();
    if (null != descriptiveLinkKey) {
        responseBuilder.append("link=" + descriptiveLinkKey);
    }

    responseBuilder.append("]");
    return responseBuilder.toString();
}

From source file:com.nridge.core.base.io.xml.DSCriteriaXML.java

/**
 * Parses an XML DOM element and loads it into a criteria.
 *
 * @param anElement DOM element.//www  . j a  v a  2s.  com
 *
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Node nodeItem;
    Attr nodeAttr;
    Element nodeElement;
    DataField dataField;
    String nodeName, nodeValue, logicalOperator;

    String className = mDSCriteria.getClass().getName();
    String attrValue = anElement.getAttribute("type");
    if ((StringUtils.isNotEmpty(attrValue)) && (!IO.isTypesEqual(attrValue, className)))
        throw new IOException("Unsupported type: " + attrValue);

    attrValue = anElement.getAttribute("name");
    if (StringUtils.isNotEmpty(attrValue))
        mDSCriteria.setName(attrValue);

    NamedNodeMap namedNodeMap = anElement.getAttributes();
    int attrCount = namedNodeMap.getLength();
    for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
        nodeAttr = (Attr) namedNodeMap.item(attrOffset);
        nodeName = nodeAttr.getNodeName();
        nodeValue = nodeAttr.getNodeValue();

        if (StringUtils.isNotEmpty(nodeValue)) {
            if ((StringUtils.equalsIgnoreCase(nodeName, "name"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "type")))
                continue;
            else
                mDSCriteria.addFeature(nodeName, nodeValue);
        }
    }

    NodeList nodeList = anElement.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        nodeItem = nodeList.item(i);

        if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
            continue;

        nodeName = nodeItem.getNodeName();
        if (nodeName.equalsIgnoreCase(IO.XML_FIELD_NODE_NAME)) {
            nodeElement = (Element) nodeItem;
            dataField = mDataFieldXML.load(nodeElement);
            if (dataField != null) {
                logicalOperator = dataField.getFeature("operator");
                if (StringUtils.isEmpty(logicalOperator))
                    logicalOperator = Field.operatorToString(Field.Operator.EQUAL);
                mDSCriteria.add(dataField, Field.stringToOperator(logicalOperator));
            }
        }
    }
}

From source file:org.pegadi.server.article.ArticleServerImpl.java

/**
 * Change the main tag name of an article. Used when the article type changes.
 *
 * @param art The article.//from   w  ww.  j  a  va  2 s. c o  m
 * @param ID  The ID of the new article type.
 */
protected void changeArticleType(Article art, int ID) {
    Map<String, Object> map = template.queryForMap("SELECT tagname FROM ArticleType WHERE ID=:id",
            Collections.singletonMap("id", ID));
    String tag = (String) map.get("tagname");

    Document doc = art.getDocument();
    if (doc == null) {
        art.parseText();
        doc = art.getDocument();
    }

    if (doc == null) {
        log.error("changeArticleType: Can't get document for article, article is NOT changed.");
        return;
    }

    Element root = doc.getDocumentElement();
    log.info("Root before: " + doc.getDocumentElement().toString());

    Element replace = doc.createElement(tag);

    NamedNodeMap att = root.getAttributes();

    for (int i = 0; i < att.getLength(); i++) {
        Node n = att.item(i);
        if (n instanceof Attr) {
            replace.setAttribute(((Attr) n).getName(), ((Attr) n).getValue());
        }
    }

    NodeList nl = root.getChildNodes();
    log.info("changeArticleType: Root node has {} children.", nl.getLength());
    for (int i = 0; i < nl.getLength(); i++) {
        Node clone = nl.item(i).cloneNode(true);
        log.info("Adding node {} to replace", (i + 1));
        replace.appendChild(clone);
    }

    log.info("Replacement node: {}", replace.toString());

    doc.replaceChild(replace, root);

    log.info("Root after: {}", doc.getDocumentElement().toString());

    if (!art.serialize()) {
        log.error("changeArticleType: Can't serialize the changed XML.");
    }
}

From source file:com.bstek.dorado.config.xml.DispatchableXmlParser.java

/**
 * ??<br>//  w  ww . j  a  v  a  2s. c  o m
 * XML(Attribute)???
 * <code><Property name="xxx">XXXX</Property></code>
 * ??
 * 
 * @param element
 *            XML
 * @param context
 *            ?
 * @return ?Map???
 *         ??????
 * @throws Exception
 */
protected Map<String, Object> parseProperties(Element element, ParseContext context) throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();

    for (Element propertyElement : DomUtils.getChildrenByTagName(element, XmlConstants.PROPERTY)) {
        String name = propertyElement.getAttribute(XmlConstants.ATTRIBUTE_NAME);
        if (StringUtils.isNotEmpty(name)) {
            properties.put(name, propertyElement);
        }
    }

    NamedNodeMap attributes = element.getAttributes();
    int attributeNum = attributes.getLength();
    for (int i = 0; i < attributeNum; i++) {
        Node node = attributes.item(i);
        String property = node.getNodeName();
        properties.put(property, node);
    }

    for (Iterator<Map.Entry<String, Object>> it = properties.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, Object> entry = it.next();
        String property = entry.getKey();
        Node node = (Node) entry.getValue();
        Object value = parseProperty(property, node, context);
        if (value != ConfigUtils.IGNORE_VALUE) {
            entry.setValue(value);
        } else {
            it.remove();
        }
    }
    return properties;
}

From source file:com.nridge.core.base.io.xml.DocumentOpXML.java

private void loadOperation(Element anElement) throws IOException {
    Attr nodeAttr;/*from  ww  w  .ja  v  a  2 s  .c o m*/
    Node nodeItem;
    Document document;
    Element nodeElement;
    DocumentXML documentXML;
    DSCriteriaXML criteriaXML;
    String nodeName, nodeValue;

    mCriteria = null;
    mDocumentList.clear();
    mField.clearFeatures();

    String attrValue = anElement.getAttribute(Doc.FEATURE_OP_NAME);
    if (StringUtils.isNotEmpty(attrValue)) {
        mField.setName(attrValue);
        NamedNodeMap namedNodeMap = anElement.getAttributes();
        int attrCount = namedNodeMap.getLength();
        for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
            nodeAttr = (Attr) namedNodeMap.item(attrOffset);
            nodeName = nodeAttr.getNodeName();
            nodeValue = nodeAttr.getNodeValue();

            if (StringUtils.isNotEmpty(nodeValue)) {
                if ((!StringUtils.equalsIgnoreCase(nodeName, Doc.FEATURE_OP_NAME))
                        && (!StringUtils.equalsIgnoreCase(nodeName, Doc.FEATURE_OP_COUNT)))
                    mField.addFeature(nodeName, nodeValue);
            }
        }
    }

    NodeList nodeList = anElement.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        nodeItem = nodeList.item(i);

        if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
            continue;

        nodeName = nodeItem.getNodeName();
        if (nodeName.equalsIgnoreCase(IO.XML_CRITERIA_NODE_NAME)) {
            nodeElement = (Element) nodeItem;
            criteriaXML = new DSCriteriaXML();
            criteriaXML.load(nodeElement);
            mCriteria = criteriaXML.getCriteria();
        } else if (StringUtils.startsWithIgnoreCase(nodeName, IO.XML_DOCUMENT_NODE_NAME)) {
            nodeElement = (Element) nodeItem;
            documentXML = new DocumentXML();
            documentXML.load(nodeElement);
            document = documentXML.getDocument();
            if (document != null)
                mDocumentList.add(document);
        }
    }
}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

/**
 * Retrieve a configuration parameter value.
 *
 * Retrieves the value of the config parameter from the config section 
  * that is supplied.//w  w w  .  j  a v  a 2  s .  c om
 * @param eSection The base section.
 * @param sName The parameter name.
 * @return The paramater value.
 * @throws ConfigurationException If retrieving fails.
 */
public synchronized String getParam(Element eSection, String sName) throws ConfigurationException {
    if (eSection == null)
        throw new IllegalArgumentException("Suplied section is empty");
    if (sName == null)
        throw new IllegalArgumentException("Suplied name is empty");

    String sValue = null;
    try {
        //check attributes within the section tag
        if (eSection.hasAttributes()) {
            NamedNodeMap oNodeMap = eSection.getAttributes();
            Node nAttribute = oNodeMap.getNamedItem(sName);
            if (nAttribute != null)
                sValue = nAttribute.getNodeValue();
        }

        if (sValue == null) {//check sub sections
            NodeList nlChilds = eSection.getChildNodes();
            for (int i = 0; i < nlChilds.getLength(); i++) {
                Node nTemp = nlChilds.item(i);
                if (nTemp != null && nTemp.getNodeName().equalsIgnoreCase(sName)) {
                    NodeList nlSubNodes = nTemp.getChildNodes();
                    if (nlSubNodes.getLength() > 0) {
                        for (int iSub = 0; iSub < nlSubNodes.getLength(); iSub++) {
                            Node nSubTemp = nlSubNodes.item(iSub);
                            if (nSubTemp.getNodeType() == Node.TEXT_NODE) {
                                sValue = nSubTemp.getNodeValue();
                                if (sValue == null)
                                    sValue = "";

                                return sValue;
                            }
                        }
                    } else {
                        if (sValue == null)
                            sValue = "";

                        return sValue;
                    }
                }
            }
        }
    } catch (DOMException e) {
        _logger.error("Could not retrieve parameter: " + sValue, e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_READ);
    }
    return sValue;
}

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

/**
 * Execute a file upload.//from  w  ww  .  j a  v  a2  s . c o m
 * 
 * @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;
}