Search in sources :

Example 11 with EngineException

use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.

the class HttpUtils method checkXSRF.

public static void checkXSRF(HttpServletRequest request, HttpServletResponse response) throws EngineException {
    HttpSession session = request.getSession(true);
    String token = SessionAttribute.xsrfToken.get(session);
    String header = HeaderName.XXsrfToken.getHeader(request);
    if (token == null && header != null) {
        token = Base64.encodeBytes(DigestUtils.sha256(session.getId() + Engine.startStopDate)).replaceAll("[^\\w\\d]", "-");
        SessionAttribute.xsrfToken.set(session, token);
        HeaderName.XXsrfToken.setHeader(response, token);
    } else {
        if (header == null) {
            header = request.getParameter(Parameter.XsrfToken.getName());
        }
        if (token != null && !token.equals(header)) {
            EngineException e = new EngineException("Invalid XSRF Token header for this session.");
            e.setStackTrace(new StackTraceElement[0]);
            throw e;
        }
    }
}
Also used : HttpSession(javax.servlet.http.HttpSession) EngineException(com.twinsoft.convertigo.engine.EngineException)

Example 12 with EngineException

use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.

the class CarUtils method makeArchive.

public static File makeArchive(File file, Project project, Set<ArchiveExportOption> archiveExportOptions) throws EngineException {
    Set<File> undeployedFiles = getUndeployedFiles(project.getName());
    String projectName = project.getName();
    String dirPath = project.getDirPath();
    File projectDir = new File(dirPath);
    File skipTestCase = null;
    try {
        if (!archiveExportOptions.contains(ArchiveExportOption.includeTestCase)) {
            skipTestCase = new File(projectDir, "_private/noTestCase/c8oProject.yaml");
            CarUtils.exportProject(project, skipTestCase.getAbsolutePath(), false);
        }
        for (ArchiveExportOption opt : ArchiveExportOption.values()) {
            if (!archiveExportOptions.contains(opt)) {
                for (File dir : opt.dirs(projectDir)) {
                    undeployedFiles.add(dir);
                }
            }
        }
        FileUtils.deleteQuietly(file);
        File f = ZipUtils.makeZip(file.getAbsolutePath(), dirPath, projectName, undeployedFiles);
        if (skipTestCase != null) {
            Map<String, String> zip_properties = new HashMap<>();
            zip_properties.put("create", "false");
            zip_properties.put("encoding", "UTF-8");
            URI zip_disk = URI.create("jar:" + f.toURI());
            try (FileSystem zipfs = FileSystems.newFileSystem(zip_disk, zip_properties)) {
                Path addNewFile = skipTestCase.getParentFile().toPath();
                Files.walk(addNewFile).forEach(p -> {
                    try {
                        String relat = addNewFile.relativize(p).toString();
                        if (!relat.isEmpty()) {
                            Files.copy(p, zipfs.getPath(projectName, relat));
                        }
                    } catch (IOException e) {
                        Engine.logEngine.debug("(CarUtils) failed to copy project without TestCase: " + e);
                    }
                });
            }
        }
        return f;
    } catch (Exception e) {
        throw new EngineException("Unable to make the archive file for the project \"" + projectName + "\".", e);
    } finally {
        if (skipTestCase != null) {
            FileUtils.deleteQuietly(skipTestCase.getParentFile());
        }
    }
}
Also used : Path(java.nio.file.Path) HashMap(java.util.HashMap) FileSystem(java.nio.file.FileSystem) EngineException(com.twinsoft.convertigo.engine.EngineException) ArchiveExportOption(com.twinsoft.convertigo.engine.enums.ArchiveExportOption) IOException(java.io.IOException) File(java.io.File) URI(java.net.URI) IOException(java.io.IOException) IntrospectionException(java.beans.IntrospectionException) EngineException(com.twinsoft.convertigo.engine.EngineException)

Example 13 with EngineException

use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.

the class CarUtils method exportXMLProject.

private static void exportXMLProject(String fileName, Document document) throws EngineException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        File file = new File(fileName);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        boolean isCR = FileUtils.isCRLF();
        Writer writer = isCR ? new StringWriter() : new FileWriterWithEncoding(fileName, "UTF-8");
        transformer.transform(new DOMSource(document), new StreamResult(writer));
        if (isCR) {
            String content = FileUtils.CrlfToLf(writer.toString());
            writer = new FileWriterWithEncoding(fileName, "UTF-8");
            writer.write(content);
        }
        writer.close();
    } catch (Exception e) {
        throw new EngineException("(CarUtils) exportProject failed", e);
    }
}
Also used : FileWriterWithEncoding(org.apache.commons.io.output.FileWriterWithEncoding) DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) EngineException(com.twinsoft.convertigo.engine.EngineException) File(java.io.File) StringWriter(java.io.StringWriter) Writer(java.io.Writer) IOException(java.io.IOException) IntrospectionException(java.beans.IntrospectionException) EngineException(com.twinsoft.convertigo.engine.EngineException)

