Example usage for org.apache.commons.httpclient URI getHost

List of usage examples for org.apache.commons.httpclient URI getHost

Introduction

In this page you can find the example usage for org.apache.commons.httpclient URI getHost.

Prototype

public String getHost() throws URIException 

Source Link

Document

Get the host.

Usage

From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java

public static void configure(HttpClient client, URI targetURI, Element authPart, HttpParams params)
        throws URIException {
    if (log.isDebugEnabled())
        log.debug("Configuring http client...");

    /* Do not forget to wire params so that endpoint properties are passed around
       Down the road, when the request will be executed, the hierarchy of parameters will be the following:
     (-> means "is parent of")//from w ww. ja v a  2s . c  o m
     default params -> params from endpoint properties -> HttpClient -> HostConfig -> Method
       This wiring is done by HttpClient.
    */
    client.getParams().setDefaults(params);

    // Here we make sure HttpClient will not handle the default headers.
    // Actually HttpClient *appends* default headers while we want them to be ignored if the process assign them
    client.getParams().setParameter(HostParams.DEFAULT_HEADERS, Collections.EMPTY_LIST);

    // proxy configuration
    if (ProxyConf.isProxyEnabled(params, targetURI.getHost())) {
        if (log.isDebugEnabled())
            log.debug("ProxyConf");
        ProxyConf.configure(client.getHostConfiguration(), client.getState(),
                (HttpTransportProperties.ProxyProperties) params
                        .getParameter(Properties.PROP_HTTP_PROXY_PREFIX));
    }

    // security
    // ...

    // authentication
    /*
    We're expecting the following element:
    <xs:complexType name="credentialType">
    <xs:attribute name="scheme" type="xs:string" default="server-decide" />
    <xs:attribute name="username" type="xs:string" />
    <xs:attribute name="password" type="xs:string" />
    </xs:complexType>
    <xs:element type="rest_connector:credentialType" name="credentials" />
     */
    if (authPart != null) {
        // the part must be defined with an element, so take the fist child
        Element credentialsElement = DOMUtils.getFirstChildElement(authPart);
        if (credentialsElement != null && credentialsElement.getAttributes().getLength() != 0) {
            String scheme = DOMUtils.getAttribute(credentialsElement, "scheme");
            String username = DOMUtils.getAttribute(credentialsElement, "username");
            String password = DOMUtils.getAttribute(credentialsElement, "password");

            if (scheme != null && !"server-decides".equalsIgnoreCase(scheme)
                    && !"basic".equalsIgnoreCase(scheme) && !"digest".equalsIgnoreCase(scheme)) {
                throw new IllegalArgumentException("Unknown Authentication scheme: [" + scheme
                        + "] Accepted values are: Basic, Digest, Server-Decides");
            } else {
                if (log.isDebugEnabled())
                    log.debug("credentials provided: scheme=" + scheme + " user=" + username
                            + " password=********");
                client.getState().setCredentials(
                        new AuthScope(targetURI.getHost(), targetURI.getPort(), AuthScope.ANY_REALM, scheme),
                        new UsernamePasswordCredentials(username, password));
                // save one round trip if basic
                client.getParams().setAuthenticationPreemptive("basic".equalsIgnoreCase(scheme));
            }
        }
    }
}

From source file:org.apache.servicemix.http.processors.ProviderProcessor.java

