Example usage for org.w3c.dom Document getXmlEncoding

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

Introduction

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

Prototype

public String getXmlEncoding();

Source Link

Document

An attribute specifying, as part of the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#NT-XMLDecl'>XML declaration</a>, the encoding of this document.

Usage

From source file:Main.java

License:asdf

public static void main(String args[]) throws Exception {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder(); // Create the parser
    Document xmlDoc = builder.parse(new InputSource(new StringReader(xmlString)));

    System.out.println(xmlDoc.getXmlEncoding());

}

From source file:eu.europa.esig.dss.DSSXMLUtils.java

public static byte[] transformDomToByteArray(final Document documentDom) {

    try {//  w w  w .j a  va  2s  . com

        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final String xmlEncoding = documentDom.getXmlEncoding();
        if (StringUtils.isNotBlank(xmlEncoding)) {
            transformer.setOutputProperty(OutputKeys.ENCODING, xmlEncoding);
        }
        final DOMSource source = new DOMSource(documentDom);

        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final StreamResult streamResult = new StreamResult(byteArrayOutputStream);
        transformer.transform(source, streamResult);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return byteArray;
    } catch (final TransformerException e) {
        throw new DSSException(e);
    }
}

From source file:com.photon.maven.plugins.android.standalonemojos.ManifestUpdateMojo.java

/**
 * Write manifest using JAXP transformer
 *///ww  w  . j a  v a 2  s.c om
private void writeManifest(File manifestFile, Document doc) throws IOException, TransformerException {
    TransformerFactory xfactory = TransformerFactory.newInstance();
    Transformer xformer = xfactory.newTransformer();
    xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    Source source = new DOMSource(doc);

    FileWriter writer = null;
    try {
        writer = new FileWriter(manifestFile, false);
        String xmldecl = String.format("<?xml version=\"%s\" encoding=\"%s\"?>%n", doc.getXmlVersion(),
                doc.getXmlEncoding());
        writer.write(xmldecl);
        Result result = new StreamResult(writer);

        xformer.transform(source, result);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:com.panet.imeta.job.entries.dtdvalidator.JobEntryDTDValidator.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);//from  w w  w .  j  av  a2s  . co m

    String realxmlfilename = getRealxmlfilename();
    String realDTDfilename = getRealDTDfilename();

    FileObject xmlfile = null;
    FileObject DTDfile = null;

    try

    {

        if (xmlfilename != null && ((dtdfilename != null && !dtdintern) || (dtdintern))) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);

            if (xmlfile.exists())

            {

                //URL xmlFile = new URL (KettleVFS.getFilename(xmlfile));
                URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURI().toURL();

                // open XML File
                BufferedReader xmlBufferedReader = new BufferedReader(
                        new InputStreamReader(xmlFile.openStream()));
                StringBuffer xmlStringbuffer = new StringBuffer("");

                char[] buffertXML = new char[1024];
                int LenXML = -1;
                while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1)
                    xmlStringbuffer.append(buffertXML, 0, LenXML);

                // Prepare parsing ...
                DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
                Document xmlDocDTD = null;
                DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();

                // Let's try to get XML document encoding
                DocBuilderFactory.setValidating(false);
                xmlDocDTD = DocBuilder
                        .parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8")));

                String encoding = null;
                if (xmlDocDTD.getXmlEncoding() == null) {
                    encoding = "UTF-8";
                } else {
                    encoding = xmlDocDTD.getXmlEncoding();
                }

                int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE");

                if (dtdintern) {
                    // DTD find in the XML document
                    if (xmlStartDTD != -1) {
                        if (log.isBasic())
                            log.logBasic(toString(), Messages
                                    .getString("JobEntryDTDValidator.ERRORDTDFound.Label", realxmlfilename));
                    } else {
                        if (log.isBasic())
                            log.logBasic(toString(), Messages
                                    .getString("JobEntryDTDValidator.ERRORDTDNotFound.Label", realxmlfilename));
                    }

                } else {
                    // DTD in external document
                    // If we find an intern declaration, we remove it
                    DTDfile = KettleVFS.getFileObject(realDTDfilename);

                    if (DTDfile.exists()) {
                        if (xmlStartDTD != -1) {
                            int EndDTD = xmlStringbuffer.indexOf(">", xmlStartDTD);
                            //String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1);
                            xmlStringbuffer.replace(xmlStartDTD, EndDTD + 1, "");

                        }

                        String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName();

                        String RefDTD = "<?xml version='" + xmlDocDTD.getXmlVersion() + "' encoding='"
                                + encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD + " SYSTEM '"
                                + KettleVFS.getFilename(DTDfile) + "'>\n";

                        int xmloffsetDTD = xmlStringbuffer.indexOf("<" + xmlRootnodeDTD);
                        xmlStringbuffer.replace(0, xmloffsetDTD, RefDTD);
                    } else {
                        log.logError(Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"),
                                Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Msg",
                                        realDTDfilename));
                    }
                }

                if ((dtdintern && xmlStartDTD == -1 || (!dtdintern && !DTDfile.exists()))) {
                    result.setResult(false);
                    result.setNrErrors(1);
                } else {
                    DocBuilderFactory.setValidating(true);

                    // Let's parse now ...

                    xmlDocDTD = DocBuilder
                            .parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding)));
                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Subject"),
                                Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Label",
                                        realxmlfilename));

                    // Everything is OK
                    result.setResult(true);
                }

            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(),
                            Messages.getString("JobEntryDTDValidator.FileDoesNotExist.Label", realxmlfilename));
                }

                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryDTDValidator.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    }

    catch (Exception e) {
        log.logError(Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Subject"),
                Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Label", realxmlfilename,
                        realDTDfilename, e.getMessage()));

        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (DTDfile != null)
                DTDfile.close();

        } catch (IOException e) {
        }
    }

    return result;
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WFSRequestHandler.java