Example 14 with EngineException

use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.

the class HttpConnector method executeMethod.

private byte[] executeMethod(HttpMethod method, final Context context) throws IOException, URIException, MalformedURLException, EngineException {
    Header[] requestHeaders, responseHeaders = null;
    byte[] result = null;
    String contents = null;
    int statuscode = -1;
    final String referer = this.referer;
    if (!context.requestedObject.runningThread.bContinue)
        return null;
    Engine.logBeans.debug("(HttpConnector) Executing method - " + method.getName() + "(" + method.getPath() + ")");
    try {
        AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject;
        requestHeaders = method.getRequestHeaders();
        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans.trace("(HttpConnector) Request headers :\n" + Arrays.asList(requestHeaders).toString());
        statuscode = doExecuteMethod(method, context);
        Engine.logBeans.debug("(HttpConnector) Status: " + statuscode + " " + method.getStatusLine());
        responseHeaders = method.getResponseHeaders();
        context.setResponseHeaders(responseHeaders);
        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans.trace("(HttpConnector) Response headers:\n" + Arrays.asList(responseHeaders).toString());
        if (statuscode != -1) {
            InputStream in = method.getResponseBodyAsStream();
            if (in != null)
                try {
                    /**
                     * Retrieve response charset if available in responseHeaders
                     */
                    charset = null;
                    // add GZip support #320
                    boolean checkGZip = false;
                    for (int i = 0; i < responseHeaders.length && (charset == null || !checkGZip); i++) {
                        Header head = responseHeaders[i];
                        if (HeaderName.ContentType.is(head)) {
                            context.contentType = head.getValue();
                            HeaderElement[] els = head.getElements();
                            for (int j = 0; j < els.length && charset == null; j++) {
                                NameValuePair nvp = els[j].getParameterByName("charset");
                                if (nvp != null)
                                    charset = nvp.getValue();
                            }
                        } else if (HeaderName.ContentEncoding.is(head)) {
                            checkGZip = true;
                            HeaderElement[] els = head.getElements();
                            for (int j = 0; j < els.length; j++) if ("gzip".equals(els[j].getName())) {
                                Engine.logBeans.debug("(HttpConnector) Decode GZip stream");
                                in = new GZIPInputStream(in);
                            }
                        }
                    }
                    if (context.contentType != null && context.contentType.startsWith("multipart/") && context.requestedObject instanceof AbstractHttpTransaction) {
                        Engine.logBeans.debug("(HttpConnector) Decoding multipart contentType");
                        try {
                            BigMimeMultipart mp = new BigMimeMultipart(new BufferedInputStream(in), context.contentType);
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                            mp.nextPart(bos);
                            result = bos.toByteArray();
                            if (transaction.getAllowDownloadAttachment()) {
                                Document doc = context.outputDocument;
                                Element attInfo = null;
                                File file = File.createTempFile("c8o_", ".part");
                                for (MimePart bp = mp.nextPart(file); bp != null; bp = mp.nextPart(file)) {
                                    try {
                                        file.deleteOnExit();
                                        if (attInfo == null) {
                                            Engine.logBeans.debug("(HttpConnector) Saving attachment(s)");
                                            attInfo = doc.createElement("AttachmentInfo");
                                            doc.getDocumentElement().appendChild(attInfo);
                                        }
                                        Element att = doc.createElement("attachment");
                                        attInfo.appendChild(att);
                                        String cid = bp.getContentID();
                                        if (cid != null) {
                                            cid = cid.replaceFirst("^<?(.*?)>?$", "$1");
                                            att.setAttribute("cid", "cid:" + cid);
                                        }
                                        Engine.logBeans.debug("(HttpConnector) Saving the attachment cid: " + cid + " in file: " + file.getAbsolutePath());
                                        att.setAttribute("filepath", file.getAbsolutePath());
                                        Enumeration<javax.mail.Header> headers = GenericUtils.cast(bp.getAllHeaders());
                                        while (headers.hasMoreElements()) {
                                            javax.mail.Header header = headers.nextElement();
                                            Element eHeader = doc.createElement("header");
                                            att.appendChild(eHeader);
                                            eHeader.setAttribute("name", header.getName());
                                            eHeader.setAttribute("value", header.getValue());
                                        }
                                    } catch (Exception e1) {
                                        Engine.logBeans.error("(HttpConnector) Failed to retrieve the attachment in " + file.getAbsolutePath(), e1);
                                    }
                                    file = File.createTempFile("c8o_", ".part");
                                }
                                file.delete();
                            }
                        } catch (Exception e) {
                            Engine.logBeans.error("(HttpConnector) Failed to retrieve attachments", e);
                        }
                    } else {
                        result = transaction.readResult(in, method);
                    }
                } finally {
                    in.close();
                }
            if (Engine.logBeans.isTraceEnabled()) {
                contents = new String((result != null) ? result : new byte[] {});
                Engine.logBeans.trace("(HttpConnector) Response content:\n" + contents);
            }
            String redirectUrl, newuri;
            // Handles REDIRECTION through Location header
            if (transaction.isFollowRedirect() && (statuscode == HttpStatus.SC_MOVED_TEMPORARILY || statuscode == HttpStatus.SC_MOVED_PERMANENTLY || statuscode == HttpStatus.SC_SEE_OTHER || statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                Header location = method.getResponseHeader("Location");
                if (location != null) {
                    newuri = location.getValue();
                    if ((newuri == null) || (newuri.equals(""))) {
                        newuri = "/";
                    }
                    // ignore any data after the ";" character
                    int split = newuri.indexOf(';');
                    if (split != -1) {
                        newuri = newuri.substring(0, split);
                    }
                    redirectUrl = getAbsoluteUrl(method, newuri);
                    Engine.logBeans.debug("(HttpConnector) Redirecting to : " + redirectUrl);
                    result = getData(context, redirectUrl);
                } else {
                    Engine.logBeans.debug("(HttpConnector) Invalid redirect!");
                }
            }
        }
        // Added by julienda - #3433 - 04/03/2013
        AbstractHttpTransaction abstractHttpTransaction = (AbstractHttpTransaction) context.transaction;
        if (abstractHttpTransaction.getHttpInfo()) {
            Document doc = context.outputDocument;
            // Parent Element
            httpInfoElement = doc.createElement(abstractHttpTransaction.getHttpInfoTagName());
            // Add requested URL
            Element urlElement = doc.createElement("url");
            urlElement.setTextContent(referer);
            httpInfoElement.appendChild(urlElement);
            // Add status code
            Element httpStatusElement = doc.createElement("status");
            httpStatusElement.setAttribute("code", Integer.toString(statuscode));
            httpStatusElement.setAttribute("text", method.getStatusText());
            httpInfoElement.appendChild(httpStatusElement);
            // We add headers informations
            List<Header> headers = Arrays.asList(requestHeaders);
            if (!headers.isEmpty()) {
                Element httpHeadersElement = doc.createElement("headers");
                for (int i = 0; i < headers.size(); i++) {
                    Element elt = doc.createElement("header");
                    elt.setAttribute("name", headers.get(i).getName());
                    elt.setAttribute("value", headers.get(i).getValue());
                    httpHeadersElement.appendChild(elt);
                }
                httpInfoElement.appendChild(httpHeadersElement);
            }
            // we add response header information
            if (responseHeaders.length != 0) {
                Element httpHeadersElement = doc.createElement("responseHeaders");
                for (int i = 0; i < responseHeaders.length; i++) {
                    Element elt = doc.createElement("header");
                    elt.setAttribute("name", responseHeaders[i].getName());
                    elt.setAttribute("value", responseHeaders[i].getValue());
                    httpHeadersElement.appendChild(elt);
                }
                httpInfoElement.appendChild(httpHeadersElement);
            }
            doc.getDocumentElement().appendChild(httpInfoElement);
        }
    } finally {
        method.releaseConnection();
    }
    return result;
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) Enumeration(java.util.Enumeration) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement) HeaderElement(org.apache.commons.httpclient.HeaderElement) Element(org.w3c.dom.Element) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) URIException(org.apache.commons.httpclient.URIException) SocketTimeoutException(java.net.SocketTimeoutException) OAuthException(oauth.signpost.exception.OAuthException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) MessagingException(javax.mail.MessagingException) FileNotFoundException(java.io.FileNotFoundException) EngineException(com.twinsoft.convertigo.engine.EngineException) MalformedURLException(java.net.MalformedURLException) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) GZIPInputStream(java.util.zip.GZIPInputStream) Header(org.apache.commons.httpclient.Header) BufferedInputStream(java.io.BufferedInputStream) MimePart(javax.mail.internet.MimePart) BigMimeMultipart(com.twinsoft.convertigo.engine.util.BigMimeMultipart) File(java.io.File)