private HostConfiguration getHostConfiguration(String locationURI, MessageExchange exchange,
        NormalizedMessage message) throws Exception {
    HostConfiguration host;/* w w w.ja  v  a 2s . c o  m*/
    URI uri = new URI(locationURI, false);
    if (uri.getScheme().equals("https")) {
        synchronized (this) {
            if (protocol == null) {
                ProtocolSocketFactory sf = new CommonsHttpSSLSocketFactory(endpoint.getSsl(),
                        KeystoreManager.Proxy.create(endpoint.getKeystoreManager()));
                protocol = new Protocol("https", sf, 443);
            }
        }
        HttpHost httphost = new HttpHost(uri.getHost(), uri.getPort(), protocol);
        host = new HostConfiguration();
        host.setHost(httphost);
    } else {
        host = new HostConfiguration();
        host.setHost(uri.getHost(), uri.getPort());
    }
    if (endpoint.getProxy() != null) {
        if ((endpoint.getProxy().getProxyHost() != null) && (endpoint.getProxy().getProxyPort() != 0)) {
            host.setProxy(endpoint.getProxy().getProxyHost(), endpoint.getProxy().getProxyPort());
        }
        if (endpoint.getProxy().getProxyCredentials() != null) {
            endpoint.getProxy().getProxyCredentials().applyProxyCredentials(getClient(), exchange, message);
        }
    } else if ((getConfiguration().getProxyHost() != null) && (getConfiguration().getProxyPort() != 0)) {
        host.setProxy(getConfiguration().getProxyHost(), getConfiguration().getProxyPort());
    }
    //host.getParams().setLongParameter(HttpConnectionParams.CONNECTION_TIMEOUT, getClient().getParams().getSoTimeout());
    return host;
}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

/**
 * @param idp//from ww w  .  j a v a2 s . com
 * @param query
 * @throws URIException
 * @throws HttpException
 * @throws IOException
 * @throws AuthException
 * @throws RemoteException
 * @throws ServiceException
 */
