Search in sources :

Example 1 with Replacements

use of com.twinsoft.convertigo.beans.connectors.ProxyHttpConnector.Replacements in project convertigo by convertigo.

the class ProxyServletRequester method coreProcessRequest.

protected Object coreProcessRequest() throws Exception {
    // The proxy converts HTML data on the fly
    ParameterShuttle infoShuttle = threadParameterShuttle.get();
    HttpClient httpClient = threadHttpClient.get();
    HttpServletRequest request = (HttpServletRequest) inputData;
    InputStream siteIn = null;
    try {
        try {
            getUserRequest(infoShuttle, context, request);
            // Loading project
            if (context.projectName == null)
                throw new EngineException("The project name has not been specified!");
            Project currentProject;
            if (Engine.isStudioMode()) {
                currentProject = Engine.objectsProvider.getProject(context.projectName);
                if (currentProject == null) {
                    throw new EngineException("No project has been opened in the Studio. A project should be opened in the Studio in order that the Convertigo engine can work.");
                } else if (!currentProject.getName().equalsIgnoreCase(context.projectName)) {
                    throw new EngineException("The requested project (\"" + context.projectName + "\") does not match with the opened project (\"" + currentProject.getName() + "\") in the Studio.\nYou cannot make a request on a different project than the one opened in the Studio.");
                }
                Engine.logEngine.debug("Using project from Studio");
                context.project = currentProject;
            } else {
                if ((context.project == null) || (context.isNewSession)) {
                    Engine.logEngine.debug("New project requested: '" + context.projectName + "'");
                    context.project = Engine.theApp.databaseObjectsManager.getProjectByName(context.projectName);
                    Engine.logEngine.debug("Project loaded: " + context.project.getName());
                }
            }
            // Loading sequence
            if (context.sequenceName != null) {
                context.requestedObject = context.project.getSequenceByName(context.sequenceName);
                Engine.logEngine.debug("Loaded sequence: " + context.requestedObject.getName());
            }
            // Loading connector
            context.loadConnector();
            if (context.requestedObject != null)
                context.requestedObject.context = context;
            if (context.getConnector() != null)
                context.getConnector().context = context;
            if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) {
                System.setProperty("javax.net.debug", "all");
                Engine.logEngine.trace("(ProxyServletRequester) Enabling SSL debug mode");
            } else {
                System.setProperty("javax.net.debug", "");
                Engine.logEngine.debug("(ProxyServletRequester) Disabling SSL debug mode");
            }
            if (context.getConnector().isTasAuthenticationRequired() && (context.tasSessionKey == null)) {
                throw new EngineException("A Carioca authentication is required in order to process the transaction.");
            }
            infoShuttle.userID = context.tasUserName;
            infoShuttle.userIP = context.remoteAddr;
            // gather user id, parameters, headers from request
            gatherRequestInfo(infoShuttle, request);
            String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);
            try {
                // get connected
                httpClient.connect(infoShuttle);
            } finally {
                context.statistics.stop(t);
            }
            if (infoShuttle.siteInputStream == null) {
                Engine.logEngine.debug("(ProxyServletRequester) No input stream!");
                return null;
            }
            siteIn = infoShuttle.siteInputStream;
            Engine.logEngine.debug("(ProxyServletRequester) Start of document retransmission");
            Object result;
            ProxyHttpConnector proxyHttpConnector = (ProxyHttpConnector) infoShuttle.context.getConnector();
            String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String newBaseUrl = host + request.getRequestURI() + "?" + Parameter.Connector.getName() + "=" + proxyHttpConnector.getName() + "&" + Parameter.ProxyGoto.getName() + "=";
            String newBaseUrlThen = newBaseUrl + URLEncoder.encode(infoShuttle.siteURL.getPath(), "UTF-8") + "&" + Parameter.ProxyThen.getName() + "=";
            if (isDynamicContent(infoShuttle.siteURL.getPath(), proxyHttpConnector.getDynamicContentFiles())) {
                Engine.logEngine.debug("(ProxyServletRequester) Dynamic content");
                String sResponse;
                StringBuffer sbResponse = new StringBuffer("");
                t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);
                try {
                    int c = siteIn.read();
                    char cc;
                    while (c > -1) {
                        cc = (char) c;
                        sbResponse.append(cc);
                        c = siteIn.read();
                    }
                } finally {
                    context.statistics.stop(t, true);
                }
                sResponse = sbResponse.toString();
                result = sResponse;
                if (infoShuttle.siteContentType == null) {
                    Engine.logEngine.warn("(ProxyServletRequester) Aborting string replacements because of null mimetype! Resource: " + infoShuttle.siteURL);
                } else {
                    Engine.logEngine.debug("(ProxyServletRequester) String replacements");
                    // Text/html replacements
                    Engine.logEngine.debug("(ProxyServletRequester) Replacements for mime type '" + infoShuttle.siteContentType + "'");
                    Replacements replacements = proxyHttpConnector.getReplacementsForMimeType(infoShuttle.siteContentType);
                    if (!replacements.isEmpty()) {
                        StringEx sxResponse = new StringEx(sResponse);
                        StringEx sx;
                        String strSearched, strReplacing;
                        for (int i = 0; i < replacements.strReplacing.length; i++) {
                            strSearched = replacements.strSearched[i];
                            sx = new StringEx(strSearched);
                            sx.replaceAll("{tab}", "\t");
                            sx.replaceAll("{apos0x92}", "" + (char) 146);
                            sx.replaceAll("{newBaseUrl}", newBaseUrl);
                            sx.replaceAll("{newBaseUrlThen}", newBaseUrlThen);
                            strSearched = sx.toString();
                            replacements.strSearched[i] = strSearched;
                            Engine.logEngine.debug("(ProxyServletRequester) Replacing: " + strSearched);
                            strReplacing = replacements.strReplacing[i];
                            sx = new StringEx(strReplacing);
                            sx.replaceAll("{newBaseUrl}", newBaseUrl);
                            sx.replaceAll("{newBaseUrlThen}", newBaseUrlThen);
                            strReplacing = sx.toString();
                            replacements.strReplacing[i] = strReplacing;
                            Engine.logEngine.debug("(ProxyServletRequester) By: " + strReplacing);
                        }
                        Engine.logEngine.debug("(ProxyServletRequester) Replacements in progress");
                        sxResponse.replaceAll(replacements.strSearched, replacements.strReplacing);
                        Engine.logEngine.debug("(ProxyServletRequester) Replacements done!");
                        if (Engine.isStudioMode()) {
                            sxResponse.replaceAll("?" + Parameter.Connector.getName() + "=", "?" + Parameter.Context.getName() + "=" + infoShuttle.context.name + "&" + Parameter.Connector.getName() + "=");
                        }
                        result = sxResponse.toString();
                    }
                }
                infoShuttle.siteContentSize = ((String) result).length();
                Engine.logEngine.debug("(ProxyServletRequester) HTML data retrieved!");
                String billingClassName = context.getConnector().getBillingClassName();
                if (billingClassName != null) {
                    try {
                        Engine.logContext.debug("Billing class name required: " + billingClassName);
                        AbstractBiller biller = (AbstractBiller) Class.forName(billingClassName).getConstructor().newInstance();
                        Engine.logContext.debug("Executing the biller");
                        biller.insertBilling(context);
                    } catch (Throwable e) {
                        Engine.logContext.warn("Unable to execute the biller (the billing is thus ignored): [" + e.getClass().getName() + "] " + e.getMessage());
                    }
                }
            } else {
                Engine.logEngine.debug("(ProxyServletRequester) Static content: " + infoShuttle.siteContentType);
                ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
                t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);
                try {
                    // Read either from the cache, either from the remote server
                    int c = siteIn.read();
                    while (c > -1) {
                        baos.write(c);
                        c = siteIn.read();
                    }
                } finally {
                    context.statistics.stop(t, true);
                }
                result = baos.toByteArray();
                Engine.logEngine.debug("(ProxyServletRequester) Static data retrieved!");
                // Determine if the resource has already been cached or not
                String resourceUrl = infoShuttle.siteURL.toString();
                CacheEntry cacheEntry = ProxyServletRequester.proxyCacheManager.getCacheEntry(resourceUrl);
                if (cacheEntry == null) {
                    // Managing text replacements
                    Engine.logEngine.debug("(ProxyServletRequester) Replacements for mime type '" + infoShuttle.siteContentType + "'");
                    Replacements replacements = proxyHttpConnector.getReplacementsForMimeType(infoShuttle.siteContentType);
                    if (!replacements.isEmpty()) {
                        String sResult = new String((byte[]) result);
                        StringEx sxResponse = new StringEx(sResult);
                        StringEx sx;
                        String strSearched, strReplacing;
                        for (int i = 0; i < replacements.strReplacing.length; i++) {
                            strSearched = replacements.strSearched[i];
                            sx = new StringEx(strSearched);
                            sx.replaceAll("{tab}", "\t");
                            sx.replaceAll("{newBaseUrl}", newBaseUrl);
                            sx.replaceAll("{newBaseUrlThen}", newBaseUrlThen);
                            strSearched = sx.toString();
                            replacements.strSearched[i] = strSearched;
                            Engine.logEngine.debug("(ProxyServletRequester) Replacing: " + strSearched);
                            strReplacing = replacements.strReplacing[i];
                            sx = new StringEx(strReplacing);
                            sx.replaceAll("{newBaseUrl}", newBaseUrl);
                            sx.replaceAll("{newBaseUrlThen}", newBaseUrlThen);
                            strReplacing = sx.toString();
                            replacements.strReplacing[i] = strReplacing;
                            Engine.logEngine.debug("(ProxyServletRequester) By: " + strReplacing);
                        }
                        Engine.logEngine.debug("(ProxyServletRequester) Replacements in progress");
                        sxResponse.replaceAll(replacements.strSearched, replacements.strReplacing);
                        Engine.logEngine.debug("(ProxyServletRequester) Replacements done!");
                        result = sxResponse.toString().getBytes();
                    }
                    if (infoShuttle.httpCode == 200) {
                        Engine.logEngine.debug("(ProxyServletRequester) Resource stored: " + resourceUrl);
                        cacheEntry = proxyCacheManager.storeResponse(resourceUrl, (byte[]) result);
                        cacheEntry.contentLength = ((byte[]) result).length;
                        infoShuttle.siteContentSize = cacheEntry.contentLength;
                        cacheEntry.contentType = infoShuttle.siteContentType;
                    }
                } else {
                    infoShuttle.httpCode = 200;
                    infoShuttle.siteContentSize = cacheEntry.contentLength;
                    infoShuttle.siteContentType = cacheEntry.contentType;
                }
                baos.close();
            }
            Engine.logEngine.debug("(ProxyServletRequester) End of document retransmission");
            return result;
        } finally {
            if (siteIn != null) {
                try {
                    siteIn.close();
                } catch (Exception e) {
                }
            }
        }
    } finally {
        context.contentType = infoShuttle.siteContentType;
        httpClient.disconnect();
    }
}
Also used : Replacements(com.twinsoft.convertigo.beans.connectors.ProxyHttpConnector.Replacements) InputStream(java.io.InputStream) ProxyHttpConnector(com.twinsoft.convertigo.beans.connectors.ProxyHttpConnector) EngineException(com.twinsoft.convertigo.engine.EngineException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CacheEntry(com.twinsoft.convertigo.engine.proxy.cache.CacheEntry) IOException(java.io.IOException) EngineException(com.twinsoft.convertigo.engine.EngineException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Project(com.twinsoft.convertigo.beans.core.Project) StringEx(com.twinsoft.util.StringEx) AbstractBiller(com.twinsoft.convertigo.engine.AbstractBiller)

Example 2 with Replacements

use of com.twinsoft.convertigo.beans.connectors.ProxyHttpConnector.Replacements in project convertigo by convertigo.

the class ReverseProxyServlet method handleStringReplacements.

private byte[] handleStringReplacements(String baseUrl, String contentType, String charset, ProxyHttpConnector proxyHttpConnector, byte[] data) throws IOException {
    Engine.logEngine.debug("(ReverseProxyServlet) String replacements for content-type: " + contentType);
    if (contentType == null) {
        Engine.logEngine.warn("(ReverseProxyServlet) Aborting string replacements because of null mimetype!");
    } else {
        Replacements replacements = proxyHttpConnector.getReplacementsForMimeType(contentType);
        if (!replacements.isEmpty()) {
            String sData = new String(data, charset);
            Engine.logEngine.trace("(ReverseProxyServlet) Data before string replacements:\n" + sData);
            Engine.logEngine.debug("(ReverseProxyServlet) Replacements in progress");
            String strSearched, strReplacing;
            for (int i = 0; i < replacements.strReplacing.length; i++) {
                strSearched = replacements.strSearched[i];
                Engine.logEngine.debug("(ReverseProxyServlet) Replacing: " + strSearched);
                strReplacing = replacements.strReplacing[i];
                Matcher m_connector = reg_connector.matcher(strReplacing);
                if (m_connector.find() && m_connector.groupCount() >= 1) {
                    String newConnector = m_connector.group(1);
                    Engine.logEngine.trace("(ReverseProxyServlet) find connector : " + newConnector);
                    // Bugfix for #1798 regression about #1718
                    String newBaseUrl = switchConnector(baseUrl, newConnector) + '/';
                    Engine.logEngine.trace("(ReverseProxyServlet) new baseUrl : " + newBaseUrl);
                    strReplacing = m_connector.replaceAll(newBaseUrl);
                } else {
                    strReplacing = reg_base.matcher(replacements.strReplacing[i]).replaceAll(baseUrl);
                }
                Engine.logEngine.debug("(ReverseProxyServlet) By: " + strReplacing);
                sData = sData.replaceAll(strSearched, strReplacing);
            }
            Engine.logEngine.debug("(ReverseProxyServlet) Replacements done!");
            Engine.logEngine.trace("(ReverseProxyServlet) Data after string replacements:\n" + sData);
            data = sData.getBytes(charset);
        }
    }
    return data;
}
Also used : Replacements(com.twinsoft.convertigo.beans.connectors.ProxyHttpConnector.Replacements) Matcher(java.util.regex.Matcher)

Aggregations

Replacements (com.twinsoft.convertigo.beans.connectors.ProxyHttpConnector.Replacements)2 ProxyHttpConnector (com.twinsoft.convertigo.beans.connectors.ProxyHttpConnector)1 Project (com.twinsoft.convertigo.beans.core.Project)1 AbstractBiller (com.twinsoft.convertigo.engine.AbstractBiller)1 EngineException (com.twinsoft.convertigo.engine.EngineException)1 CacheEntry (com.twinsoft.convertigo.engine.proxy.cache.CacheEntry)1 StringEx (com.twinsoft.util.StringEx)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Matcher (java.util.regex.Matcher)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1