public void writeResponse(DataWrapper data, User user) throws Exception {
    OGCResponse ogcresponse = getNewOGCResponse();
    OGCRequest ogcrequest = data.getOgcrequest();

    String version = ogcrequest.getFinalVersion();
    String spInUrl = ogcrequest.getServiceProviderName();

    Integer[] orgIds = user.getOrganizationIds();
    OutputStream os = data.getOutputStream();

    Object identity = null;/*from w ww. j  a  v  a 2  s .  com*/
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);

        boolean forAdmin = isConfigInUrlAndAdmin(data, user);
        // zet layers uit request in een list
        List<LayerSummary> layerSummaryList = prepareRequestLayers(ogcrequest);
        if (layerSummaryList == null) {
            // als geen layers meegegeven, dan alle layers gebruiken
            // alleen bij getcapabilities
            EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
            String[] al = getOrganisationLayers(em, orgIds, version, forAdmin);
            layerSummaryList = LayerSummary.createLayerSummaryList(Arrays.asList(al), spInUrl, true);
        }

        // maak lijst waarin de layers per sp zijn verzameld
        // boolean om volgorde van de lagen te bewaren
        List<SpLayerSummary> spLayerSummaries = null;
        if (forAdmin) {
            spLayerSummaries = getLayerSummaries(layerSummaryList, spInUrl);
        } else {
            spLayerSummaries = getServiceProviderURLS(layerSummaryList, orgIds, false, data, false);
        }
        if (spLayerSummaries == null || spLayerSummaries.isEmpty()) {
            throw new UnsupportedOperationException(
                    "No Serviceprovider available! User might not have rights to any Serviceprovider!");
        }
        if (spLayerSummaries.size() > 1 && version.equals(OGCConstants.WFS_VERSION_UNSPECIFIED)) {
            // forceren dat alle sp dezelfde versie retourneren, indien meer dan 1
            ogcrequest.addOrReplaceParameter(OGCConstants.VERSION, OGCConstants.WFS_VERSION_110);
        }

        DataMonitoring rr = data.getRequestReporting();
        long startprocestime = System.currentTimeMillis();
        String xmlEncoding = "UTF-8";

        for (SpLayerSummary sp : spLayerSummaries) {
            if (spInUrl != null && !spInUrl.equals(sp.getSpAbbr())) {
                // sp in url en dit is een andere sp
                continue;
            }
            sp.setSpInUrl(spInUrl);

            // zet de juiste layers voor deze sp
            OGCRequest sprequest = (OGCRequest) ogcrequest.clone();
            prepareRequest4Sp(sprequest, sp);

            String lurl = sp.getSpUrl();
            if (lurl.length() == 0) {
                throw new UnsupportedOperationException("No Serviceprovider for this service available!");
            }
            ServiceProviderRequest wfsRequest = this.createServiceProviderRequest(data, lurl,
                    sp.getServiceproviderId(), 0l);

            B3PCredentials credentials = new B3PCredentials();
            credentials.setUserName(sp.getUsername());
            credentials.setPassword(sp.getPassword());
            credentials.setUrl(lurl);
            HttpClientConfigured hcc = new HttpClientConfigured(credentials);

            HttpUriRequest method = null;
            if (sprequest.getHttpMethod().equalsIgnoreCase("POST")) {
                method = createPostMethod(sprequest, sp, wfsRequest);
            } else { // get
                method = createGetMethod(sprequest, sp, wfsRequest);
            }

            try {
                HttpResponse response = hcc.execute(method);

                try {

                    int statusCode = response.getStatusLine().getStatusCode();
                    wfsRequest.setResponseStatus(statusCode);
                    HttpEntity entity = response.getEntity();

                    if (statusCode != 200) {
                        log.error("Failed to connect with " + method.getURI() + " Using body: "
                                + sprequest.getXMLBody());
                        throw new UnsupportedOperationException("Failed to connect with " + method.getURI()
                                + " Using body: " + sprequest.getXMLBody());
                    }

                    wfsRequest.setRequestResponseTime(System.currentTimeMillis() - startprocestime);

                    data.setContentType("text/xml");
                    InputStream is = entity.getContent();

                    InputStream isx = null;
                    byte[] bytes = null;
                    int rsl = 0;
                    try {
                        rsl = new Integer(KBConfiguration.RESPONSE_SIZE_LIMIT);
                    } catch (NumberFormatException nfe) {
                        log.debug("KBConfiguration.RESPONSE_SIZE_LIMIT not properly configured: "
                                + nfe.getLocalizedMessage());
                    }
                    if (KBConfiguration.SAVE_MESSAGES) {
                        int len = 1;
                        byte[] buffer = new byte[2024];
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        while ((len = is.read(buffer, 0, buffer.length)) > 0) {
                            bos.write(buffer, 0, len);
                            if (buffer.length > rsl && rsl > 0) {
                                throw new ProviderException(
                                        "Response size exceeds maximum set in configuration:" + buffer.length
                                                + ", max is: " + rsl);
                            }
                        }
                        bytes = bos.toByteArray();
                        isx = new ByteArrayInputStream(bytes);
                    } else {
                        isx = new CountingInputStream(is);
                    }

                    if (KBConfiguration.SAVE_MESSAGES || spInUrl == null || !mayDirectWrite()) {
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        dbf.setNamespaceAware(true);
                        DocumentBuilder builder = dbf.newDocumentBuilder();
                        Document doc = builder.parse(isx);
                        // indien meerdere sp met verschillende encodings
                        // dan wint de laatste!
                        String docEncoding = doc.getXmlEncoding();
                        if (docEncoding != null) {
                            xmlEncoding = docEncoding;
                        }

                        int len = 0;
                        if (KBConfiguration.SAVE_MESSAGES) {
                            wfsRequest.setMessageReceived(new String(bytes));
                        } else {
                            len = new Integer(((CountingInputStream) isx).getCount());
                            wfsRequest.setBytesReceived(new Long(len));
                        }
                        if (len > rsl && rsl > 0) {
                            throw new ProviderException("Response size exceeds maximum set in configuration:"
                                    + len + ", max is: " + rsl);
                        }

                        String prefix = sp.getSpAbbr();
                        if (spInUrl != null && !spInUrl.isEmpty()) {
                            // sp in url dus geen prefix toevoegen
                            prefix = null;
                        }

                        if (OGCResponse.isWfsV100ErrorResponse(doc.getDocumentElement())) {
                            // wfs 1.0.0 error
                            ogcresponse.rebuildWfsV100ErrorResponse(doc, sprequest, prefix);
                        } else if (OGCResponse.isOwsV100ErrorResponse(doc.getDocumentElement())) {
                            // wfs 1.1.0 error
                            ogcresponse.rebuildOwsV100ErrorResponse(doc, sprequest, prefix);
                        } else {
                            // normale response
                            ogcresponse.rebuildResponse(doc, sprequest, prefix);
                        }
                    } else {
                        /**
                         * Deze methode kan alleen aangeroepen worden als
                         * aan de volgende voorwaarden is voldaan:
                         * <li> slechts n sp nodig voor aanroep
                         * <li> spabbr zit in de url en niet als prefix in
                         * de layer name
                         * <li> KBConfiguration.SAVE_MESSAGES is false Als
                         * aan voorwaarden is voldaan dat wordt direct
                         * doorgestreamd indien er geen fout is opgetreden.
                         * <li> de aanroep methode mayDirectWrite is true.
                         */
                        // direct write possible
                        byte[] h = prepareDirectWrite(isx);
                        if (h != null) {
                            os.write(h);
                        }
                        // write rest
                        IOUtils.copy(isx, os);
                        wfsRequest.setBytesReceived(new Long(((CountingInputStream) isx).getCount()));
                        ogcresponse.setAlreadyDirectWritten(true);
                        break;
                    }
                } finally {
                    hcc.close(response);
                    hcc.close();
                }

            } catch (Exception e) {
                wfsRequest.setExceptionMessage("Failed to send bytes to client: " + e.getMessage());
                wfsRequest.setExceptionClass(e.getClass());

                throw e;
            } finally {
                rr.addServiceProviderRequest(wfsRequest);
            }
        }

        // only write when not already direct written
        if (!ogcresponse.isAlreadyDirectWritten()) {
            String responseBody = ogcresponse.getResponseBody(spLayerSummaries, ogcrequest, xmlEncoding);
            if (responseBody != null && !responseBody.equals("")) {
                byte[] buffer = responseBody.getBytes(xmlEncoding);
                os.write(buffer);
            } else {
                throw new UnsupportedOperationException("XMLbody empty!");
            }
        }
        doAccounting(user.getMainOrganizationId(), data, user);

    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }
}

