Search in sources :

Example 1 with CertificateManager

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

the class TransactionWithVariables method getRequestString.

public String getRequestString(Context context) {
    checkSubLoaded();
    List<String> vVariables = new ArrayList<String>(variables.size());
    // Use authenticated user as cache key
    if (isAuthenticatedUserAsCacheKey())
        vVariables.add("userID=" + context.getAuthenticatedUser());
    for (String variableName : variables.keySet()) {
        if (includeVariableIntoRequestString(variableName)) {
            String variableValueAsString = ParameterUtils.toString(variables.get(variableName));
            vVariables.add(variableName + "=" + variableValueAsString);
        }
    }
    if (bIncludeCertificateGroup) {
        try {
            CertificateManager certificateManager = ((HttpConnector) getParent()).certificateManager;
            certificateManager.collectStoreInformation(context);
            if ((certificateManager.keyStoreGroup == null) || (certificateManager.keyStoreGroup.length() == 0)) {
                vVariables.add("certificateGroup=" + certificateManager.keyStoreName);
            } else {
                vVariables.add("certificateGroup=" + certificateManager.keyStoreGroup);
            }
        } catch (EngineException e) {
            vVariables.add("certificateGroup=exception");
        }
    }
    Collections.sort(vVariables);
    String requestString = context.projectName + " " + context.transactionName + " " + vVariables.toString();
    return requestString;
}
Also used : HttpConnector(com.twinsoft.convertigo.beans.connectors.HttpConnector) ArrayList(java.util.ArrayList) EngineException(com.twinsoft.convertigo.engine.EngineException) CertificateManager(com.twinsoft.convertigo.engine.CertificateManager)

Example 2 with CertificateManager

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

the class JsseSecureSocketImpl method connect.

@SuppressWarnings("rawtypes")
@Override
public void connect(InetAddress adr, int port, short[] suites, byte[][] certs, Hashtable clientCertProperties) throws IOException {
    Engine.logEmulators.debug("[JsseSecureSocketImpl] Connecting...");
    Engine.logEmulators.trace("jdk.certpath.disabledAlgorithms=" + java.security.Security.getProperty("jdk.certpath.disabledAlgorithms"));
    Engine.logEmulators.trace("jdk.tls.disabledAlgorithms=" + java.security.Security.getProperty("jdk.tls.disabledAlgorithms"));
    Boolean bTrustAllServerCertificates = Boolean.TRUE;
    String contextID = null;
    if (clientCertProperties != null) {
        if (clientCertProperties.get(ACL.CERT_PROPERTY_NAME_FORMAT).equals("c8o")) {
            Hashtable customProps = (Hashtable) clientCertProperties.get(ACL.CERT_PROPERTY_NAME_CONTENT);
            contextID = (String) customProps.get("ContextID");
            bTrustAllServerCertificates = (Boolean) customProps.get("TrustAllServerCertificates");
        }
    }
    if (contextID == null) {
        throw new IOException("Invalid c8o ContextID");
    }
    try {
        CertificateManager cm = new CertificateManager();
        cm.collectStoreInformation(Engine.theApp.contextManager.get(contextID));
        SSLSocket socket = (SSLSocket) MySSLSocketFactory.getSSLSocketFactory(cm.keyStore, cm.keyStorePassword, cm.trustStore, cm.trustStorePassword, bTrustAllServerCertificates).createSocket(adr.getHostAddress(), Integer.valueOf(port));
        if (socket != null) {
            String[] supportedProtocols = socket.getSupportedProtocols();
            Engine.logEmulators.trace("[JsseSesureSocketImpl] Supported protocols:" + Arrays.asList(supportedProtocols));
            String[] enabledProtocols = socket.getEnabledProtocols();
            Engine.logEmulators.trace("[JsseSesureSocketImpl] Enabled protocols:" + Arrays.asList(enabledProtocols));
            // Engine.logEmulators.trace("[JsseSesureSocketImpl] Enabling all supported protocols...");
            // socket.setEnabledProtocols(supportedProtocols);
            String[] supportedSuites = socket.getSupportedCipherSuites();
            Engine.logEmulators.trace("[JsseSesureSocketImpl] Supported cipher suites:" + Arrays.asList(supportedSuites));
            String[] enabledSuites = socket.getEnabledCipherSuites();
            Engine.logEmulators.trace("[JsseSesureSocketImpl] Enabled cipher suites:" + Arrays.asList(enabledSuites));
            // Engine.logEmulators.trace("[JsseSesureSocketImpl] Enabling all supported cipher suites...");
            // socket.setEnabledCipherSuites(supportedSuites);
            socket.addHandshakeCompletedListener(this);
            Engine.logEmulators.trace("[JsseSesureSocketImpl] Start handshake...");
            socket.startHandshake();
            isTrusted = true;
            isExpired = false;
            secureSocket = socket;
            Engine.logEmulators.debug("[JsseSesureSocketImpl] Socket retrieved !");
        } else
            throw new IOException("Invalid socket (null)");
    } catch (Exception e) {
        Engine.logEmulators.error(e);
        if (e instanceof IOException) {
            if (e instanceof SSLPeerUnverifiedException) {
                isTrusted = false;
                throw new IOException("Remote server is not verified", e);
            }
            if (e instanceof CertificateExpiredException) {
                isExpired = true;
                throw new IOException("Certificate has expired", e);
            }
            if (e instanceof CertificateNotYetValidException) {
                isExpired = true;
                throw new IOException("Certificate has expired", e);
            } else {
                throw ((IOException) e);
            }
        } else {
            throw new IOException("Unable to connect through JSSE", e);
        }
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) Hashtable(java.util.Hashtable) SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) CertificateManager(com.twinsoft.convertigo.engine.CertificateManager) IOException(java.io.IOException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) IOException(java.io.IOException) CertificateExpiredException(java.security.cert.CertificateExpiredException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException)