private URI processIdPSSO(IdentityProvider idp, URI spResponseURI)
        throws URIException, HttpException, IOException, AuthException, RemoteException, ServiceException {
    String idpSSOURL = idp.getUrl();
    LOG.debug("IdP SSO URL: " + idpSSOURL);
    String spResponseURL = spResponseURI.getEscapedURI();
    LOG.debug("spResponseURL=" + spResponseURL);
    // check if the spResponseURL is not already the IdP SSO url
    if (spResponseURL.startsWith(idpSSOURL)) {
        idpSSOURL = spResponseURL;
    } else {
        // if not, build it
        // BUG FIX: Shib SP 2.0 send the ?service=... in the query
        String query = spResponseURI.getEscapedQuery();
        LOG.debug("IdP SSO Query: " + query);
        if (query != null) {
            if (query.startsWith("service=")) {
                int i = query.indexOf("shire");
                if (i > 0) {
                    query = query.substring(i);
                    LOG.debug(
                            "IdP SSO Query contains the 'service=...' part, cutting up to 'shire=': " + query);
                } else {
                    LOG.error(
                            "IdP SSO Query contains the 'service=' parameter, but not the 'shire=' parameter: "
                                    + query);
                    throw new RemoteException(
                            "IdP SSO Query contains the 'service=' parameter, but not the 'shire=' parameter: "
                                    + query);
                }
            }
            // getIdpSSOMethod.setQueryString(query);
            idpSSOURL += "?" + query;
        }
        LOG.debug("IdP SSO URL (with query): " + idpSSOURL);
    }
    // create HttpMethod
    GetMethod getIdpSSOMethod = new GetMethod(idpSSOURL);

    URI idpSSOURI = getIdpSSOMethod.getURI();
    // set credential for basic or ntlm
    int authType = idp.getAuthType();
    LOG.debug("IdP authType: " + idp.getAuthTypeName());
    if (authType == IdentityProvider.SSO_AUTHTYPE_BASIC || authType == IdentityProvider.SSO_AUTHTYPE_NTLM) {
        // enable BASIC or NTLM authN
        AuthScope scope = new AuthScope(idpSSOURI.getHost(), idpSSOURI.getPort(), idp.getAuthRealm());
        LOG.info("Enable " + idp.getAuthTypeName() + " authentication: " + credentials_ + ", scope: " + scope);
        httpClient_.getState().setCredentials(scope, credentials_);
        getIdpSSOMethod.setDoAuthentication(true);
    }

    // execute the method
    LOG.info("GET IdpSSOMethod: " + idpSSOURI);
    int idpSSOResponseStatus = executeMethod(getIdpSSOMethod);
    String idpSSOResponseStatusLine = getIdpSSOMethod.getStatusLine().toString();
    LOG.debug(idpSSOResponseStatusLine);

    URI idpSSOResponseURI = getIdpSSOMethod.getURI();
    LOG.debug("idpSSOResponseURI=" + idpSSOResponseURI);
    String idpSSOResponseQuery = idpSSOResponseURI.getEscapedQuery();
    LOG.debug("idpSSOResponseQuery=" + idpSSOResponseQuery);

    // XXX
    dumpHttpClientCookies();

    LOG.debug("idpSSOResponseStatus=" + idpSSOResponseStatus);
    // BASIC or NTLM response handling
    if (idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_BASIC
            || idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_NTLM) {
        // !200 and same URL as before: if BASIC or NTLM failed on IdP

        LOG.debug("idpSSOURI=" + idpSSOURI);
        LOG.debug("idpSSOResponseURI=" + idpSSOResponseURI);

        if (idpSSOResponseStatus != 200 && idpSSOResponseURI.equals(idpSSOURI)) {

            LOG.trace("getIdpSSOMethod.releaseConnection()");
            getIdpSSOMethod.releaseConnection();

            LOG.error("BASIC or NTLM authentication was required for " + idpSSOURL);

            throw new AuthException(
                    idp.getAuthTypeName() + " authentication failed: " + idpSSOResponseStatusLine + " URL: "
                            + idpSSOResponseURI + " Credentials: " + this.credentials_);
        } else {
            // SAML/Artifact: idpSSOResponseURI is already SP login and the
            // XML <SLCSLoginResponse> is already there
            // XXX: resend to same IdP SSO page once again
            LOG.info("IdP BASIC or NTLM authN: resend again to the same IdP SSO URI: " + idpSSOURL);
            idpSSOResponseURI = new URI(idpSSOURL, false);
        }

    }
    // CAS sends 200 + Cookies and the login form directly
    else if (idpSSOResponseStatus == 200 && (idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_CAS
            || idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_FORM)) {
        LOG.debug("Process " + idp.getAuthTypeName() + " login form...");
        // process CAS login form
        InputStream idpLoginForm = getIdpSSOMethod.getResponseBodyAsStream();
        LOG.debug("idpSSOURI Query=" + idpSSOURI.getQuery());
        idpSSOResponseURI = processIdPLoginForm(idp, idpSSOResponseURI, idpSSOURI.getQuery(), idpLoginForm);
        LOG.debug(idp.getAuthTypeName() + " idpSSOResponseURI=" + idpSSOResponseURI);
    }
    // FIXME: ETHZ use a new PubCookie
    // PUBCOOKIE sends 200 + onload form with hidden fields to post
    else if (idpSSOResponseStatus == 200 && idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_PUBCOOKIE) {

        // parse <form> and extract hidden fields, then post
        PostMethod postPubcookieFormMethod = null;
        InputStream pubcookieFormStream = getIdpSSOMethod.getResponseBodyAsStream();
        Source source = new Source(pubcookieFormStream);
        List<Element> forms = source.findAllElements(Tag.FORM);
        for (Element form : forms) {
            String formAction = form.getAttributeValue("ACTION");
            LOG.debug("PubCookie form action=" + formAction);
            if (!idp.getAuthUrl().equalsIgnoreCase(formAction)) {
                // TODO: ERROR
                throw new RemoteException(
                        "form action: " + formAction + " doesn't match IdP authN url: " + idp.getAuthUrl());
            }
            // create PubCookie POST
            postPubcookieFormMethod = new PostMethod(formAction);

            // add all HIDDEN fields to POST
            List<FormControl> formControls = form.findFormControls();
            for (FormControl control : formControls) {
                FormControlType type = control.getFormControlType();
                if (type.equals(FormControlType.HIDDEN)) {
                    String name = control.getName();
                    Collection<String> values = control.getValues();
                    for (String value : values) {
                        LOG.debug("add hidden: " + name + "=" + value);
                        // add all hidden fields
                        postPubcookieFormMethod.addParameter(name, value);
                    }
                }
            }

        } // for all forms

        LOG.trace("getIdpSSOMethod.releaseConnection()");
        getIdpSSOMethod.releaseConnection();

        if (postPubcookieFormMethod == null) {
            // ERROR
            LOG.error("PubCookie form not found");
            throw new RemoteException("PubCookie form not found");
        }

        //
        LOG.debug("POST " + postPubcookieFormMethod.getURI());
        int postPubcookieFormStatus = executeMethod(postPubcookieFormMethod);
        LOG.debug(postPubcookieFormMethod.getStatusLine());

        // XXX
        dumpHttpClientCookies();

        // process pubcookie login form
        InputStream loginFormStream = postPubcookieFormMethod.getResponseBodyAsStream();
        idpSSOResponseURI = processIdPLoginForm(idp, idpSSOResponseURI, idpSSOURI.getQuery(), loginFormStream);
        LOG.debug("Pubcookie idpSSOResponseURI=" + idpSSOResponseURI);

        LOG.trace("postPubcookieFormMethod.releaseConnection()");
        postPubcookieFormMethod.releaseConnection();

    } else {
        // error handling
        InputStream htmlStream = getIdpSSOMethod.getResponseBodyAsStream();
        String htmlBody = inputStreamToString(htmlStream);
        LOG.error("Unexpected IdP SSO reponse: URL: " + idpSSOResponseURI + " Status: "
                + idpSSOResponseStatusLine + " AuthType: " + idp.getAuthTypeName() + " HTML:\n" + htmlBody);
        LOG.debug("getIdpSSOMethod.releaseConnection()");
        getIdpSSOMethod.releaseConnection();
        throw new RemoteException("Unexprected IdP SSO reponse: URL: " + idpSSOResponseURI + " Status: "
                + idpSSOResponseStatusLine + ". Please see the log file.");
    }

    LOG.debug("getIdpSSOMethod.releaseConnection()");
    getIdpSSOMethod.releaseConnection();

    return idpSSOResponseURI;

}