From source file:com.xpn.xwiki.pdf.impl.PdfExportImpl.java

/**
 * Cleans up an HTML document, turning it into valid XHTML.
 * /* ww  w . j a v a2  s .c  o m*/
 * @param input the source HTML to process
 * @return the cleaned up source
 */
private String convertToStrictXHtml(String input) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Cleaning HTML: " + input);
    }

    try {
        // First step, Tidy the document
        StringWriter tidyOutput = new StringWriter(input.length());
        this.tidy.parse(new StringReader(input), tidyOutput);

        // Tidy can't solve duplicate IDs, so it needs to be done manually
        DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(Utils.getComponent(EntityResolver.class));
        String tidied = tidyOutput.toString().trim();
        if (StringUtils.isEmpty(tidied)) {
            tidied = input.trim();
        }
        Document doc = docBuilder.parse(new InputSource(new StringReader(tidied)));
        List<String> seenIDs = new ArrayList<String>();
        this.cleanIDs(doc.getDocumentElement(), seenIDs);

        // Write back the fixed document to a String
        LSOutput output = lsImpl.createLSOutput();
        StringWriter result = new StringWriter();
        output.setCharacterStream(result);
        LSSerializer serializer = lsImpl.createLSSerializer();
        serializer.setNewLine("\n");
        output.setEncoding(doc.getXmlEncoding());
        serializer.write(doc, output);
        return result.toString();
    } catch (Exception ex) {
        LOGGER.warn("Failed to tidy document for export: " + ex.getMessage(), ex);
        return input;
    }
}