Example 15 with EngineException

use of com.twinsoft.convertigo.engine.EngineException in project convertigo by convertigo.

the class HttpConnector method prepareForTransaction.

@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 {
        System.setProperty("javax.net.debug", "");
        Engine.logBeans.debug("(HttpConnector) Disabling SSL debug mode");
    }
    Engine.logBeans.debug("(HttpConnector) Initializing...");
    if (context.isRequestFromVic) {
        // 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) {
        // remove cookies from previous transaction
        httpState.clearCookies();
    }
    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.projectDir(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 (org.apache.commons.lang3.StringUtils.isNotBlank(httpUrl)) {
        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 + "\\}", Matcher.quoteReplacement(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();
        if (httpVariable.isBlank()) {
            httpVariable = variable;
        }
        httpObjectVariableValue = httpTransaction.getParameterValue(variable);
        bIgnoreVariable = urlPathVariableList.contains(variable) || httpObjectVariableValue == null || variable.startsWith(DynamicHttpVariable.__header_.name()) || httpVariable.isEmpty() || !method.equals("GET");
        if (!bIgnoreVariable) {
            Engine.logBeans.trace("(HttpConnector) Query variable: " + variable + " => (" + method + ") " + httpVariable);
            queryString = appendToQuery(queryString, isMultiValued, httpVariable, httpObjectVariableValue);
        }
    }
    // 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) {
        // 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();
                } else // XML document
                {
                    // 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) {
            if ("application/json".equals(contentType) && httpObjectVariableValue instanceof Element) {
                try {
                    postQuery = XMLUtils.XmlToJson(((Element) httpObjectVariableValue), true, true, JsonRoot.docChildNodes);
                } catch (JSONException e) {
                    Engine.logBeans.warn("Failed to transform the XML input to JSON string: [" + e.getClass().getCanonicalName() + "] " + e.getMessage());
                    postQuery = ParameterUtils.toString(httpObjectVariableValue);
                }
            } else {
                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());
        if (httpVariable.isBlank()) {
            httpVariable = variable;
        }
        if (variable.startsWith(DynamicHttpVariable.__header_.name())) {
            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
                        postQuery = appendToQuery(postQuery, isMultiValued, httpVariable, httpObjectVariableValue);
                    }
                } else // Content-Type is 'text/xml'
                {
                    // 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<?>) {
                                // 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();
                            }
                        } else // Handle single valued variable
                        {
                            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();
                        }
                    } else // Remove variable from postQuery
                    {
                        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");
}
Also used : RequestableHttpVariable(com.twinsoft.convertigo.beans.variables.RequestableHttpVariable) DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) HeaderElement(org.apache.commons.httpclient.HeaderElement) Element(org.w3c.dom.Element) EngineException(com.twinsoft.convertigo.engine.EngineException) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) StringWriter(java.io.StringWriter) StringEx(com.twinsoft.util.StringEx) TransformerFactory(javax.xml.transform.TransformerFactory) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) JSONException(org.codehaus.jettison.json.JSONException) RequestableVariable(com.twinsoft.convertigo.beans.variables.RequestableVariable) Text(org.w3c.dom.Text) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) URIException(org.apache.commons.httpclient.URIException) SocketTimeoutException(java.net.SocketTimeoutException) OAuthException(oauth.signpost.exception.OAuthException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) MessagingException(javax.mail.MessagingException) FileNotFoundException(java.io.FileNotFoundException) EngineException(com.twinsoft.convertigo.engine.EngineException) MalformedURLException(java.net.MalformedURLException) Collection(java.util.Collection) VicApi(com.twinsoft.convertigo.engine.plugins.VicApi) File(java.io.File)

