Example usage for org.w3c.dom Element getTextContent

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

Introduction

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

Prototype

public String getTextContent() throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:org.brekka.stillingar.spring.config.ConfigurationServiceBeanDefinitionParser.java

/**
 * @param element/*from w  w  w.ja v  a 2 s.  co  m*/
 * @param builder
 */
protected void prepareJAXB(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    Element jaxbElement = selectSingleChildElement(element, "jaxb", false);

    // Path
    String contextPath = jaxbElement.getAttribute("context-path");
    builder.addConstructorArgValue(contextPath);

    // Schemas
    List<Element> schemaElementList = selectChildElements(jaxbElement, "schema");
    ManagedList<URL> schemaUrlList = new ManagedList<URL>(schemaElementList.size());
    for (Element schemaElement : schemaElementList) {
        String schemaPath = schemaElement.getTextContent();
        try {
            Resource resource = parserContext.getReaderContext().getResourceLoader().getResource(schemaPath);
            schemaUrlList.add(resource.getURL());
        } catch (IOException e) {
            throw new ConfigurationException(String.format("Failed to parse schema location '%s'", schemaPath),
                    e);
        }
    }
    builder.addConstructorArgValue(schemaUrlList);

    // Namespaces
    builder.addConstructorArgReference(this.namespacesId);

    // ConversionManager
    builder.addConstructorArgValue(prepareJAXBConversionManager());
}

From source file:com.cloud.test.regression.ApiCommand.java

public Element queryAsyncJobResult(String jobId) {
    Element returnBody = null;/*w ww.j a  v  a2  s. c o m*/
    int code = 400;
    String resultUrl = this.host + ":8096/?command=queryAsyncJobResult&jobid=" + jobId;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(resultUrl);
    while (true) {
        try {
            code = client.executeMethod(method);
            if (code == 200) {
                InputStream is = method.getResponseBodyAsStream();
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(is);
                doc.getDocumentElement().normalize();
                returnBody = doc.getDocumentElement();
                Element jobStatusTag = (Element) returnBody.getElementsByTagName("jobstatus").item(0);
                String jobStatus = jobStatusTag.getTextContent();
                if (jobStatus.equals("0")) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                } else {
                    break;
                }
                method.releaseConnection();
            } else {
                s_logger.error("Error during queryJobAsync. Error code is " + code);
                this.responseCode = code;
                return null;
            }
        } catch (Exception ex) {
            s_logger.error(ex);
        }
    }
    return returnBody;
}

From source file:com.microsoft.windowsazure.management.scheduler.CloudServiceManagementClientImpl.java

