Search in sources :

Example 1 with VicApi

use of com.twinsoft.convertigo.engine.plugins.VicApi 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)

Example 2 with VicApi

use of com.twinsoft.convertigo.engine.plugins.VicApi in project convertigo by convertigo.

the class JavelinConnector method prepareForTransaction.

@Override
public void prepareForTransaction(Context context) throws EngineException {
    String t = context.statistics.start(EngineStatistics.GET_JAVELIN_OBJECT);
    try {
        // Quick and dirty workaround for ticket #1280
        if (!checkKeys())
            throw new EngineException("No more key available; check your license keys!");
        // if something append during transaction execution
        com.twinsoft.api.Session session = Engine.theApp.sessionManager.getSession(context.contextID);
        if (session != null)
            session.resetSomethingChange();
        if (Engine.isStudioMode()) {
            if (javelin != null) {
                Engine.logBeans.debug("(JavelinConnector) Using the studio Javelin object");
                return;
            }
            throw new EngineException("Studio mode: the Legacy connector must be open in order to execute transactions");
        }
        Engine.logBeans.debug("(JavelinConnector) Retrieving the Javelin object");
        JavelinTransaction javelinTransaction = null;
        try {
            javelinTransaction = (JavelinTransaction) context.requestedObject;
        } catch (ClassCastException e) {
            throw new EngineException("Requested object is not a transaction", e);
        }
        int timeout = javelinTransaction.getTimeoutForDataStable();
        int threshold = javelinTransaction.getDataStableThreshold();
        Authentication auth = null;
        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);
                }
            }
        } else {
            // Check the Carioca authorizations only if this is a non trusted request
            if (context.isTrustedRequest) {
            // Nothing to do: all the tas* variables from the context must have been set
            // by the caller.
            // Means we must not execute the TAS API.
            } else {
                // Getting Authentication object
                context.tasVirtualServerName = getVirtualServer();
                try {
                    String authName = (context.tasSessionKey == null ? context.tasUserName : context.tasSessionKey);
                    auth = Engine.theApp.getAuthenticationObject(context.tasVirtualServerName, authName);
                    // Logging to Carioca only if needed
                    User user = auth.getCurrentUser();
                    if (user == null) {
                        // Request from Carioca
                        if (context.tasSessionKey != null) {
                            auth.login(context.tasSessionKey);
                            User currentUser = auth.getCurrentUser();
                            context.tasUserName = currentUser.getName();
                            context.tasUserPassword = currentUser.getPassword();
                            context.tasVirtualServerName = "(SV #" + currentUser.getServerID() + ")";
                            String message = "Authentication to Carioca with sesskey = '" + context.tasSessionKey + "' => user: \"" + context.tasUserName + "\"";
                            Engine.logBeans.debug("(JavelinConnector) " + message);
                        } else // Specific user
                        if ((context.tasUserName != null) && (context.tasUserPassword != null)) {
                            auth.login(context.tasUserName, context.tasUserPassword);
                            String message = "Authentication to Carioca with user = '" + context.tasUserName + "' and password = '" + context.tasUserPassword + "'";
                            Engine.logBeans.debug("(JavelinConnector) " + message);
                        } else {
                            context.tasUserName = EnginePropertiesManager.getProperty(PropertyName.CARIOCA_DEFAULT_USER_NAME);
                            context.tasUserPassword = EnginePropertiesManager.getProperty(PropertyName.CARIOCA_DEFAULT_USER_PASSWORD);
                            auth.login(context.tasUserName, context.tasUserPassword);
                            String message = "Default authentication to Carioca";
                            Engine.logBeans.debug("(JavelinConnector) " + message);
                        }
                    } else {
                        context.tasUserName = user.getName();
                        context.tasUserPassword = user.getPassword();
                        context.tasUserGroup = user.getMainGroupName();
                        context.tasVirtualServerName = "(#" + Long.toString(user.getServerID()) + ")";
                        String message = "Already authenticated to Carioca with user = '" + context.tasUserName + "' and password = '" + context.tasUserPassword + "'";
                        Engine.logBeans.debug("(JavelinConnector) " + message);
                    }
                } catch (Exception e) {
                    auth = null;
                    String message = "Unable to authenticate to Carioca.\n" + "Carioca virtual server: " + context.tasVirtualServerName + "\n" + "SessKey: \"" + context.tasSessionKey + "\"\n" + "User: \"" + context.tasUserName + "\"\n" + "Password: \"" + context.tasUserPassword + "\"";
                    EngineException ee = new EngineException(message, e);
                    throw ee;
                }
            }
        }
        // We retrieve the current project
        String javelinServiceCode = context.tasServiceCode;
        if (javelinServiceCode == null) {
            javelinServiceCode = getServiceCode();
            Engine.logBeans.debug("(JavelinConnector)  No service code provided; getting the connector service code.");
        }
        // Analyzes/overrrides service code for device number pooling
        javelinServiceCode = analyzeServiceCode(javelinServiceCode);
        Engine.logBeans.debug("(JavelinConnector) Service code: " + javelinServiceCode);
        session = Engine.theApp.sessionManager.getSession(context.contextID);
        if (session == null) {
            Engine.logBeans.debug("(JavelinConnector) No session has been found; creation of a new one and ignoring the user request.");
            context.inputDocument = null;
            try {
                if (context.isRequestFromVic) {
                    session = Engine.theApp.sessionManager.addVicSession(javelinServiceCode, context.tasUserName, context.tasUserGroup + "@" + context.tasVirtualServerName, context.tasDteAddress, context.tasCommDevice, context.contextID);
                } else if (context.isTrustedRequest) {
                    String connectionParameters = getServiceCode();
                    try {
                        StringTokenizer st = new StringTokenizer(connectionParameters, ",");
                        String appType = st.nextToken();
                        if (appType.equals("vic")) {
                            javelinServiceCode = st.nextToken();
                            context.tasDteAddress = st.nextToken();
                            context.tasCommDevice = st.nextToken();
                            Engine.logBeans.debug("(JavelinConnector) Trusted request => the connector handles connection parameters : " + connectionParameters);
                            Engine.logBeans.debug("(JavelinConnector) serviceCode: " + javelinServiceCode);
                            Engine.logBeans.debug("(JavelinConnector) dteAddress: " + context.tasDteAddress);
                            Engine.logBeans.debug("(JavelinConnector) commDevice: " + context.tasCommDevice);
                            Engine.logBeans.debug("(JavelinConnector) user: " + context.tasUserName);
                            String group = context.tasUserGroup + "@" + context.tasVirtualServerName;
                            Engine.logBeans.debug("(JavelinConnector) group: " + group);
                            session = Engine.theApp.sessionManager.addVicSession(javelinServiceCode, context.tasUserName, group, context.tasDteAddress, context.tasCommDevice, context.contextID);
                        }
                    } catch (NoSuchElementException e) {
                        Engine.logBeans.error("(JavelinConnector) Invalid connector connection parameters: " + connectionParameters);
                    }
                } else {
                    session = Engine.theApp.sessionManager.addSession((int) emulatorID, auth, javelinServiceCode, context.contextID, getJavelinLanguage(), isSslEnabled(), isSslTrustAllServerCertificates(), getIbmTerminalType());
                }
            } catch (Exception e) {
                String message = "Unable to open the Javelin session: serviceCode= '" + javelinServiceCode + "', contextID = '" + context.contextID + "'";
                EngineException ee = new EngineException(message, e);
                throw ee;
            }
            if (session == null) {
                String message = "Unable to add a new session: the access to the service '" + javelinServiceCode + "' has been forbidden by the Carioca administrator.";
                EngineException ee = new EngineException(message);
                throw ee;
            }
            javelin = session.getJavelinObject();
            javelin.setLog(new LogWrapper(Engine.logEmulators));
            javelin.setDataStableOnCursorOn(false);
            javelin.connect(javelinTransaction.getTimeoutForConnect());
            boolean isConnected = javelin.isConnected();
            Engine.logBeans.debug("(JavelinConnector) isConnected=" + isConnected);
            if (!isConnected) {
                throw new ConnectionException("Unable to connect the session! See the emulator logs for more details...");
            }
            executeConnectionSyncCode(javelin, timeout, threshold);
        } else {
            Engine.logBeans.debug("(JavelinConnector) Using the existing session");
            if (context.isNewSession) {
                Engine.logBeans.debug("(JavelinConnector) New session required and ignoring the user request");
                context.inputDocument = null;
                // First, we remove the previous session
                Engine.theApp.sessionManager.removeSession(context.contextID);
                try {
                    if (context.isRequestFromVic) {
                        session = Engine.theApp.sessionManager.addVicSession(javelinServiceCode, context.tasUserName, context.tasUserGroup, context.tasDteAddress, context.tasCommDevice, context.contextID);
                    } else {
                        session = Engine.theApp.sessionManager.addSession((int) emulatorID, auth, javelinServiceCode, context.contextID, getJavelinLanguage(), isSslEnabled(), isSslTrustAllServerCertificates(), getIbmTerminalType());
                    }
                } catch (Exception e) {
                    String message = "Unable to open the Javelin session: serviceCode= '" + javelinServiceCode + "', contextID = '" + context.contextID + "'";
                    Engine.logBeans.warn("(JavelinConnector) " + message);
                    EngineException ee = new EngineException(message, e);
                    throw ee;
                }
                if (session == null) {
                    String message = "Unable to add a new session: the access to the service '" + javelinServiceCode + "' has been forbidden by the Carioca administrator.";
                    Engine.logBeans.warn("(JavelinConnector) " + message);
                    EngineException ee = new EngineException(message);
                    throw ee;
                }
                javelin = session.getJavelinObject();
                javelin.setLog(new LogWrapper(Engine.logEmulators));
                javelin.setDataStableOnCursorOn(false);
                javelin.connect(javelinTransaction.getTimeoutForConnect());
                if (!javelin.isConnected()) {
                    throw new ConnectionException("Unable to connect the session! See the emulator logs for more details...");
                }
                executeConnectionSyncCode(javelin, timeout, threshold);
            } else {
                javelin = session.getJavelinObject();
                // Reconnect only if the requested transaction is not the end transaction
                if ((!context.isDestroying) && (!session.isConnected())) {
                    javelin.setDataStableOnCursorOn(false);
                    javelin.connect(javelinTransaction.getTimeoutForConnect());
                    if (!javelin.isConnected()) {
                        throw new ConnectionException("Unable to connect the session! See the emulator logs for more details...");
                    }
                    executeConnectionSyncCode(javelin, timeout, threshold);
                }
            }
        }
        context.isNewSession = false;
    } finally {
        context.statistics.stop(t);
    }
}
Also used : User(com.twinsoft.tas.User) EngineException(com.twinsoft.convertigo.engine.EngineException) FindString(com.twinsoft.convertigo.beans.common.FindString) IOException(java.io.IOException) LogWrapper(com.twinsoft.convertigo.engine.util.LogWrapper) RESyntaxException(org.apache.regexp.RESyntaxException) NoSuchElementException(java.util.NoSuchElementException) EvaluatorException(org.mozilla.javascript.EvaluatorException) JavaScriptException(org.mozilla.javascript.JavaScriptException) IOException(java.io.IOException) EngineException(com.twinsoft.convertigo.engine.EngineException) JavelinTransaction(com.twinsoft.convertigo.beans.transactions.JavelinTransaction) StringTokenizer(java.util.StringTokenizer) Authentication(com.twinsoft.tas.Authentication) VicApi(com.twinsoft.convertigo.engine.plugins.VicApi) NoSuchElementException(java.util.NoSuchElementException)

Aggregations

EngineException (com.twinsoft.convertigo.engine.EngineException)2 VicApi (com.twinsoft.convertigo.engine.plugins.VicApi)2 IOException (java.io.IOException)2 FindString (com.twinsoft.convertigo.beans.common.FindString)1 AbstractHttpTransaction (com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction)1 JavelinTransaction (com.twinsoft.convertigo.beans.transactions.JavelinTransaction)1 RequestableHttpVariable (com.twinsoft.convertigo.beans.variables.RequestableHttpVariable)1 RequestableVariable (com.twinsoft.convertigo.beans.variables.RequestableVariable)1 LogWrapper (com.twinsoft.convertigo.engine.util.LogWrapper)1 Authentication (com.twinsoft.tas.Authentication)1 User (com.twinsoft.tas.User)1 StringEx (com.twinsoft.util.StringEx)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 StringWriter (java.io.StringWriter)1 MalformedURLException (java.net.MalformedURLException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1