Example 3 with CertificateManager

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

the class ReverseProxyServlet method doRequest.

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @param httpMethodProxyRequest
 *            An object representing the proxy request to be made
 * @param httpServletResponse
 *            An object by which we can send the proxied response back to
 *            the client
 * @throws IOException
 *             Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException
 *             Can be thrown to indicate that another error has occurred
 * @throws EngineException
 */
private void doRequest(HttpMethodType httpMethodType, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
    try {
        Engine.logEngine.debug("(ReverseProxyServlet) Starting request handling");
        if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) {
            System.setProperty("javax.net.debug", "all");
            Engine.logEngine.trace("(ReverseProxyServlet) Enabling SSL debug mode");
        } else {
            System.setProperty("javax.net.debug", "");
            Engine.logEngine.debug("(ReverseProxyServlet) Disabling SSL debug mode");
        }
        String baseUrl;
        String projectName;
        String connectorName;
        String contextName;
        String extraPath;
        {
            String requestURI = httpServletRequest.getRequestURI();
            Engine.logEngine.trace("(ReverseProxyServlet) Requested URI : " + requestURI);
            Matcher m = reg_fields.matcher(requestURI);
            if (m.matches() && m.groupCount() >= 5) {
                baseUrl = m.group(1);
                projectName = m.group(2);
                connectorName = m.group(3);
                contextName = m.group(4);
                extraPath = m.group(5);
            } else {
                throw new MalformedURLException("The request doesn't contains needed fields : projectName, connectorName and contextName");
            }
        }
        String sessionID = httpServletRequest.getSession().getId();
        Engine.logEngine.debug("(ReverseProxyServlet) baseUrl : " + baseUrl + " ; projectName : " + projectName + " ; connectorName : " + connectorName + " ; contextName : " + contextName + " ; extraPath : " + extraPath + " ; sessionID : " + sessionID);
        Context context = Engine.theApp.contextManager.get(null, contextName, sessionID, null, projectName, connectorName, null);
        Project project = Engine.theApp.databaseObjectsManager.getProjectByName(projectName);
        context.projectName = projectName;
        context.project = project;
        ProxyHttpConnector proxyHttpConnector = (ProxyHttpConnector) project.getConnectorByName(connectorName);
        context.connector = proxyHttpConnector;
        context.connectorName = proxyHttpConnector.getName();
        HostConfiguration hostConfiguration = proxyHttpConnector.hostConfiguration;
        // Proxy configuration
        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();
        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(ReverseProxyServlet) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }
        String targetHost = proxyHttpConnector.getServer();
        Engine.logEngine.debug("(ReverseProxyServlet) Target host: " + targetHost);
        int targetPort = proxyHttpConnector.getPort();
        Engine.logEngine.debug("(ReverseProxyServlet) Target port: " + targetPort);
        // Configuration SSL
        Engine.logEngine.debug("(ReverseProxyServlet) Https: " + proxyHttpConnector.isHttps());
        CertificateManager certificateManager = proxyHttpConnector.certificateManager;
        boolean trustAllServerCertificates = proxyHttpConnector.isTrustAllServerCertificates();
        if (proxyHttpConnector.isHttps()) {
            Engine.logEngine.debug("(ReverseProxyServlet) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);
            Engine.logEngine.debug("(ReverseProxyServlet) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!targetHost.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != targetPort)) {
                Engine.logEngine.debug("(ReverseProxyServlet) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, trustAllServerCertificates), targetPort);
                hostConfiguration.setHost(targetHost, targetPort, myhttps);
            }
            Engine.logEngine.debug("(ReverseProxyServlet) Updated host configuration for SSL purposes");
        } else {
            hostConfiguration.setHost(targetHost, targetPort);
        }
        HttpMethod httpMethodProxyRequest;
        String targetPath = proxyHttpConnector.getBaseDir() + extraPath;
        // Handle the query string
        if (httpServletRequest.getQueryString() != null) {
            targetPath += "?" + httpServletRequest.getQueryString();
        }
        Engine.logEngine.debug("(ReverseProxyServlet) Target path: " + targetPath);
        Engine.logEngine.debug("(ReverseProxyServlet) Requested method: " + httpMethodType);
        if (httpMethodType == HttpMethodType.GET) {
            // Create a GET request
            httpMethodProxyRequest = new GetMethod();
        } else if (httpMethodType == HttpMethodType.POST) {
            // Create a standard POST request
            httpMethodProxyRequest = new PostMethod();
            ((PostMethod) httpMethodProxyRequest).setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream()));
        } else {
            throw new IllegalArgumentException("Unknown HTTP method: " + httpMethodType);
        }
        String charset = httpMethodProxyRequest.getParams().getUriCharset();
        URI targetURI;
        try {
            targetURI = new URI(targetPath, true, charset);
        } catch (URIException e) {
            // Bugfix #1484
            String newTargetPath = "";
            for (String part : targetPath.split("&")) {
                if (!newTargetPath.equals("")) {
                    newTargetPath += "&";
                }
                String[] pair = part.split("=");
                try {
                    newTargetPath += URLDecoder.decode(pair[0], "UTF-8") + "=" + (pair.length > 1 ? URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8") : "");
                } catch (UnsupportedEncodingException ee) {
                    newTargetPath = targetPath;
                }
            }
            targetURI = new URI(newTargetPath, true, charset);
        }
        httpMethodProxyRequest.setURI(targetURI);
        // Tells the method to automatically handle authentication.
        httpMethodProxyRequest.setDoAuthentication(true);
        HttpState httpState = getHttpState(proxyHttpConnector, context);
        String basicUser = proxyHttpConnector.getAuthUser();
        String basicPassword = proxyHttpConnector.getAuthPassword();
        String givenBasicUser = proxyHttpConnector.getGivenAuthUser();
        String givenBasicPassword = proxyHttpConnector.getGivenAuthPassword();
        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(targetHost, targetPort, realm), new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Credentials: " + userName + ":******");
        }
        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Proxy credentials: " + proxyUser + ":******");
        }
        // Forward the request headers
        setProxyRequestHeaders(httpServletRequest, httpMethodProxyRequest, proxyHttpConnector);
        // Use the CEMS HttpClient
        HttpClient httpClient = Engine.theApp.httpClient;
        httpMethodProxyRequest.setFollowRedirects(false);
        // Execute the request
        int intProxyResponseCode = httpClient.executeMethod(hostConfiguration, httpMethodProxyRequest, httpState);
        // Hooray for open source software
        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES && /* 300 */
        intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED) /* 304 */
        {
            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            if (stringLocation == null) {
                throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response");
            }
            // Modify the redirect to go to this proxy servlet rather that
            // the
            // proxied host
            String redirect = handleRedirect(stringLocation, baseUrl, proxyHttpConnector);
            httpServletResponse.sendRedirect(redirect);
            Engine.logEngine.debug("(ReverseProxyServlet) Send redirect (" + redirect + ")");
            return;
        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            Engine.logEngine.debug("(ReverseProxyServlet) NOT MODIFIED (304)");
            return;
        }
        // Pass the response code back to the client
        httpServletResponse.setStatus(intProxyResponseCode);
        // Pass response headers back to the client
        Engine.logEngine.debug("(ReverseProxyServlet) Response headers back to the client:");
        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
        for (Header header : headerArrayResponse) {
            String headerName = header.getName();
            String headerValue = header.getValue();
            if (!headerName.equalsIgnoreCase("Transfer-Encoding") && !headerName.equalsIgnoreCase("Set-Cookie")) {
                httpServletResponse.setHeader(headerName, headerValue);
                Engine.logEngine.debug("   " + headerName + "=" + headerValue);
            }
        }
        String contentType = null;
        Header[] contentTypeHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Type");
        for (Header contentTypeHeader : contentTypeHeaders) {
            contentType = contentTypeHeader.getValue();
            break;
        }
        String pageCharset = "UTF-8";
        if (contentType != null) {
            int iCharset = contentType.indexOf("charset=");
            if (iCharset != -1) {
                pageCharset = contentType.substring(iCharset + "charset=".length()).trim();
            }
            Engine.logEngine.debug("(ReverseProxyServlet) Using charset: " + pageCharset);
        }
        InputStream siteIn = httpMethodProxyRequest.getResponseBodyAsStream();
        // Handle gzipped content
        Header[] contentEncodingHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Encoding");
        boolean bGZip = false, bDeflate = false;
        for (Header contentEncodingHeader : contentEncodingHeaders) {
            HeaderElement[] els = contentEncodingHeader.getElements();
            for (int j = 0; j < els.length; j++) {
                if ("gzip".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode GZip stream");
                    siteIn = new GZIPInputStream(siteIn);
                    bGZip = true;
                } else if ("deflate".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode Deflate stream");
                    siteIn = new InflaterInputStream(siteIn, new Inflater(true));
                    bDeflate = true;
                }
            }
        }
        byte[] bytesDataResult;
        ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
        // String resourceUrl = projectName + targetPath;
        String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);
        try {
            // Read either from the cache, either from the remote server
            // InputStream is = proxyCacheManager.getResource(resourceUrl);
            // if (is != null) {
            // Engine.logEngine.debug("(ReverseProxyServlet) Getting data from cache");
            // siteIn = is;
            // }
            int c = siteIn.read();
            while (c > -1) {
                baos.write(c);
                c = siteIn.read();
            }
        // if (is != null) is.close();
        } finally {
            context.statistics.stop(t, true);
        }
        bytesDataResult = baos.toByteArray();
        baos.close();
        Engine.logEngine.debug("(ReverseProxyServlet) Data retrieved!");
        // if (isDynamicContent(httpServletRequest.getPathInfo(),
        // proxyHttpConnector.getDynamicContentFiles())) {
        Engine.logEngine.debug("(ReverseProxyServlet) Dynamic content");
        bytesDataResult = handleStringReplacements(baseUrl, contentType, pageCharset, proxyHttpConnector, bytesDataResult);
        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());
            }
        }
        // Send the content to the client
        if (Engine.logEngine.isDebugEnabled() && MimeType.Html.is(contentType)) {
            Engine.logEngine.debug("Data proxied:\n" + new String(bytesDataResult, pageCharset));
        }
        if (bGZip || bDeflate) {
            baos = new ByteArrayOutputStream();
            OutputStream compressedOutputStream = bGZip ? new GZIPOutputStream(baos) : new DeflaterOutputStream(baos, new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
            compressedOutputStream.write(bytesDataResult);
            compressedOutputStream.close();
            bytesDataResult = baos.toByteArray();
            baos.close();
        }
        httpServletResponse.setContentLength(bytesDataResult.length);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        outputStreamClientResponse.write(bytesDataResult);
        Engine.logEngine.debug("(ReverseProxyServlet) End of document retransmission");
    } catch (Exception e) {
        Engine.logEngine.error("Error while trying to proxy page", e);
        throw new ServletException("Error while trying to proxy page", e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) Matcher(java.util.regex.Matcher) PostMethod(org.apache.commons.httpclient.methods.PostMethod) ProxyHttpConnector(com.twinsoft.convertigo.beans.connectors.ProxyHttpConnector) GZIPOutputStream(java.util.zip.GZIPOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DeflaterOutputStream(java.util.zip.DeflaterOutputStream) OutputStream(java.io.OutputStream) HttpState(org.apache.commons.httpclient.HttpState) CertificateManager(com.twinsoft.convertigo.engine.CertificateManager) URI(org.apache.commons.httpclient.URI) ServletException(javax.servlet.ServletException) GZIPInputStream(java.util.zip.GZIPInputStream) URIException(org.apache.commons.httpclient.URIException) Deflater(java.util.zip.Deflater) GZIPOutputStream(java.util.zip.GZIPOutputStream) DeflaterOutputStream(java.util.zip.DeflaterOutputStream) Protocol(org.apache.commons.httpclient.protocol.Protocol) AbstractBiller(com.twinsoft.convertigo.engine.AbstractBiller) Context(com.twinsoft.convertigo.engine.Context) HostConfiguration(org.apache.commons.httpclient.HostConfiguration) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement) InflaterInputStream(java.util.zip.InflaterInputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletException(javax.servlet.ServletException) URIException(org.apache.commons.httpclient.URIException) EngineException(com.twinsoft.convertigo.engine.EngineException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Project(com.twinsoft.convertigo.beans.core.Project) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) AuthScope(org.apache.commons.httpclient.auth.AuthScope) Inflater(java.util.zip.Inflater) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 4 with CertificateManager

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

the class SiteClipperConnector method clone.

@Override
public SiteClipperConnector clone() throws CloneNotSupportedException {
    SiteClipperConnector siteClipperConnector = (SiteClipperConnector) super.clone();
    siteClipperConnector.screenClassHelper = new ScreenClassHelper<SiteClipperScreenClass>(siteClipperConnector);
    siteClipperConnector.domainsFilter = new DomainsFilterHelper(siteClipperConnector);
    siteClipperConnector.givenAuthPassword = null;
    siteClipperConnector.givenAuthUser = null;
    siteClipperConnector.givenAuthMode = null;
    siteClipperConnector.certificateManager = new CertificateManager();
    siteClipperConnector.siteClipperRequestObjectsPerThread = Collections.synchronizedMap(new HashMap<Thread, Shuttle>());
    return siteClipperConnector;
}
Also used : HashMap(java.util.HashMap) DomainsFilterHelper(com.twinsoft.convertigo.engine.helpers.DomainsFilterHelper) SiteClipperScreenClass(com.twinsoft.convertigo.beans.screenclasses.SiteClipperScreenClass) CertificateManager(com.twinsoft.convertigo.engine.CertificateManager)

Example 5 with CertificateManager

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

the class HttpClient method getData.

private byte[] getData(HttpConnector connector, String resourceUrl, ParameterShuttle infoShuttle) throws IOException, EngineException {
    byte[] result = null;
    try {
        Context context = infoShuttle.context;
        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();
        HostConfiguration hostConfiguration = connector.hostConfiguration;
        boolean trustAllServerCertificates = connector.isTrustAllServerCertificates();
        // Retrieving httpState
        getHttpState(connector, infoShuttle);
        Engine.logEngine.trace("(HttpClient) Retrieving data as a bytes array...");
        Engine.logEngine.debug("(HttpClient) Connecting to: " + resourceUrl);
        // Proxy configuration
        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(HttpClient) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }
        Engine.logEngine.debug("(HttpClient) Https: " + connector.isHttps());
        CertificateManager certificateManager = connector.certificateManager;
        URL url = null;
        String host = "";
        int port = -1;
        if (resourceUrl.toLowerCase().startsWith("https:")) {
            Engine.logEngine.debug("(HttpClient) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);
            url = new URL(resourceUrl);
            host = url.getHost();
            port = url.getPort();
            if (port == -1)
                port = 443;
            Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port);
            Engine.logEngine.debug("(HttpClient) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) {
                Engine.logEngine.debug("(HttpClient) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, trustAllServerCertificates), port);
                hostConfiguration.setHost(host, port, myhttps);
            }
            resourceUrl = url.getFile();
            Engine.logEngine.debug("(HttpClient) Updated URL for SSL purposes: " + resourceUrl);
        } else {
            url = new URL(resourceUrl);
            host = url.getHost();
            port = url.getPort();
            Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port);
            hostConfiguration.setHost(host, port);
        }
        Engine.logEngine.debug("(HttpClient) Building method on: " + resourceUrl);
        Engine.logEngine.debug("(HttpClient) postFromUser=" + infoShuttle.postFromUser);
        Engine.logEngine.debug("(HttpClient) postToSite=" + infoShuttle.postToSite);
        if (infoShuttle.postFromUser && infoShuttle.postToSite) {
            method = new PostMethod(resourceUrl);
            ((PostMethod) method).setRequestEntity(new StringRequestEntity(infoShuttle.userPostData, infoShuttle.userContentType, infoShuttle.context.httpServletRequest.getCharacterEncoding()));
        } else {
            method = new GetMethod(resourceUrl);
        }
        HttpMethodParams httpMethodParams = method.getParams();
        // Cookie configuration
        if (handleCookie) {
            Engine.logEngine.debug("(HttpClient) Setting cookie policy.");
            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }
        String basicUser = connector.getAuthUser();
        String basicPassword = connector.getAuthPassword();
        String givenBasicUser = connector.getGivenAuthUser();
        String givenBasicPassword = connector.getGivenAuthPassword();
        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(host, port, realm), new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(HttpClient) Credentials: " + userName + ":******");
        }
        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(HttpClient) Proxy credentials: " + proxyUser + ":******");
        }
        // Setting HTTP headers
        Engine.logEngine.debug("(HttpClient) Incoming HTTP headers:");
        String headerName, headerValue;
        for (int k = 0, kSize = infoShuttle.userHeaderNames.size(); k < kSize; k++) {
            headerName = (String) infoShuttle.userHeaderNames.get(k);
            // See #986 (Multiples cookies don't work with some proxies)
            if (headerName.toLowerCase().equals("cookie")) {
                Engine.logEngine.debug("Cookie header ignored");
            } else {
                headerValue = (String) infoShuttle.userHeaderValues.get(k);
                method.setRequestHeader(headerName, headerValue);
                Engine.logEngine.debug(headerName + "=" + headerValue);
            }
        }
        // Getting the result
        executeMethod(method, connector, resourceUrl, infoShuttle);
        result = method.getResponseBody();
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return result;
}
Also used : Context(com.twinsoft.convertigo.engine.Context) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HostConfiguration(org.apache.commons.httpclient.HostConfiguration) CertificateManager(com.twinsoft.convertigo.engine.CertificateManager) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) URL(java.net.URL) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) GetMethod(org.apache.commons.httpclient.methods.GetMethod) AuthScope(org.apache.commons.httpclient.auth.AuthScope) Protocol(org.apache.commons.httpclient.protocol.Protocol)

Aggregations

CertificateManager (com.twinsoft.convertigo.engine.CertificateManager)6 HostConfiguration (org.apache.commons.httpclient.HostConfiguration)3 Context (com.twinsoft.convertigo.engine.Context)2 EngineException (com.twinsoft.convertigo.engine.EngineException)2 IOException (java.io.IOException)2 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)2 AuthScope (org.apache.commons.httpclient.auth.AuthScope)2 XMLVector (com.twinsoft.convertigo.beans.common.XMLVector)1 HttpConnector (com.twinsoft.convertigo.beans.connectors.HttpConnector)1 ProxyHttpConnector (com.twinsoft.convertigo.beans.connectors.ProxyHttpConnector)1 Project (com.twinsoft.convertigo.beans.core.Project)1 SiteClipperScreenClass (com.twinsoft.convertigo.beans.screenclasses.SiteClipperScreenClass)1 AbstractBiller (com.twinsoft.convertigo.engine.AbstractBiller)1 DomainsFilterHelper (com.twinsoft.convertigo.engine.helpers.DomainsFilterHelper)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1