/**
* The Get Operation Status operation returns the status of thespecified
* operation. After calling an asynchronous operation, you can call Get
* Operation Status to determine whether the operation has succeeded,
* failed, or is still in progress.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for
* more information)//  w ww. ja v a 2 s .c  o  m
*
* @param requestId Required. The request ID for the request you wish to
* track. The request ID is returned in the x-ms-request-id response header
* for every request.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request.  If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request, and also includes error information regarding the
* failure.
*/
@Override
public CloudServiceOperationStatusResponse getOperationStatus(String requestId)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (requestId == null) {
        throw new NullPointerException("requestId");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("requestId", requestId);
        CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    if (this.getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/operations/";
    url = url + URLEncoder.encode(requestId, "UTF-8");
    String baseUrl = this.getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2013-03-01");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        CloudServiceOperationStatusResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new CloudServiceOperationStatusResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "Operation");
            if (operationElement != null) {
                Element idElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "ID");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    result.setId(idInstance);
                }

                Element statusElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Status");
                if (statusElement != null && statusElement.getTextContent() != null
                        && !statusElement.getTextContent().isEmpty()) {
                    CloudServiceOperationStatus statusInstance;
                    statusInstance = CloudServiceOperationStatus.valueOf(statusElement.getTextContent());
                    result.setStatus(statusInstance);
                }

                Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "HttpStatusCode");
                if (httpStatusCodeElement != null && httpStatusCodeElement.getTextContent() != null
                        && !httpStatusCodeElement.getTextContent().isEmpty()) {
                    Integer httpStatusCodeInstance;
                    httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent());
                    result.setHttpStatusCode(httpStatusCodeInstance);
                }

                Element errorElement = XmlUtility.getElementByTagNameNS(operationElement,
                        "http://schemas.microsoft.com/windowsazure", "Error");
                if (errorElement != null) {
                    CloudServiceOperationStatusResponse.ErrorDetails errorInstance = new CloudServiceOperationStatusResponse.ErrorDetails();
                    result.setError(errorInstance);

                    Element codeElement = XmlUtility.getElementByTagNameNS(errorElement,
                            "http://schemas.microsoft.com/windowsazure", "Code");
                    if (codeElement != null) {
                        String codeInstance;
                        codeInstance = codeElement.getTextContent();
                        errorInstance.setCode(codeInstance);
                    }

                    Element messageElement = XmlUtility.getElementByTagNameNS(errorElement,
                            "http://schemas.microsoft.com/windowsazure", "Message");
                    if (messageElement != null) {
                        String messageInstance;
                        messageInstance = messageElement.getTextContent();
                        errorInstance.setMessage(messageInstance);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.microsoft.windowsazure.management.sql.RestorableDroppedDatabaseOperationsImpl.java

/**
* Returns information about a dropped Azure SQL Database that can be
* restored.// ww w .  j a  v  a2 s  .  c om
*
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database was hosted.
* @param entityId Required. The entity ID of the restorable dropped Azure
* SQL Database to be obtained.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return Contains the response to the Get Restorable Dropped Database
* request.
*/
@Override
public RestorableDroppedDatabaseGetResponse get(String serverName, String entityId)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (entityId == null) {
        throw new NullPointerException("entityId");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serverName", serverName);
        tracingParameters.put("entityId", entityId);
        CloudTracing.enter(invocationId, this, "getAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/restorabledroppeddatabases/";
    url = url + URLEncoder.encode(entityId, "UTF-8");
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2012-03-01");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        RestorableDroppedDatabaseGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new RestorableDroppedDatabaseGetResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element serviceResourceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement != null) {
                RestorableDroppedDatabase serviceResourceInstance = new RestorableDroppedDatabase();
                result.setDatabase(serviceResourceInstance);

                Element entityIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "EntityId");
                if (entityIdElement != null) {
                    String entityIdInstance;
                    entityIdInstance = entityIdElement.getTextContent();
                    serviceResourceInstance.setEntityId(entityIdInstance);
                }

                Element serverNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "ServerName");
                if (serverNameElement != null) {
                    String serverNameInstance;
                    serverNameInstance = serverNameElement.getTextContent();
                    serviceResourceInstance.setServerName(serverNameInstance);
                }

                Element editionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "Edition");
                if (editionElement != null) {
                    String editionInstance;
                    editionInstance = editionElement.getTextContent();
                    serviceResourceInstance.setEdition(editionInstance);
                }

                Element maxSizeBytesElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeBytes");
                if (maxSizeBytesElement != null) {
                    long maxSizeBytesInstance;
                    maxSizeBytesInstance = DatatypeConverter.parseLong(maxSizeBytesElement.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInBytes(maxSizeBytesInstance);
                }

                Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "CreationDate");
                if (creationDateElement != null) {
                    Calendar creationDateInstance;
                    creationDateInstance = DatatypeConverter
                            .parseDateTime(creationDateElement.getTextContent());
                    serviceResourceInstance.setCreationDate(creationDateInstance);
                }

                Element deletionDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "DeletionDate");
                if (deletionDateElement != null) {
                    Calendar deletionDateInstance;
                    deletionDateInstance = DatatypeConverter
                            .parseDateTime(deletionDateElement.getTextContent());
                    serviceResourceInstance.setDeletionDate(deletionDateInstance);
                }

                Element recoveryPeriodStartDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement, "http://schemas.microsoft.com/windowsazure",
                        "RecoveryPeriodStartDate");
                if (recoveryPeriodStartDateElement != null
                        && recoveryPeriodStartDateElement.getTextContent() != null
                        && !recoveryPeriodStartDateElement.getTextContent().isEmpty()) {
                    Calendar recoveryPeriodStartDateInstance;
                    recoveryPeriodStartDateInstance = DatatypeConverter
                            .parseDateTime(recoveryPeriodStartDateElement.getTextContent());
                    serviceResourceInstance.setRecoveryPeriodStartDate(recoveryPeriodStartDateInstance);
                }

                Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement != null) {
                    String nameInstance;
                    nameInstance = nameElement.getTextContent();
                    serviceResourceInstance.setName(nameInstance);
                }

                Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "Type");
                if (typeElement != null) {
                    String typeInstance;
                    typeInstance = typeElement.getTextContent();
                    serviceResourceInstance.setType(typeInstance);
                }

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    serviceResourceInstance.setState(stateInstance);
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

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

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

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

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

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

            final String nsURL = node.getNamespaceURI();

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

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

                String crmFieldName = null;

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

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

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

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

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

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

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

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

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

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

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

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