From source file:com.servoy.extension.install.LibActivationHandler.java

protected void replaceReferencesInJNLP(File jnlp, File libFileToBeRemoved,
        FullLibDependencyDeclaration toActivate) {
    try {/*from w w w .  ja v a 2  s  .co  m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new XMLErrorHandler(jnlp.getName()));

        Document doc = db.parse(jnlp);
        Element root = doc.getDocumentElement();
        root.normalize();

        NodeList list;
        if ("jnlp".equals(root.getNodeName())) //$NON-NLS-1$
        {
            list = root.getElementsByTagName("resources"); //$NON-NLS-1$
            if (list != null && list.getLength() == 1 && list.item(0).getNodeType() == Node.ELEMENT_NODE) {
                File appServerDir = new File(installDir, APP_SERVER_DIR);
                Element resourcesNode = (Element) list.item(0);
                boolean replaced1 = findAndReplaceReferences(resourcesNode, "jar", appServerDir, //$NON-NLS-1$
                        libFileToBeRemoved, toActivate);
                boolean replaced2 = findAndReplaceReferences(resourcesNode, "nativelib", appServerDir, //$NON-NLS-1$
                        libFileToBeRemoved, toActivate);

                if (replaced1 || replaced2) {
                    // save back the jnlp file
                    try {
                        writeBackXML(doc, jnlp, doc.getXmlEncoding());
                    } catch (Exception e) {
                        messages.addError("Cannot write back jnlp file (when deactivating lib): " + jnlp); //$NON-NLS-1$ 
                        Debug.error(e);
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (SAXException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (IOException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (FactoryConfigurationError e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'. Please report this problem to Servoy."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.error(msg, e);
    }
}

From source file:com.jayway.maven.plugins.android.phase01generatesources.GenerateSourcesMojo.java

/**
 * Copy the AndroidManifest.xml from androidManifestFile to destinationManifestFile
 *
 * @throws MojoExecutionException//  w  ww  .  j a v a  2  s  .c o  m
 */
protected void copyManifest() throws MojoExecutionException {
    getLog().debug("copyManifest: " + androidManifestFile + " -> " + destinationManifestFile);
    if (androidManifestFile == null) {
        getLog().debug("Manifest copying disabled. Using default manifest only");
        return;
    }

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(androidManifestFile);
        Source source = new DOMSource(doc);

        TransformerFactory xfactory = TransformerFactory.newInstance();
        Transformer xformer = xfactory.newTransformer();
        xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        FileWriter writer = null;
        try {
            destinationManifestFile.getParentFile().mkdirs();

            writer = new FileWriter(destinationManifestFile, false);
            if (doc.getXmlEncoding() != null && doc.getXmlVersion() != null) {
                String xmldecl = String.format("<?xml version=\"%s\" encoding=\"%s\"?>%n", doc.getXmlVersion(),
                        doc.getXmlEncoding());

                writer.write(xmldecl);
            }
            Result result = new StreamResult(writer);
            xformer.transform(source, result);
            getLog().info("Manifest copied from " + androidManifestFile + " to " + destinationManifestFile);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    } catch (Exception e) {
        getLog().error("Error during copyManifest");
        throw new MojoExecutionException("Error during copyManifest", e);
    }
}

From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java

@Override
public void prepareForTransaction(Context context) throws EngineException {
    Engine.logBeans.debug("(HttpConnector) Preparing for transaction");

    if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) {
        System.setProperty("javax.net.debug", "all");
        Engine.logBeans.trace("(HttpConnector) Enabling SSL debug mode");
    } else {//from  w w w  .j a  v  a2s .  co m
        System.setProperty("javax.net.debug", "");
        Engine.logBeans.debug("(HttpConnector) Disabling SSL debug mode");
    }

    Engine.logBeans.debug("(HttpConnector) Initializing...");

    if (context.isRequestFromVic) {
        // Check the VIC authorizations only if this is a non trusted
        // request, i.e. from a request not triggered from VIC (for
        // instance, from a web service call).
        if (!context.isTrustedRequest) {
            try {
                VicApi vicApi = new VicApi();
                if (!vicApi.isServiceAuthorized(context.tasUserName, context.tasVirtualServerName,
                        context.tasServiceCode)) {
                    throw new EngineException("The service '" + context.tasServiceCode
                            + "' is not authorized for the user '" + context.tasUserName + "'");
                }
            } catch (IOException e) {
                throw new EngineException("Unable to retrieve authorization from the VIC database.", e);
            }
        }
    }

    AbstractHttpTransaction httpTransaction = null;
    try {
        httpTransaction = (AbstractHttpTransaction) context.requestedObject;
    } catch (ClassCastException e) {
        throw new EngineException("Requested object is not a transaction", e);
    }

    handleCookie = httpTransaction.isHandleCookie();
    if (!handleCookie && httpState != null) {
        httpState.clearCookies(); // remove cookies from previous transaction
    }

    httpParameters = httpTransaction.getCurrentHttpParameters();

    contentType = MimeType.WwwForm.value();

    for (List<String> httpParameter : httpParameters) {
        String headerName = httpParameter.get(0);
        String value = httpParameter.get(1);

        // Content-Type
        if (HeaderName.ContentType.is(headerName)) {
            contentType = value;
        }

        // oAuth Parameters are passed as standard Headers
        if (HeaderName.OAuthKey.is(headerName)) {
            oAuthKey = value;
        }
        if (HeaderName.OAuthSecret.is(headerName)) {
            oAuthSecret = value;
        }
        if (HeaderName.OAuthToken.is(headerName)) {
            oAuthToken = value;
        }
        if (HeaderName.OAuthTokenSecret.is(headerName)) {
            oAuthTokenSecret = value;
        }
    }

    {
        String overrideContentType = ParameterUtils
                .toString(httpTransaction.getParameterValue(Parameter.HttpContentType.getName()));
        if (overrideContentType != null) {
            contentType = overrideContentType;
        }
    }

    int len = httpTransaction.numberOfVariables();
    boolean isFormUrlEncoded = MimeType.WwwForm.is(contentType);

    doMultipartFormData = false;
    for (int i = 0; i < len; i++) {
        RequestableHttpVariable trVariable = (RequestableHttpVariable) httpTransaction.getVariable(i);
        if (trVariable.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) {
            doMultipartFormData = true;
            isFormUrlEncoded = true;
        }
    }

    // Retrieve request template file if necessary
    File requestTemplateFile = null;
    if (!isFormUrlEncoded) {
        String requestTemplateUrl = httpTransaction.getRequestTemplate();
        if (!requestTemplateUrl.equals("")) {
            String projectDirectoryName = context.project.getName();
            String absoluteRequestTemplateUrl = Engine.PROJECTS_PATH + "/" + projectDirectoryName + "/"
                    + (context.subPath.length() > 0 ? context.subPath + "/" : "") + requestTemplateUrl;
            Engine.logBeans.debug("(HttpConnector) Request template Url: " + absoluteRequestTemplateUrl);
            requestTemplateFile = new File(absoluteRequestTemplateUrl);
            if (!requestTemplateFile.exists()) {
                Engine.logBeans.debug(
                        "(HttpConnector) The local request template file (\"" + absoluteRequestTemplateUrl
                                + "\") does not exist. Trying search in Convertigo TEMPLATES directory...");
                absoluteRequestTemplateUrl = Engine.TEMPLATES_PATH + "/" + requestTemplateUrl;
                Engine.logBeans.debug("(HttpConnector) Request template Url: " + absoluteRequestTemplateUrl);
                requestTemplateFile = new File(absoluteRequestTemplateUrl);
                if (!requestTemplateFile.exists()) {
                    Engine.logBeans.debug("(HttpConnector) The common request template file (\""
                            + absoluteRequestTemplateUrl + "\") does not exist. Trying absolute search...");
                    absoluteRequestTemplateUrl = requestTemplateUrl;
                    Engine.logBeans
                            .debug("(HttpConnector) Request template Url: " + absoluteRequestTemplateUrl);
                    requestTemplateFile = new File(absoluteRequestTemplateUrl);
                    if (!requestTemplateFile.exists()) {
                        throw new EngineException(
                                "Could not find any request template file \"" + requestTemplateUrl
                                        + "\" for transaction \"" + httpTransaction.getName() + "\".");
                    }
                }
            }
        }
    }

    // Sets or overwrites server url
    String httpUrl = httpTransaction.getParameterStringValue(Parameter.ConnectorConnectionString.getName());
    if (httpUrl != null)
        setBaseUrl(httpUrl);
    else
        setBaseUrl();

    String transactionBaseDir = httpTransaction.getCurrentSubDir();
    if (transactionBaseDir.startsWith("http")) {
        sUrl = transactionBaseDir;
        /*
         * if (transactionBaseDir.startsWith("https")) setHttps(true);
         */
    } else
        sUrl += transactionBaseDir;

    // Setup the SSL properties if needed
    if (https) {
        Engine.logBeans.debug("(HttpConnector) Setting up SSL properties");
        certificateManager.collectStoreInformation(context);
    }

    String variable, method, httpVariable, queryString = "";
    Object httpObjectVariableValue;
    boolean isMultiValued = false;
    boolean bIgnoreVariable = false;

    String urlEncodingCharset = httpTransaction.getComputedUrlEncodingCharset();

    // Replace variables in URL
    List<String> urlPathVariableList = AbstractHttpTransaction.getPathVariableList(sUrl);
    if (!urlPathVariableList.isEmpty()) {
        Engine.logBeans.debug("(HttpConnector) Defined URL: " + sUrl);
        for (String varName : urlPathVariableList) {
            RequestableHttpVariable rVariable = (RequestableHttpVariable) httpTransaction.getVariable(varName);
            httpObjectVariableValue = rVariable == null ? "" : httpTransaction.getParameterValue(varName);
            httpVariable = rVariable == null ? "null" : varName;
            method = rVariable == null ? "NULL" : rVariable.getHttpMethod();

            Engine.logBeans.trace(
                    "(HttpConnector) Path variable: " + varName + " => (" + method + ") " + httpVariable);

            sUrl = sUrl.replaceAll("\\{" + varName + "\\}", ParameterUtils.toString(httpObjectVariableValue));
        }
    }

    // Build query string
    for (int i = 0; i < len; i++) {
        RequestableHttpVariable rVariable = (RequestableHttpVariable) httpTransaction.getVariable(i);
        variable = rVariable.getName();
        isMultiValued = rVariable.isMultiValued();
        method = rVariable.getHttpMethod();
        httpVariable = rVariable.getHttpName();
        httpObjectVariableValue = httpTransaction.getParameterValue(variable);

        bIgnoreVariable = urlPathVariableList.contains(variable) || httpObjectVariableValue == null
                || httpVariable.isEmpty() || !method.equals("GET");

        if (!bIgnoreVariable) {
            Engine.logBeans.trace(
                    "(HttpConnector) Query variable: " + variable + " => (" + method + ") " + httpVariable);

            try {
                // handle multivalued variable
                if (isMultiValued) {
                    if (httpObjectVariableValue instanceof Collection<?>) {
                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                            queryString += ((queryString.length() != 0) ? "&" : "");
                            queryString += httpVariable + "=" + URLEncoder
                                    .encode(ParameterUtils.toString(httpVariableValue), urlEncodingCharset);
                        }
                    }
                }
                // standard case
                else {
                    queryString += ((queryString.length() != 0) ? "&" : "");
                    queryString += httpVariable + "=" + URLEncoder
                            .encode(ParameterUtils.toString(httpObjectVariableValue), urlEncodingCharset);
                }
            } catch (UnsupportedEncodingException e) {
                throw new EngineException(urlEncodingCharset + " encoding is not supported.", e);
            }
        }
    }

    // Encodes URL if it contains special characters
    sUrl = URLUtils.encodeAbsoluteURL(sUrl, urlEncodingCharset);

    if (queryString.length() != 0) {
        if (sUrl.indexOf('?') == -1) {
            sUrl += "?" + queryString;
        } else {
            sUrl += "&" + queryString;
        }
    }

    Engine.logBeans.debug("(HttpConnector) URL: " + sUrl);

    if (Engine.logBeans.isDebugEnabled()) {
        Engine.logBeans.debug("(HttpConnector) GET query: "
                + Visibility.Logs.replaceVariables(httpTransaction.getVariablesList(), queryString));
    }

    if (doMultipartFormData) {
        Engine.logBeans.debug("(HttpConnector) Skip postQuery computing and do a multipart/formData content");
        return;
    }

    // Build body for POST/PUT
    postQuery = "";

    // Load request template in postQuery if necessary
    if (!isFormUrlEncoded) {

        // Ticket #1040
        // A request template may be an XML document; in this case, the
        // "standard"
        // process apply: tokens are replaced by their respective value.
        // But a request template may also be an XSL document. In this case,
        // an XML
        // document giving all transaction variables should be built and
        // applied to
        // the XSL in order to produce a real XML request template.
        if (requestTemplateFile != null) {
            try {
                FileInputStream fis = new FileInputStream(requestTemplateFile);
                Document requestTemplate = XMLUtils.parseDOM(fis);

                Element documentElement = requestTemplate.getDocumentElement();
                // XSL document
                if (documentElement.getNodeName().equalsIgnoreCase("xsl:stylesheet")) {
                    // Build the variables XML document
                    Document variablesDocument = XMLUtils.createDom("java");
                    Element variablesElement = variablesDocument.createElement("variables");
                    variablesDocument.appendChild(variablesElement);

                    for (RequestableVariable requestableVariable : httpTransaction.getVariablesList()) {
                        RequestableHttpVariable trVariable = (RequestableHttpVariable) requestableVariable;
                        variable = trVariable.getName();
                        isMultiValued = trVariable.isMultiValued();
                        httpVariable = trVariable.getHttpName();

                        Element variableElement = variablesDocument.createElement("variable");
                        variablesElement.appendChild(variableElement);
                        variableElement.setAttribute("name", variable);

                        httpObjectVariableValue = httpTransaction.getParameterValue(variable);
                        if (httpObjectVariableValue != null) {
                            if (isMultiValued) {
                                variableElement.setAttribute("multi", "true");
                                if (httpObjectVariableValue instanceof Collection<?>) {
                                    for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                        Element valueElement = variablesDocument.createElement("value");
                                        variableElement.appendChild(valueElement);
                                        Text valueText = variablesDocument
                                                .createTextNode(getStringValue(trVariable, httpVariableValue));
                                        valueElement.appendChild(valueText);
                                    }
                                }
                            } else {
                                Element valueElement = variablesDocument.createElement("value");
                                variableElement.appendChild(valueElement);
                                Text valueText = variablesDocument
                                        .createTextNode(getStringValue(trVariable, httpObjectVariableValue));
                                valueElement.appendChild(valueText);
                            }
                        }
                    }

                    if (Engine.logBeans.isDebugEnabled()) {
                        String sVariablesDocument = XMLUtils.prettyPrintDOM((Document) Visibility.Logs
                                .replaceVariables(httpTransaction.getVariablesList(), variablesDocument));
                        Engine.logBeans.debug("Build variables XML document:\n" + sVariablesDocument);
                    }

                    // Apply XSL
                    TransformerFactory tFactory = TransformerFactory.newInstance();
                    StreamSource streamSource = new StreamSource(new FileInputStream(requestTemplateFile));
                    Transformer transformer = tFactory.newTransformer(streamSource);
                    StringWriter sw = new StringWriter();
                    transformer.transform(new DOMSource(variablesElement), new StreamResult(sw));

                    postQuery = sw.getBuffer().toString();
                }
                // XML document
                else {
                    // Template has been parsed from file, retrieve its declared encoding char set
                    // If not found use "UTF-8" according to HTTP POST for text/xml (see getData)
                    String xmlEncoding = requestTemplate.getXmlEncoding();
                    xmlEncoding = (xmlEncoding == null) ? "UTF-8" : xmlEncoding;

                    postQuery = XMLUtils.prettyPrintDOMWithEncoding(requestTemplate, xmlEncoding);
                }
            } catch (Exception e) {
                Engine.logBeans.warn("Unable to parse the request template file as a valid XML/XSL document");
                throw new EngineException(
                        "An unexpected error occured while retrieving the request template file for transaction \""
                                + httpTransaction.getName() + "\".",
                        e);
            }
        }
    }

    RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction
            .getVariable(Parameter.HttpBody.getName());
    if (body != null) {
        method = body.getHttpMethod();
        httpObjectVariableValue = httpTransaction.getParameterValue(Parameter.HttpBody.getName());
        if (method.equals("POST") && httpObjectVariableValue != null) {
            postQuery = ParameterUtils.toString(httpObjectVariableValue);
            isFormUrlEncoded = false;
        }
    }

    // Add all input variables marked as POST
    boolean isLogHidden = false;
    List<String> logHiddenValues = new ArrayList<String>();

    for (int i = 0; i < len; i++) {
        bIgnoreVariable = false;
        RequestableHttpVariable trVariable = (RequestableHttpVariable) httpTransaction.getVariable(i);
        variable = trVariable.getName();
        isMultiValued = trVariable.isMultiValued();
        method = trVariable.getHttpMethod();
        httpVariable = trVariable.getHttpName();
        isLogHidden = Visibility.Logs.isMasked(trVariable.getVisibility());

        // do not add variable to query if empty name
        if (httpVariable.equals(""))
            bIgnoreVariable = true;

        // Retrieves variable value
        httpObjectVariableValue = httpTransaction.getParameterValue(variable);

        if (method.equals("POST")) {
            // variable must be sent as an HTTP parameter
            if (!bIgnoreVariable) {
                Engine.logBeans.trace("(HttpConnector) Parameter variable: " + variable + " => (" + method
                        + ") " + httpVariable);
                // Content-Type is 'application/x-www-form-urlencoded'
                if (isFormUrlEncoded) {
                    // Replace variable value in postQuery
                    if (httpObjectVariableValue != null) {
                        // handle multivalued variable
                        if (isMultiValued) {
                            if (httpObjectVariableValue instanceof Collection<?>)
                                for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                    postQuery += ((postQuery.length() != 0) ? "&" : "");
                                    postQuery += httpVariable + "="
                                            + ParameterUtils.toString(httpVariableValue);
                                }
                            else if (httpObjectVariableValue.getClass().isArray())
                                for (Object httpVariableValue : (Object[]) httpObjectVariableValue) {
                                    postQuery += ((postQuery.length() != 0) ? "&" : "");
                                    postQuery += httpVariable + "="
                                            + ParameterUtils.toString(httpVariableValue);
                                }
                        }
                        // standard case
                        else {
                            postQuery += ((postQuery.length() != 0) ? "&" : "");
                            postQuery += httpVariable + "=" + ParameterUtils.toString(httpObjectVariableValue);
                        }
                    }
                }
                // Content-Type is 'text/xml'
                else {
                    // Replace variable value in postQuery
                    if (httpObjectVariableValue != null) {
                        // Handle multivalued variable
                        if (isMultiValued) {
                            String varPattern = "$(" + httpVariable + ")";
                            int varPatternIndex, indexAfterPattern, beginTagIndex, endTagIndex;
                            if (httpObjectVariableValue instanceof Collection<?>) {
                                // while postQuery contains the variable
                                // pattern
                                while (postQuery.indexOf(varPattern) != -1) {
                                    varPatternIndex = postQuery.indexOf(varPattern);
                                    indexAfterPattern = varPatternIndex + varPattern.length();
                                    if (postQuery.substring(indexAfterPattern).startsWith("concat")) {
                                        // concat every value from the
                                        // vector
                                        // to replace the occurrence in the
                                        // template
                                        // by the concatenation of the
                                        // multiple values
                                        String httpVariableValue = "";
                                        for (Object var : (Collection<?>) httpObjectVariableValue)
                                            httpVariableValue += getStringValue(trVariable, var);
                                        if (isLogHidden)
                                            logHiddenValues.add(httpVariableValue);
                                        postQuery = postQuery.substring(0, varPatternIndex) + httpVariableValue
                                                + postQuery.substring(indexAfterPattern + "concat".length());
                                    } else {
                                        // duplicate the tag surrounding the
                                        // occurrence in the template
                                        // for each value from the vector
                                        beginTagIndex = postQuery.substring(0, varPatternIndex)
                                                .lastIndexOf('<');
                                        endTagIndex = indexAfterPattern
                                                + postQuery.substring(indexAfterPattern).indexOf('>');
                                        String tmpPostQuery = postQuery.substring(0, beginTagIndex);
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            String stringValue = getStringValue(trVariable, httpVariableValue);
                                            if (isLogHidden) {
                                                logHiddenValues.add(stringValue);
                                            }
                                            tmpPostQuery += (postQuery.substring(beginTagIndex, varPatternIndex)
                                                    + stringValue
                                                    + postQuery.substring(indexAfterPattern, endTagIndex + 1));
                                        }
                                        tmpPostQuery += postQuery.substring(endTagIndex + 1);
                                        postQuery = tmpPostQuery;
                                    }
                                }
                            } else {
                                String stringValue = getStringValue(trVariable, httpObjectVariableValue);
                                if (isLogHidden) {
                                    logHiddenValues.add(stringValue);
                                }
                                StringEx sx = new StringEx(postQuery);
                                sx.replaceAll("$(" + httpVariable + ")concat", stringValue);
                                postQuery = sx.toString();
                            }
                        }
                        // Handle single valued variable
                        else {
                            String stringValue = getStringValue(trVariable, httpObjectVariableValue);

                            if (isLogHidden) {
                                logHiddenValues.add(stringValue);
                            }
                            StringEx sx = new StringEx(postQuery);
                            sx.replaceAll("$(" + httpVariable + ")noE", stringValue);
                            sx.replaceAll("$(" + httpVariable + ")", stringValue);
                            postQuery = sx.toString();
                        }
                    }
                    // Remove variable from postQuery
                    else {
                        String varPattern = "$(" + httpVariable + ")";
                        int varPatternIndex, beginTagIndex, endTagIndex;
                        // while postQuery contains the variable pattern
                        while (postQuery.indexOf(varPattern) != -1) {
                            varPatternIndex = postQuery.indexOf(varPattern);
                            beginTagIndex = postQuery.substring(0, varPatternIndex).lastIndexOf('<');
                            endTagIndex = postQuery.indexOf('>', varPatternIndex);
                            postQuery = postQuery.substring(0, beginTagIndex)
                                    + postQuery.substring(endTagIndex + 1);
                        }
                    }
                }
            }
        } else if (method.equals("")) {
            // Replace variable value in postQuery
            if (httpObjectVariableValue != null) {
                if (!isFormUrlEncoded && (!(httpVariable.equals("")))) {// used
                    // to
                    // replace
                    // empty
                    // element
                    String stringValue = getStringValue(trVariable, httpObjectVariableValue);
                    if (isLogHidden) {
                        logHiddenValues.add(stringValue);
                    }
                    StringEx sx = new StringEx(postQuery);
                    sx.replaceAll(httpVariable, stringValue);
                    postQuery = sx.toString();
                }
            }
        }
    }

    if (Engine.logBeans.isDebugEnabled()) {
        Engine.logBeans.debug("(HttpConnector) POST query: " + (isFormUrlEncoded ? "" : "\n")
                + (isFormUrlEncoded
                        ? Visibility.Logs.replaceVariables(httpTransaction.getVariablesList(), postQuery)
                        : Visibility.Logs.replaceValues(logHiddenValues, postQuery)));
    }
    Engine.logBeans.debug("(HttpConnector) Connector successfully prepared for transaction");
}

