Search in sources :

Example 6 with StringEx

use of com.twinsoft.util.StringEx in project convertigo by convertigo.

the class DatabaseCacheManager method storeResponse.

protected CacheEntry storeResponse(Document response, String requestString, long expiryDate) throws EngineException {
    try {
        storeWeakResponse(response, requestString);
        Engine.logCacheManager.debug("Trying to store the response in the cache Database");
        sqlRequester.checkConnection();
        StringEx sqlRequest = new StringEx(sqlRequester.getProperty(DatabaseCacheManager.PROPERTIES_SQL_REQUEST_STORE_RESPONSE));
        String cacheTableName = sqlRequester.getProperty(DatabaseCacheManager.PROPERTIES_SQL_CACHE_TABLE_NAME, "CacheTable");
        sqlRequest.replace("CacheTable", cacheTableName);
        String jdbcURL = sqlRequester.getProperty(SqlRequester.PROPERTIES_JDBC_URL);
        boolean isSqlServerDatabase = jdbcURL.indexOf(":sqlserver:") != -1;
        boolean isOracleServerDatabase = jdbcURL.indexOf(":oracle:") != -1;
        if (!isSqlServerDatabase) {
            sqlRequest.replace("[Transaction]", "Transaction");
        }
        String xml = XMLUtils.prettyPrintDOM(response);
        sqlRequest.replace("{Xml}", escapeString(xml));
        sqlRequest.replace("{RequestString}", escapeString(requestString));
        sqlRequest.replace("{ExpiryDate}", Long.toString(expiryDate));
        Element documentElement = response.getDocumentElement();
        String project = documentElement.getAttribute("project");
        sqlRequest.replace("{Project}", project);
        String transaction = documentElement.getAttribute("transaction");
        sqlRequest.replace("{Transaction}", transaction);
        String sSqlRequest = sqlRequest.toString();
        Engine.logCacheManager.debug("SQL: " + sSqlRequest);
        // INSERT INTO CacheTable (Xml, ExpiryDate, RequestString, Project, [Transaction]) VALUES (XMLTYPE(?), {ExpiryDate}, '{RequestString}', '{Project}', '{Transaction}')
        if (isOracleServerDatabase && sSqlRequest.toUpperCase().indexOf("XMLTYPE(?)") != -1) {
            PreparedStatement statement = null;
            java.sql.Clob clb = null;
            try {
                xml = escapeString(xml);
                clb = sqlRequester.connection.createClob();
                clb.setString(1, xml);
                statement = sqlRequester.connection.prepareStatement(sSqlRequest);
                statement.setClob(1, clb);
                int nResult = statement.executeUpdate();
                Engine.logCacheManager.debug(nResult + " row(s) inserted (Xml length=" + xml.length() + ").");
            } finally {
                if (clb != null) {
                    clb.free();
                }
                if (statement != null) {
                    statement.close();
                }
            }
        } else // Other cases
        // INSERT INTO CacheTable (Xml, ExpiryDate, RequestString, Project, [Transaction]) VALUES ('{Xml}', {ExpiryDate}, '{RequestString}', '{Project}', '{Transaction}')
        {
            Statement statement = null;
            try {
                statement = sqlRequester.connection.createStatement();
                int nResult = statement.executeUpdate(sSqlRequest);
                Engine.logCacheManager.debug(nResult + " row(s) inserted.");
            } finally {
                if (statement != null) {
                    statement.close();
                }
            }
        }
        DatabaseCacheEntry cacheEntry = new DatabaseCacheEntry();
        cacheEntry.requestString = requestString;
        cacheEntry.id = getId(requestString);
        cacheEntry.expiryDate = expiryDate;
        Engine.logCacheManager.debug("The response has been stored: [" + cacheEntry + "]");
        storeWeakEntry(cacheEntry);
        return cacheEntry;
    } catch (Exception e) {
        throw new EngineException("Unable to store the response! (requestString: " + requestString + ")", e);
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Element(org.w3c.dom.Element) EngineException(com.twinsoft.convertigo.engine.EngineException) PreparedStatement(java.sql.PreparedStatement) StringEx(com.twinsoft.util.StringEx) IOException(java.io.IOException) SQLException(java.sql.SQLException) EngineException(com.twinsoft.convertigo.engine.EngineException)

Example 7 with StringEx

use of com.twinsoft.util.StringEx in project convertigo by convertigo.

the class Biller method insertCariocaBilling.

public void insertCariocaBilling(Context context, Object data) throws EngineException {
    String sSqlRequest = null;
    try {
        Engine.logBillers.debug("[Biller] Trying to insert the billing into a Carioca database ");
        sqlRequester.checkConnection();
        int cache = 0;
        double cost = getCost(context, data);
        if (cost == -1) {
            Engine.logBillers.debug("[Biller] Billing aborted because the returned cost is -1, i.e. do not need to bill.");
            return;
        } else if (cost == -2) {
            Engine.logBillers.debug("[Biller] Billing zero cost because the response was in cache.");
            cost = 0;
            cache = 1;
        }
        Connector connector = context.getConnector();
        CertificateManager certificateManager = null;
        if (connector instanceof HttpConnector) {
            certificateManager = ((HttpConnector) connector).certificateManager;
        } else if (connector instanceof SiteClipperConnector) {
            certificateManager = ((SiteClipperConnector) connector).certificateManager;
        }
        if (!certificateManager.storeInformationCollected) {
            certificateManager.collectStoreInformation(context);
        }
        String certificate = new File(certificateManager.keyStore).getName();
        int idx = certificate.indexOf('.');
        if (idx != -1) {
            certificate = certificate.substring(0, idx);
        }
        Statement statement = null;
        long startBilling = System.currentTimeMillis();
        try {
            Engine.logBillers.debug("[Biller] Replacements from the context done");
            StringEx sqlRequest = new StringEx(sqlRequester.getProperty(Biller.PROPERTIES_SQL_REQUEST_INSERT_BILLING));
            try {
                Engine.logBillers.debug("[Biller] Replacing TAS IDs");
                sqlRequest.replace("{IDSVR}", context.get("IDSVR").toString());
                sqlRequest.replace("{IDSERV}", context.get("IDSERV").toString());
                sqlRequest.replace("{IDUSER}", context.get("IDUSER").toString());
                sqlRequest.replace("{IDPROF}", context.get("IDPROF").toString());
                sqlRequest.replace("{IDEMUL}", context.get("IDEMUL").toString());
                Engine.logBillers.debug("[Biller] Replacing TAS variables");
                sqlRequest.replaceSQL("{NomSv}", context.tasVirtualServerName, '\'');
                sqlRequest.replaceSQL("{UserName}", context.tasUserName, '\'');
                sqlRequest.replaceSQL("{UserGroup}", context.tasUserGroup, '\'');
                sqlRequest.replaceSQL("{Service}", getService(context, data), '\'');
                Engine.logBillers.debug("[Biller] Replacing POBI variables");
                sqlRequest.replace("{cdbanque}", context.get("cdbanque").toString());
                sqlRequest.replace("{cdguichet}", context.get("cdguichet").toString());
                sqlRequest.replaceSQL("{certificat}", certificate, '\'');
                sqlRequest.replace("{cache}", Integer.toString(cache));
                sqlRequest.replaceSQL("{module}", getModule(context, data), '\'');
                sqlRequest.replaceSQL("{userdata}", context.get("userdata").toString(), '\'');
                sqlRequest.replaceSQL("{BDFKey}", getDataKey(context, data), '\'');
                sqlRequest.replaceSQL("{UserGroupAuto}", context.get("UserGroupAuto").toString(), '\'');
            } catch (NullPointerException e) {
                throw new EngineException("One parameter for SQL replacement is missing.", e);
            }
            Calendar rightNow = Calendar.getInstance();
            SimpleDateFormat df = new SimpleDateFormat(sqlRequester.getProperty(Biller.PROPERTIES_SQL_DATE_FORMAT));
            String date = df.format(rightNow.getTime());
            sqlRequest.replace("{StartHour}", date);
            sqlRequest.replace("{EndHour}", date);
            Engine.logBillers.debug("[Biller] Start and End hour computed");
            sqlRequest.replace("{Cost}", Double.toString(cost));
            Engine.logBillers.debug("[Biller] Cost computed");
            sSqlRequest = sqlRequest.toString();
            Engine.logBillers.debug("[Biller] SQL: " + sSqlRequest);
            statement = sqlRequester.connection.createStatement();
            int nResult = statement.executeUpdate(sSqlRequest);
            Engine.logBillers.debug("[Biller] " + nResult + " row(s) inserted.");
        } finally {
            if (statement != null) {
                statement.close();
            }
            Engine.logBillers.info("[Biller] insertCariocaBilling, 1 request in " + (System.currentTimeMillis() - startBilling) + " ms");
        }
    } catch (SQLException e) {
        Engine.logBillers.warn("[Biller] Unable to insert the billing.\n" + e.getMessage() + " (error code: " + e.getErrorCode() + ")\nSQL: " + sSqlRequest);
    } catch (Exception e) {
        Engine.logBillers.error("[Biller] Unable to insert the billing", e);
    }
}
Also used : SiteClipperConnector(com.twinsoft.convertigo.beans.connectors.SiteClipperConnector) HttpConnector(com.twinsoft.convertigo.beans.connectors.HttpConnector) Connector(com.twinsoft.convertigo.beans.core.Connector) HttpConnector(com.twinsoft.convertigo.beans.connectors.HttpConnector) SQLException(java.sql.SQLException) Statement(java.sql.Statement) Calendar(java.util.Calendar) IOException(java.io.IOException) SQLException(java.sql.SQLException) SiteClipperConnector(com.twinsoft.convertigo.beans.connectors.SiteClipperConnector) StringEx(com.twinsoft.util.StringEx) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 8 with StringEx

use of com.twinsoft.util.StringEx in project convertigo by convertigo.

the class RequestableStep method backupWsdlTypes.

protected void backupWsdlTypes(Element element) throws TransformerFactoryConfigurationError, Exception {
    if (wsdlType.equals(""))
        return;
    StringEx sx = new StringEx(wsdlType);
    sx.replaceAll("<cdata>", "<![CDATA[");
    sx.replaceAll("</cdata>", "]]>");
    sx.replaceAll("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>", "");
    String sDom = sx.toString();
    DocumentBuilder documentBuilder = XMLUtils.getDefaultDocumentBuilder();
    Document document = documentBuilder.parse(new InputSource(new StringReader(sDom)));
    String wsdlBackupDir = getWsdlBackupDir(element);
    File dir = new File(wsdlBackupDir);
    if (!dir.exists())
        dir.mkdirs();
    File file = new File(wsdlBackupDir + "/step-" + priority + ".xml");
    XMLUtils.saveXml(document, file);
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilder(javax.xml.parsers.DocumentBuilder) StringReader(java.io.StringReader) StringEx(com.twinsoft.util.StringEx) Document(org.w3c.dom.Document) File(java.io.File)

Example 9 with StringEx

use of com.twinsoft.util.StringEx in project convertigo by convertigo.

the class SqlConnector method configure.

@Override
public void configure(Element element) throws Exception {
    super.configure(element);
    String version = element.getAttribute("version");
    if (version == null) {
        String s = XMLUtils.prettyPrintDOM(element);
        EngineException ee = new EngineException("Unable to find version number for the database object \"" + getName() + "\".\n" + "XML data: " + s);
        throw ee;
    }
    if (VersionUtils.compare(version, "4.6.0") < 0) {
        if ((jdbcURL.startsWith("jdbc:hsqldb:file:")) && (jdbcURL.indexOf("/WEB-INF/minime/") != -1)) {
            StringEx sx = new StringEx(jdbcURL);
            sx.replace("/WEB-INF/minime/", "/WEB-INF/databases/");
            jdbcURL = sx.toString();
            hasChanged = true;
            Engine.logBeans.warn("[SqlConnector] Successfully updated connection string for \"" + getName() + "\" (v 4.6.0)");
        }
    }
}
Also used : EngineException(com.twinsoft.convertigo.engine.EngineException) StringEx(com.twinsoft.util.StringEx)

Example 10 with StringEx

use of com.twinsoft.util.StringEx 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();
        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);
            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());
        // 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
                        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

StringEx (com.twinsoft.util.StringEx)30 EngineException (com.twinsoft.convertigo.engine.EngineException)14 IOException (java.io.IOException)13 Statement (java.sql.Statement)10 SQLException (java.sql.SQLException)9 File (java.io.File)7 PreparedStatement (java.sql.PreparedStatement)7 Document (org.w3c.dom.Document)5 ResultSet (java.sql.ResultSet)4 HttpConnector (com.twinsoft.convertigo.beans.connectors.HttpConnector)3 Element (org.w3c.dom.Element)3 AbstractHttpTransaction (com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction)2 RequestableHttpVariable (com.twinsoft.convertigo.beans.variables.RequestableHttpVariable)2 RequestableVariable (com.twinsoft.convertigo.beans.variables.RequestableVariable)2 StringReader (java.io.StringReader)2 StringWriter (java.io.StringWriter)2 MalformedURLException (java.net.MalformedURLException)2 SimpleDateFormat (java.text.SimpleDateFormat)2 ArrayList (java.util.ArrayList)2 DocumentBuilder (javax.xml.parsers.DocumentBuilder)2