/**
 * /*from   w  w w  .j av a2 s.  c om*/
 * @param account
 * @param accountId
 * @param cADbject
 * @return
 * @throws Exception
 */
public static final Task createCRMObjectTypeTask(final ScribeObject cADbject,
        final String crmFieldIntraSeparator) throws Exception {

    /* Create xml beans object */
    final Task task = Task.Factory.newInstance();

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

        /* Get main namespace URl */
        if (node != null) {
            final String nsURL = node.getNamespaceURI();

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

                if (logger.isDebugEnabled()) {
                    logger.debug("----Inside createCRMObject_Task: adding node : " + element.getNodeName()
                            + " with value : " + element.getTextContent());
                }

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

                String crmFieldName = null;

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

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

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

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

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

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

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

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

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

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

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

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    initialize(request);/* w  w w.  jav  a  2s . c  om*/

    int userId = 0;
    int groupId = 0;
    String user = "";
    String context = request.getContextPath();
    String url = request.getPathInfo();

    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    Credential credential = null;
    try {
        //On initialise le dataProvider
        Connection c = null;
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // =====================================================================================
    boolean trace = false;
    StringBuffer outTrace = new StringBuffer();
    StringBuffer outPrint = new StringBuffer();
    String logFName = null;

    response.setCharacterEncoding("UTF-8");

    System.out.println("FileServlet::doGet");
    try {
        // ====== URI : /resources/file[/{lang}]/{context-id}
        // ====== PathInfo: /resources/file[/{uuid}?lang={fr|en}&size={S|L}] pathInfo
        //         String uri = request.getRequestURI();
        String[] token = url.split("/");
        String uuid = token[1];
        //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile:"+request.getRemoteAddr()+":"+uri);

        /// FIXME: Passe la scurit si la source provient de localhost, il faudrait un change afin de s'assurer que n'importe quel servlet ne puisse y accder
        String sourceip = request.getRemoteAddr();
        System.out.println("IP: " + sourceip);

        /// Vrification des droits d'accs
        // TODO: Might be something special with proxy and export/PDF, to investigate
        if (!ourIPs.contains(sourceip)) {
            if (userId == 0)
                throw new RestWebApplicationException(Status.FORBIDDEN, "");

            if (!credential.hasNodeRight(userId, groupId, uuid, Credential.READ)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit READ sur le noeud "+nodeUuid);
            }
        } else // Si la requte est locale et qu'il n'y a pas de session, on ignore la vrification
        {
            System.out.println("IP OK: bypass");
        }

        /// On rcupre le noeud de la ressource pour retrouver le lien
        String data = dataProvider.getResNode(uuid, userId, groupId);

        //         javax.servlet.http.HttpSession session = request.getSession(true);
        //====================================================
        //String ppath = session.getServletContext().getRealPath("/");
        //logFName = ppath +"logs/logNode.txt";
        //====================================================
        String size = request.getParameter("size");
        if (size == null)
            size = "S";

        String lang = request.getParameter("lang");
        if (lang == null) {
            lang = "fr";
        }

        /*
        String nodeUuid = uri.substring(uri.lastIndexOf("/")+1);
        if  (uri.lastIndexOf("/")>uri.indexOf("file/")+6) { // -- file/ = 5 carac. --
           lang = uri.substring(uri.indexOf("file/")+5,uri.lastIndexOf("/"));
        }
        //*/

        String ref = request.getHeader("referer");

        /// Parse les donnes
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader("<node>" + data + "</node>"));
        Document doc = documentBuilder.parse(is);
        DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
        LSSerializer serial = impl.createLSSerializer();
        serial.getDomConfig().setParameter("xml-declaration", false);

        /// Trouve le bon noeud
        XPath xPath = XPathFactory.newInstance().newXPath();

        /// Either we have a fileid per language
        String filterRes = "//fileid[@lang='" + lang + "']";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);
        String resolve = "";
        if (nodelist.getLength() != 0) {
            Element fileNode = (Element) nodelist.item(0);
            resolve = fileNode.getTextContent();
        }

        /// Or just a single one shared
        if ("".equals(resolve)) {
            response.setStatus(404);
            return;
        }

        String filterName = "//filename[@lang='" + lang + "']";
        NodeList textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET);
        String filename = "";
        if (textList.getLength() != 0) {
            Element fileNode = (Element) textList.item(0);
            filename = fileNode.getTextContent();
        }

        String filterType = "//type[@lang='" + lang + "']";
        textList = (NodeList) xPath.compile(filterType).evaluate(doc, XPathConstants.NODESET);
        String type = "";
        if (textList.getLength() != 0) {
            Element fileNode = (Element) textList.item(0);
            type = fileNode.getTextContent();
        }

        /*
        String filterSize = "//size[@lang='"+lang+"']";
        textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET);
        String filesize = "";
        if( textList.getLength() != 0 )
        {
           Element fileNode = (Element) textList.item(0);
           filesize = fileNode.getTextContent();
        }
        //*/

        System.out.println("!!! RESOLVE: " + resolve);

        /// Envoie de la requte au servlet de fichiers
        // http://localhost:8080/MiniRestFileServer/user/claudecoulombe/file/a8e0f07f-671c-4f6a-be6c-9dba12c519cf/ptype/sql
        /// TODO: Ne plus avoir besoin du switch
        String urlTarget = "http://" + server + "/" + resolve;
        //         String urlTarget = "http://"+ server + "/user/" + resolve +"/"+ lang + "/ptype/fs";

        HttpURLConnection connection = CreateConnection(urlTarget, request);
        connection.connect();
        InputStream input = connection.getInputStream();
        String sizeComplete = connection.getHeaderField("Content-Length");
        int completeSize = Integer.parseInt(sizeComplete);

        response.setContentLength(completeSize);
        response.setContentType(type);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        ServletOutputStream output = response.getOutputStream();

        byte[] buffer = new byte[completeSize];
        int totalRead = 0;
        int bytesRead = -1;

        while ((bytesRead = input.read(buffer, 0, completeSize)) != -1 || totalRead < completeSize) {
            output.write(buffer, 0, bytesRead);
            totalRead += bytesRead;
        }

        //         IOUtils.copy(input, output);
        //         IOUtils.closeQuietly(output);

        output.flush();
        output.close();
        input.close();
        connection.disconnect();
    } catch (RestWebApplicationException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        logger.error(e.toString() + " -> " + e.getLocalizedMessage());
        e.printStackTrace();
        //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile: error"+e);
    } finally {
        try {
            dataProvider.disconnect();
        } catch (Exception e) {
            ServletOutputStream out = response.getOutputStream();
            out.println("Erreur dans doGet: " + e);
            out.close();
        }
    }
}

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