From source file:org.mule.transport.http.MuleHostConfiguration.java

@Override
public synchronized void setHost(URI uri) {
    try {// w  w  w .  ja v  a 2  s  .c om
        Protocol original = getProtocol();

        if (uri.getScheme().equals(original.getScheme())) {
            Protocol newProtocol = new Protocol(uri.getScheme(), original.getSocketFactory(),
                    original.getDefaultPort());

            super.setHost(uri.getHost(), uri.getPort(), newProtocol);
        } else {
            Protocol protoByName = Protocol.getProtocol(uri.getScheme());
            super.setHost(uri.getHost(), uri.getPort(), protoByName);
        }
    } catch (URIException uriException) {
        throw new IllegalArgumentException(uriException);
    }
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Checks if the given client files exist on the server and internally stores duplications.<p>
 * //from w w  w  .j a v  a2 s.co  m
 * Comparison is made by cutting the current directory of the file chooser from the path of the given files. 
 * The server files (VFS files) to compare to are found by the current session of the user which finds the correct site and 
 * the knowledge about the current directory. File translation rules are taken into account on the server. <p>
 * 
 * @param files the local files to check if they exist in the VFS 
 * 
 * @return one of {@link ModalDialog#ERROR_OPTION} , {@link ModalDialog#CANCEL_OPTION}, {@link ModalDialog#APPROVE_OPTION}. 
 */
int checkServerOverwrites(File[] files) {

    m_action = m_actionOverwriteCheck;
    repaint();
    int rtv = ModalDialog.ERROR_OPTION;
    // collect files
    List fileNames = new ArrayList();
    for (int i = 0; i < files.length; i++) {
        getRelativeFilePaths(files[i], fileNames);
    }

    StringBuffer uploadFiles = new StringBuffer();
    Iterator it = fileNames.iterator();
    // Http post header is limited, therefore only a ceratain amount of files may be checked 
    // for server overwrites. Solution is: multiple requests. 
    int count = 0;
    List duplications;
    // request to server
    HttpClient client = new HttpClient();
    this.m_overwrites = new ArrayList();
    try {
        while (it.hasNext()) {
            count++;
            uploadFiles.append(((String) it.next())).append('\n');

            if (((count % 40) == 0) || (!it.hasNext())) {
                // files to upload:
                PostMethod post = new PostMethod(m_targetUrl);
                Header postHeader = new Header("uploadFiles",
                        URLEncoder.encode(uploadFiles.toString(), "utf-8"));
                post.addRequestHeader(postHeader);
                // upload folder in vfs: 
                Header header2 = new Header("uploadFolder",
                        URLEncoder.encode(getParameter("filelist"), "utf-8"));
                post.addRequestHeader(header2);

                // the action constant
                post.setParameter("action", DIALOG_CHECK_OVERWRITE);

                // add jsessionid query string
                String sessionId = getParameter("sessionId");
                String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
                post.setQueryString(query);
                post.addRequestHeader(C_JSESSIONID, sessionId);

                HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
                connectionParams.setConnectionTimeout(5000);

                // add the session cookie
                client.getState();
                client.getHostConfiguration().getHost();

                HttpState initialState = new HttpState();
                URI uri = new URI(m_targetUrl, false);
                Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
                initialState.addCookie(sessionCookie);
                client.setState(initialState);
                int status = client.executeMethod(post);

                if (status == HttpStatus.SC_OK) {
                    String response = post.getResponseBodyAsString();
                    duplications = parseDuplicateFiles(URLDecoder.decode(response, "utf-8"));
                    this.m_overwrites.addAll(duplications);

                } else {
                    // continue without overwrite check 
                    String error = m_errorLine1 + "\n" + post.getStatusLine();
                    System.err.println(error);
                }

                count = 0;
                uploadFiles = new StringBuffer();
            }

        }
        if (m_overwrites.size() > 0) {
            rtv = showDuplicationsDialog(m_overwrites);
        } else {
            rtv = ModalDialog.APPROVE_OPTION;
        }

    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

    return rtv;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Uploads the zipfile to the OpenCms.<p>
 * //from w  w w  .  j  a  v a  2  s  .  c o m
 * @param uploadFile the zipfile to upload
 */
private void uploadZipFile(File uploadFile) {

    m_action = m_actionOutputUpload;
    repaint();

    PostMethod post = new PostMethod(m_targetUrl);

    try {
        Part[] parts = new Part[5];
        parts[0] = new FilePart(uploadFile.getName(), uploadFile);
        parts[1] = new StringPart("action", "submitform");
        parts[2] = new StringPart("unzipfile", "true");
        parts[3] = new StringPart("uploadfolder", m_uploadFolder);
        parts[4] = new StringPart("clientfolder", m_fileSelector.getCurrentDirectory().getAbsolutePath());

        HttpMethodParams methodParams = post.getParams();
        methodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        MultipartRequestEntity request = new MultipartRequestEntity(parts, methodParams);
        post.setRequestEntity(request);

        // add jsessionid query string
        String sessionId = getParameter("sessionId");
        String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
        post.setQueryString(query);
        post.addRequestHeader(C_JSESSIONID, sessionId);

        HttpClient client = new HttpClient();
        HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
        connectionParams.setConnectionTimeout(5000);

        // add the session cookie
        client.getState();
        client.getHostConfiguration().getHost();

        HttpState initialState = new HttpState();
        URI uri = new URI(m_targetUrl, false);
        Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
        initialState.addCookie(sessionCookie);
        client.setState(initialState);

        // no execute the file upload
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_OK) {
            //return to the specified url and frame target
            getAppletContext().showDocument(new URL(m_redirectUrl), m_redirectTargetFrame);
        } else {
            // create the error text
            String error = m_errorLine1 + "\n" + post.getStatusLine();
            //JOptionPane.showMessageDialog(this, error, "Error!", JOptionPane.ERROR_MESSAGE);
            getAppletContext().showDocument(new URL(m_errorUrl + "?action=showerror&uploaderror=" + error),
                    "explorer_files");
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
        // finally delete the zipFile on the harddisc
        uploadFile.delete();
    }
}

From source file:org.openmrs.module.sync.server.ServerConnection.java

public static ConnectionResponse sendExportedData(String url, String username, String password, String content,
        boolean isResponse) {

    // Default response - default constructor instantiates contains error codes 
    ConnectionResponse syncResponse = new ConnectionResponse();

    HttpClient client = new HttpClient();

    url = url + SyncConstants.DATA_IMPORT_SERVLET;
    log.info("POST multipart request to " + url);

    if (url.startsWith("https")) {
        try {//  ww w  .j av  a2 s.c  o m
            if (Boolean.parseBoolean(Context.getAdministrationService()
                    .getGlobalProperty(SyncConstants.PROPERTY_ALLOW_SELFSIGNED_CERTS))) {

                // It is necessary to provide a relative url (from the host name and port to the right)
                String relativeUrl;

                URI uri = new URI(url, true);
                String host = uri.getHost();
                int port = uri.getPort();

                // URI.getPort() returns -1 if port is not explicitly set
                if (port <= 0) {
                    port = SyncConstants.DEFAULT_HTTPS_PORT;
                    relativeUrl = url.split(host, 2)[1];
                } else {
                    relativeUrl = url.split(host + ":" + port, 2)[1];
                }

                Protocol easyhttps = new Protocol("https",
                        (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), port);
                client.getHostConfiguration().setHost(host, port, easyhttps);

                url = relativeUrl;
            }
        } catch (IOException ioe) {
            log.error("Unable to configure SSL to accept self-signed certificates");
        } catch (GeneralSecurityException e) {
            log.error("Unable to configure SSL to accept self-signed certificates");
        }
    }

    PostMethod method = new PostMethod(url);

    try {

        boolean useCompression = Boolean.parseBoolean(Context.getAdministrationService()
                .getGlobalProperty(SyncConstants.PROPERTY_ENABLE_COMPRESSION, "true"));

        log.info("use compression: " + useCompression);
        // Compress content
        ConnectionRequest request = new ConnectionRequest(content, useCompression);

        // Create up multipart request
        Part[] parts = {
                new FilePart("syncDataFile", new ByteArrayPartSource("syncDataFile", request.getBytes())),
                new StringPart("username", username), new StringPart("password", password),
                new StringPart("compressed", String.valueOf(useCompression)),
                new StringPart("isResponse", String.valueOf(isResponse)),
                new StringPart("checksum", String.valueOf(request.getChecksum())) };

        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        // Open a connection to the server and post the data
        client.getHttpConnectionManager().getParams().setSoTimeout(ServerConnection.getTimeout().intValue());
        client.getHttpConnectionManager().getParams()
                .setConnectionTimeout(ServerConnection.getTimeout().intValue());
        int status = client.executeMethod(method);

        // As long as the response is OK (200)
        if (status == HttpStatus.SC_OK) {
            // Decompress the response from the server
            //log.info("Response from server:" + method.getResponseBodyAsString());

            // Check to see if the child/parent sent back a compressed response
            Header compressionHeader = method.getResponseHeader("Enable-Compression");
            useCompression = (compressionHeader != null) ? new Boolean(compressionHeader.getValue()) : false;
            log.info("Response header Enable-Compression: " + useCompression);

            // Decompress the data received (if compression is enabled)
            syncResponse = new ConnectionResponse(method.getResponseBodyAsStream(), useCompression);

            // Now we want to validate the checksum
            Header checksumHeader = method.getResponseHeader("Content-Checksum");
            long checksumReceived = (checksumHeader != null) ? new Long(checksumHeader.getValue()) : 0;
            log.info("Response header Content-Checksum: " + checksumReceived);

            log.info("checksum value received in response header: " + checksumReceived);
            log.info("checksum of payload: " + syncResponse.getChecksum());

            // TODO Need to figure out what to do with this response
            if (checksumReceived > 0 && (checksumReceived != syncResponse.getChecksum())) {
                log.error("ERROR: FAILED CHECKSUM!");
                syncResponse.setState(ServerConnectionState.CONNECTION_FAILED); // contains error message           
            }
        }
        // if there's an error response code we should set the tran
        else {
            // HTTP error response code
            syncResponse
                    .setResponsePayload("HTTP " + status + " Error Code: " + method.getResponseBodyAsString());
            syncResponse.setState(ServerConnectionState.CONNECTION_FAILED); // contains error message 
        }

    } catch (MalformedURLException mue) {
        log.error("Malformed URL " + url, mue);
        syncResponse.setState(ServerConnectionState.MALFORMED_URL);
    } catch (Exception e) { // all other exceptions really just mean that the connection was bad
        log.error("Error occurred while sending/receiving data ", e);
        syncResponse.setState(ServerConnectionState.CONNECTION_FAILED);
    } finally {
        method.releaseConnection();
    }
    return syncResponse;
}

From source file:org.parosproxy.paros.core.spider.Spider.java

public synchronized void addSeed(HttpMessage msg) {
    URI uri = msg.getRequestHeader().getURI();
    String hostName = null;//from  ww  w .j  av a2s  .  c om
    int port = 80;

    try {
        log.info("seeding " + msg.getRequestHeader().getURI().toString());

        hostName = uri.getHost();
        port = uri.getPort();
        if (port > 0) {
            hostName = hostName + ":" + Integer.toString(port);
        }

        seedHostNameSet.add(hostName);
        addQueue(msg, 0);

    } catch (URIException e) {
        e.printStackTrace();
    }

}

From source file:org.parosproxy.paros.core.spider.Spider.java

public boolean isSeedScope(URI uri) {
    boolean result = false;

    String hostName = null;/*from www  . j a v a2 s. com*/
    try {
        hostName = uri.getHost();
        if (uri.getPort() > 0) {
            hostName = hostName + ":" + uri.getPort();
        }

        String[] hostList = (String[]) seedHostNameSet.toArray(new String[0]);
        for (int i = 0; i < hostList.length; i++) {
            if (hostList[i] == null)
                continue;
            if (hostName.endsWith(hostList[i])) {
                return true;
            }
        }

    } catch (URIException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:org.parosproxy.paros.core.spider.Spider.java

/**
 * Check if URL is to be neglected if: - not HTTP protocol - outside
 * host domain - irrelevant file suffix (eg gif, jpg) - visited before
 * URL queried by this method will be marked visited.
 * @throws URIException//from ww w .  j  a v  a 2  s. c om
 * 
 */
private boolean isNeglectFound(HttpMessage msg) throws URIException {
    boolean result = false;

    URI uri = msg.getRequestHeader().getURI();

    // check correct protocol
    if (!uri.getScheme().equalsIgnoreCase("HTTP") && !uri.getScheme().equalsIgnoreCase("HTTPS")) {
        return true;
    }

    // compare if in seed's domain or inside session domain scope
    String hostName = uri.getHost().toUpperCase();
    if (!isSeedScope(uri)) {
        if (!getSpiderParam().isInScope(hostName)) {
            return true;
        }
    }

    return false;

}