Aggregations

EngineException (com.twinsoft.convertigo.engine.EngineException)426 IOException (java.io.IOException)155 File (java.io.File)117 Element (org.w3c.dom.Element)84 NodeList (org.w3c.dom.NodeList)64 DatabaseObject (com.twinsoft.convertigo.beans.core.DatabaseObject)62 Document (org.w3c.dom.Document)43 JSONObject (org.codehaus.jettison.json.JSONObject)41 Node (org.w3c.dom.Node)40 Project (com.twinsoft.convertigo.beans.core.Project)35 ArrayList (java.util.ArrayList)35 JSONException (org.codehaus.jettison.json.JSONException)33 Sequence (com.twinsoft.convertigo.beans.core.Sequence)31 RequestableVariable (com.twinsoft.convertigo.beans.variables.RequestableVariable)29 TreeObject (com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject)27 DatabaseObjectTreeObject (com.twinsoft.convertigo.eclipse.views.projectexplorer.model.DatabaseObjectTreeObject)25 Connector (com.twinsoft.convertigo.beans.core.Connector)24 HashMap (java.util.HashMap)23 Transaction (com.twinsoft.convertigo.beans.core.Transaction)21 ObjectWithSameNameException (com.twinsoft.convertigo.engine.ObjectWithSameNameException)20