From source file:org.apache.hise.utils.DOMUtils.java

/**
 * Convert a DOM node to a stringified XML representation.
 *//*from   ww w. ja v  a2 s  . c om*/
static public String domToString(Node node) {
    if (node == null) {
        throw new IllegalArgumentException("Cannot stringify null Node!");
    }

    String value = null;
    short nodeType = node.getNodeType();
    if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE) {
        // serializer doesn't handle Node type well, only Element
        DOMSerializerImpl ser = new DOMSerializerImpl();
        ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
        ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE);
        ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);

        // create a proper XML encoding header based on the input document;
        // default to UTF-8 if the parent document's encoding is not accessible
        String usedEncoding = "UTF-8";
        Document parent = node.getOwnerDocument();
        if (parent != null) {
            String parentEncoding = parent.getXmlEncoding();
            if (parentEncoding != null) {
                usedEncoding = parentEncoding;
            }
        }

        // the receiver of the DOM
        DOMOutputImpl out = new DOMOutputImpl();
        out.setEncoding(usedEncoding);

        // we write into a String
        StringWriter writer = new StringWriter(4096);
        out.setCharacterStream(writer);

        // out, ye characters!
        ser.write(node, out);
        writer.flush();

        // finally get the String
        value = writer.toString();
    } else {
        value = node.getNodeValue();
    }
    return value;
}