/**
 * /* ww w. j a  v a 2s .c  o m*/
 * @param account
 * @param accountId
 * @param cADbject
 * @return
 * @throws Exception
 */
public static final Account createCRMObjectTypeAccount(final ScribeObject cADbject,
        final String crmFieldIntraSeparator) throws Exception {

    /* Create xml beans object */
    final Account account = Account.Factory.newInstance();

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

        /* Get main namespace URl */
        if (node != null) {
            final String nsURL = node.getNamespaceURI();

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

                if (logger.isDebugEnabled()) {
                    logger.debug("----Inside createCRMObject_Account: adding node: " + element.getNodeName()
                            + " with value : " + element.getTextContent());
                }

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

                String crmFieldName = null;

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

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

                } else {
                    crmFieldName = crmField;
                }

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

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

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

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

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

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

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

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

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

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

/**
 * //  w ww.  j  a  v  a 2 s. c  om
 * @param account
 * @param accountId
 * @param cADbject
 * @return
 * @throws Exception
 */
public static final Contact createCRMObjectTypeContact(final ScribeObject cADbject,
        final String crmFieldIntraSeparator) throws Exception {

    /* Create xml beans object */
    final Contact contact = Contact.Factory.newInstance();

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

        /* Get main namespace URl */
        if (node != null) {
            final String nsURL = node.getNamespaceURI();

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

                if (logger.isDebugEnabled()) {
                    logger.debug("----Inside createCRMObject_Contact: adding node : " + element.getNodeName()
                            + " with value : " + element.getTextContent());
                }

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

                String crmFieldName = null;

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

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

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

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

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

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

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

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

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

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

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

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

/**
 * /*from ww  w. j a v  a 2s  .c  o  m*/
 * @param account
 * @param accountId
 * @param cADbject
 * @return
 * @throws Exception
 */
public static final Incident createCRMObjectTypeIncident(final ScribeObject cADbject,
        final String crmFieldIntraSeparator) throws Exception {

    /* Create xml beans object */
    /* In MS CRM 'Incident' is actually a 'Case' */
    final Incident caseObject = Incident.Factory.newInstance();

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

        /* Get main namespace URl */
        if (node != null) {
            final String nsURL = node.getNamespaceURI();

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

                if (logger.isDebugEnabled()) {
                    logger.debug("----Inside createCRMObject_Incident: adding node : " + element.getNodeName()
                            + " with value : " + element.getTextContent());
                }

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

                String crmFieldName = null;

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

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

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

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

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

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

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

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

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

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

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