Example usage for org.apache.commons.httpclient HttpStatus SC_OK

List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_OK.

Prototype

int SC_OK

To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.

Click Source Link

Document

<tt>200 OK</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:davmail.caldav.TestCaldav.java

public void testGetOtherUserCalendar() throws IOException {
    Settings.setLoggingLevel("httpclient.wire", Level.DEBUG);
    PropFindMethod method = new PropFindMethod(
            "/principals/users/" + Settings.getProperty("davmail.to") + "/calendar/");
    httpClient.executeMethod(method);//from  w w w.  j a v a2s  .c  o  m
    assertEquals(HttpStatus.SC_OK, method.getStatusCode());
}

From source file:net.sf.ufsc.http.HttpFile.java

protected void execute(HttpMethod method) throws java.io.IOException {
    method.setFollowRedirects(true);// ww w  .  ja v a  2  s.c o m
    method.setDoAuthentication(true);

    int status = this.client.executeMethod(method);

    if (status != HttpStatus.SC_OK) {
        throw new java.io.IOException(method.getStatusText());
    }
}

From source file:com.itude.mobile.mobbl.core.services.datamanager.handlers.MBRESTServiceDataHandler.java

@Override
public MBDocument doLoadDocument(String documentName, MBDocument args) {
    MBEndPointDefinition endPoint = getEndPointForDocument(documentName);

    if (endPoint != null) {
        LOGGER.debug(//from www .  ja  v a 2 s.c  o m
                "MBRESTServiceDataHandler:loadDocument " + documentName + " from " + endPoint.getEndPointUri());

        String dataString = null;
        MBDocument responseDoc = null;
        String body = args.getValueForPath("/*[0]").toString();
        try {
            HttpPost httpPost = new HttpPost(endPoint.getEndPointUri());
            // Content-Type must be set because otherwise the MidletCommandProcessor servlet cannot read the XML
            httpPost.setHeader("Content-Type", "text/xml");
            if (body != null) {
                httpPost.setEntity(new StringEntity(body));
            }

            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            int timeoutConnection = DEFAULT_TIMEOUTCONNECTION;
            // Set the default socket timeout (SO_TIMEOUT) 
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = DEFAULT_TIMEOUT_SOCKET;

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", 8080, PlainSocketFactory.getSocketFactory()));
            ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(registry, timeoutConnection,
                    TimeUnit.MILLISECONDS);
            cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
            cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);

            HttpClient httpClient = new DefaultHttpClient(cm, httpParameters);
            if (endPoint.getTimeout() > 0) {
                timeoutSocket = endPoint.getTimeout() * 1000;
                timeoutConnection = endPoint.getTimeout() * 1000;
            }
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            if (ALLOW_ANY_CERTIFICATE)
                allowAnyCertificate(httpClient);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            int responseCode = httpResponse.getStatusLine().getStatusCode();
            String responseMessage = httpResponse.getStatusLine().getReasonPhrase();
            if (responseCode != HttpStatus.SC_OK) {
                LOGGER.error("MBRESTServiceDataHandler.loadDocument: Received HTTP responseCode=" + responseCode
                        + ": " + responseMessage);
            }

            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                InputStream inStream = entity.getContent();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int i = inStream.read(buffer);
                while (i > -1) {
                    bos.write(buffer, 0, i);
                    i = inStream.read(buffer);
                }
                inStream.close();
                dataString = new String(bos.toByteArray());
            }

            boolean serverErrorHandled = false;

            for (MBResultListenerDefinition lsnr : endPoint.getResultListeners()) {
                if (lsnr.matches(dataString)) {
                    MBResultListener rl = _applicationFactory.createResultListener(lsnr.getName());
                    rl.handleResult(dataString, args, lsnr);
                    serverErrorHandled = true;
                }
            }

            /*       if (delegate.err != nil) {
                       String errorMessage = null;
                       //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                       Log.w("MOBBL","An error ("+errorMessage+") occured while accessing endpoint "+endPoint.getEndPointUri());
                       throw new NetworkErrorException(MBLocalizationService.getInstance().textForKey((errorMessage);
                   }
                   //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            */
            if (dataString != null) {
                byte[] data = dataString.getBytes();
                responseDoc = MBDocumentFactory.getInstance().getDocumentWithData(data,
                        getDocumentFactoryType(),
                        MBMetadataService.getInstance().getDefinitionForDocumentName(documentName));
            }
            // if the response document is empty and unhandled by endpoint listeners let the user know there is a problem
            if (!serverErrorHandled && responseDoc == null) {
                String msg = MBLocalizationService.getInstance()
                        .getTextForKey("The server returned an error. Please try again later");
                //                if(delegate.err != nil) {
                //                    msg = [NSString stringWithFormat:@"%@ %@: %@", msg, delegate.err.domain, delegate.err.code];
                //                }
                throw new MBServerErrorException(msg);
            }
        }
        // TODO: clean up exception handling
        catch (Exception e) {
            // debug in stead of info because it can contain a password
            LOGGER.debug("Sent xml:\n" + body);
            LOGGER.info("Received:\n" + dataString);
            if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            else
                throw new ItudeRuntimeException(e);
        }
        return responseDoc;
    } else {
        LOGGER.warn("No endpoint defined for document name " + documentName);
        return null;
    }
}

From source file:com.dotcms.publisher.myTest.PushPublisher.java

@Override
public PublisherConfig process(final PublishStatus status) throws DotPublishingException {
    if (LicenseUtil.getLevel() < 200)
        throw new RuntimeException("need an enterprise licence to run this");

    PublishAuditHistory currentStatusHistory = null;
    try {//from ww  w.  j a v  a  2  s.c  om
        //Compressing bundle
        File bundleRoot = BundlerUtil.getBundleRoot(config);

        ArrayList<File> list = new ArrayList<File>(1);
        list.add(bundleRoot);
        File bundle = new File(
                bundleRoot + File.separator + ".." + File.separator + config.getId() + ".tar.gz");
        compressFiles(list, bundle, bundleRoot.getAbsolutePath());

        //Retriving enpoints and init client
        List<PublishingEndPoint> endpoints = ((PushPublisherConfig) config).getEndpoints();
        Map<String, List<PublishingEndPoint>> endpointsMap = new HashMap<String, List<PublishingEndPoint>>();
        List<PublishingEndPoint> buffer = null;
        //Organize the endpoints grouping them by groupId
        for (PublishingEndPoint pEndPoint : endpoints) {
            if (endpointsMap.get(pEndPoint.getGroupId()) == null)
                buffer = new ArrayList<PublishingEndPoint>();
            else
                buffer = endpointsMap.get(pEndPoint.getGroupId());

            buffer.add(pEndPoint);
            endpointsMap.put(pEndPoint.getGroupId(), buffer);
        }

        ClientConfig cc = new DefaultClientConfig();

        if (Config.getStringProperty("TRUSTSTORE_PATH") != null
                && !Config.getStringProperty("TRUSTSTORE_PATH").trim().equals(""))
            cc.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(tFactory.getHostnameVerifier(), tFactory.getSSLContext()));
        Client client = Client.create(cc);

        //Updating audit table
        currentStatusHistory = pubAuditAPI.getPublishAuditStatus(config.getId()).getStatusPojo();

        currentStatusHistory.setPublishStart(new Date());
        pubAuditAPI.updatePublishAuditStatus(config.getId(), PublishAuditStatus.Status.SENDING_TO_ENDPOINTS,
                currentStatusHistory);
        //Increment numTries
        currentStatusHistory.addNumTries();

        boolean hasError = false;
        int errorCounter = 0;

        for (String group : endpointsMap.keySet()) {
            List<PublishingEndPoint> groupList = endpointsMap.get(group);

            boolean sent = false;
            for (PublishingEndPoint endpoint : groupList) {
                EndpointDetail detail = new EndpointDetail();
                try {
                    FormDataMultiPart form = new FormDataMultiPart();
                    form.field("AUTH_TOKEN", retriveKeyString(
                            PublicEncryptionFactory.decryptString(endpoint.getAuthKey().toString())));
                    form.field("GROUP_ID", endpoint.getGroupId());
                    form.field("ENDPOINT_ID", endpoint.getId());
                    form.bodyPart(new FileDataBodyPart("bundle", bundle, MediaType.MULTIPART_FORM_DATA_TYPE));

                    //Sending bundle to endpoint
                    WebResource resource = client.resource(endpoint.toURL() + "/api/bundlePublisher/publish");

                    ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA)
                            .post(ClientResponse.class, form);

                    if (response.getClientResponseStatus().getStatusCode() == HttpStatus.SC_OK) {
                        detail.setStatus(PublishAuditStatus.Status.BUNDLE_SENT_SUCCESSFULLY.getCode());
                        detail.setInfo("Everything ok");
                        sent = true;
                    } else {
                        detail.setStatus(PublishAuditStatus.Status.FAILED_TO_SENT.getCode());
                        detail.setInfo("Returned " + response.getClientResponseStatus().getStatusCode()
                                + " status code " + "for the endpoint " + endpoint.getId() + "with address "
                                + endpoint.getAddress());
                    }
                } catch (Exception e) {
                    hasError = true;
                    detail.setStatus(PublishAuditStatus.Status.FAILED_TO_SENT.getCode());

                    String error = "An error occured for the endpoint " + endpoint.getId() + " with address "
                            + endpoint.getAddress() + ".  Error: " + e.getMessage();

                    detail.setInfo(error);

                    Logger.error(this.getClass(), error);
                }

                currentStatusHistory.addOrUpdateEndpoint(group, endpoint.getId(), detail);

                if (sent)
                    break;
            }

            if (!sent) {
                hasError = true;
                errorCounter++;
            }
        }

        if (!hasError) {
            //Updating audit table
            currentStatusHistory.setPublishEnd(new Date());
            pubAuditAPI.updatePublishAuditStatus(config.getId(),
                    PublishAuditStatus.Status.BUNDLE_SENT_SUCCESSFULLY, currentStatusHistory);

            //Deleting queue records
            //pubAPI.deleteElementsFromPublishQueueTable(config.getId());
        } else {
            if (errorCounter == endpointsMap.size()) {
                pubAuditAPI.updatePublishAuditStatus(config.getId(),
                        PublishAuditStatus.Status.FAILED_TO_SEND_TO_ALL_GROUPS, currentStatusHistory);
            } else {
                pubAuditAPI.updatePublishAuditStatus(config.getId(),
                        PublishAuditStatus.Status.FAILED_TO_SEND_TO_SOME_GROUPS, currentStatusHistory);
            }
        }

        return config;

    } catch (Exception e) {
        //Updating audit table
        try {
            pubAuditAPI.updatePublishAuditStatus(config.getId(), PublishAuditStatus.Status.FAILED_TO_PUBLISH,
                    currentStatusHistory);
        } catch (DotPublisherException e1) {
            throw new DotPublishingException(e.getMessage());
        }

        Logger.error(this.getClass(), e.getMessage(), e);
        throw new DotPublishingException(e.getMessage());

    }
}

From source file:com.rallydev.integration.build.rest.RallyRestServiceTest.java

public void testRallyRestServiceBuildSuccessWithProxyAndAuth() throws Exception {
    MockControl httpStateMockControl1;/*from  ww w  . j  a  v a2s. c  o m*/
    HttpState httpStateMock1;

    httpStateMockControl1 = MockClassControl.createControl(HttpState.class);
    httpStateMock1 = (HttpState) httpStateMockControl1.getMock();
    httpStateMock1.setCredentials(new AuthScope("host", -1, null),
            new UsernamePasswordCredentials("user", "password"));
    httpStateMock1.setProxyCredentials(new AuthScope("proxyserver.mycompany.com", 3128, null),
            new UsernamePasswordCredentials("user@rallydev.com", "password"));
    httpStateMockControl1.replay();

    String xml = readFile(BUILD_SUCCESS_FILE);
    httpClientMockControl.expectAndReturn(httpClientMock.getHostConfiguration(), hostConfigurationMock);
    hostConfigurationMock.setProxy("proxyserver.mycompany.com", 3128);

    httpClientMockControl.expectAndReturn(httpClientMock.getState(), httpStateMock1);

    httpClientMockControl.expectAndReturn(httpClientMock.executeMethod(postMethodMock), HttpStatus.SC_OK);
    postMethodMockControl.expectAndReturn(postMethodMock.getResponseBodyAsStream(),
            readFileAsStream(BUILD_SUCCESS_RESPONSE_FILE));
    postMethodMock.releaseConnection();

    httpClientMockControl.replay();
    postMethodMockControl.replay();
    hostConfigurationMockControl.replay();

    rallyRestService.setProxyInfo("proxyserver.mycompany.com", 3128, "user@rallydev.com", "password");
    String response = rallyRestService.doCreate(xml, httpClientMock, postMethodMock);
    assertEquals(readFile(BUILD_SUCCESS_RESPONSE_FILE), response);
    httpStateMockControl.verify();
    hostConfigurationMockControl.verify();
    verify();
}

From source file:it.geosolutions.geonetwork.op.GNMetadataInsert.java

/**
 * Insert a metadata in GN.<br/>/*w  ww . j a va 2s . c o m*/
 * 
 * <ul>
 * <li>Url: <tt>http://<i>server</i>:<i>port</i>/geonetwork/srv/en/metadata.insert</tt></li>
 * <li>Mime-type: <tt>application/xml</tt></li>
 * <li>Post request: <pre>{@code 
 * <?xml version="1.0" encoding="UTF-8"?>
 * <request>
 *    <group>2</group>
 *    <category>_none_</category>
 *    <styleSheet>_none_</styleSheet>
 *    <data><![CDATA[
 *       <gmd:MD_Metadata xmlns:gmd="http://www.isotc211.org/2005/gmd"
 *                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 *       ...
 *          </gmd:DQ_DataQuality>
 *         </gmd:dataQualityInfo>
 *       </gmd:MD_Metadata>]]>
 *    </data>
 * </request> }</pre></li>
 * </ul>
 * 
 * @return the id of the metadata created in geonetwork
 * 
 * @see <a href="http://geonetwork-opensource.org/latest/developers/xml_services/metadata_xml_services.html#insert-metadata-metadata-insert" >GeoNetwork documentation about inserting metadata</a>
 */
private static long gnInsertMetadata(HTTPUtils connection, String baseURL, final Element gnRequest)
        throws GNLibException, GNServerException {

    String serviceURL = baseURL + "/srv/en/xml.metadata.insert";
    String res = gnPut(connection, serviceURL, gnRequest);
    if (connection.getLastHttpStatus() != HttpStatus.SC_OK)
        throw new GNServerException(
                "Error inserting metadata in GeoNetwork (HTTP code " + connection.getLastHttpStatus() + ")");

    Element rese = parse(res);
    try {
        return Long.parseLong(rese.getChildText("id"));
    } catch (Exception e) {
        LOGGER.error("Error parsing metadata id from: " + res);
        throw new GNLibException("Error parsing metadata id", e);
    }
}

From source file:com.bluexml.side.framework.alfresco.webscriptExtension.SiteScriptExtension.java

/**
 * Method to create a site/*w  w w .  j a v  a 2s.  c  om*/
 * The site is created through an http post call using a json structure as done by Share.
 * The json structure is of the form:
 * {
  * "visibility" : "PUBLIC",
  * "title" : "My Test Site100",
  * "shortName" : "mytestsite100",
  * "description" : "My Test Site created from command line 100",
  * "sitePreset" : "site-dashboard"
  * },
        
 * 
 * @param baseUrl           the base url 
 * @param alfrescoUsername    the alfresco user login to use to send request
 * @param alfrescoUsername    the alfresco password to use to send request
 * @param siteTitle         the site title
 * @param siteShortname      the mandatory site short name
 * @param siteDescription   the site description
 * @param siteVisibility   the site visibility
 * @param sitePreset      the site preset
 *            
 * @return nodeRef of the site; null if the site failed to be created; in the javascript, use site.getSite(siteShortname) to get the site.
 */
public NodeRef createSite(String baseUrl, String alfrescoUsername, String alfrescoPwd, String siteTitle,
        String siteShortname, String siteDescription, String siteVisibility, String sitePreset) {
    if (logger.isDebugEnabled()) {
        logger.debug("Create site " + siteTitle + " - sitheShortname =" + siteShortname + " - siteDescription="
                + siteDescription);
        logger.debug("             - siteVisibility =" + siteVisibility + " - sitePreset=" + sitePreset);
        logger.debug("             - baseUrl =" + baseUrl + " - alfrescoUsername=" + alfrescoUsername
                + " - alfrescoPwd=" + alfrescoPwd);
    }
    NodeRef nodeRef = null;
    if (siteShortname != null) {
        SiteInfo siteInfo = siteService.getSite(siteShortname);
        if (siteInfo == null) {
            if (siteTitle == null)
                siteTitle = siteShortname;
            if (siteDescription == null)
                siteDescription = "";
            if (sitePreset == null)
                sitePreset = "site-dashboard";
            if (siteVisibility == null || !siteVisibility.equals(ScriptSiteService.PUBLIC_SITE)
                    || !siteVisibility.equals(ScriptSiteService.MODERATED_SITE)
                    || !siteVisibility.equals(ScriptSiteService.PRIVATE_SITE))
                siteVisibility = ScriptSiteService.PUBLIC_SITE;
            if (baseUrl == null)
                baseUrl = BASE_URL;

            // Create Apache HTTP Client to use for both calls: login and create-site
            HttpClient httpClient = new HttpClient();

            // Login to Share to get a JSESSIONID setup in HTTP Client
            String loginData = "username=" + alfrescoUsername + "&password=" + alfrescoPwd;
            makePostCall(httpClient, baseUrl + LOGIN_URL, loginData, CONTENT_TYPE_FORM,
                    "Login to Alfresco Share", HttpStatus.SC_MOVED_TEMPORARILY, alfrescoUsername);

            // create body request using site parameters
            JSONObject json = new JSONObject();
            try {
                json.put("visibility", siteVisibility);
                json.put("title", siteTitle);
                json.put("shortName", siteShortname);
                json.put("description", siteDescription);
                json.put("sitePreset", sitePreset);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // send create-site request
            makePostCall(httpClient, baseUrl + CREATE_SITE_URL, json.toString(), CONTENT_TYPE_JSON,
                    "Create site with name: " + siteShortname, HttpStatus.SC_OK, alfrescoUsername);

            siteInfo = siteService.getSite(siteShortname);
            if (siteInfo != null) {
                nodeRef = siteInfo.getNodeRef();
            } else {
                // Site already exists, cannot create it, continue with next one
                logger.warn("Site (" + siteShortname + ") has not been created !!! - Check log.");
            }
        } else {
            // Site already exists, cannot create it, continue with next one
            logger.warn("Site (" + siteShortname + ") already exists, cannot create it");
        }
    } else {
        // Site shortname is mandatory
        logger.warn("Site shortName parameter is mandatory, cannot create site without shortName");
    }
    return nodeRef;
}

From source file:com.tribune.uiautomation.testscripts.Photo.java

public Photo clonePhoto(String newNamespace, String newSlug) throws JSONException {
    checkValidStateForDelete();//from w  w  w .  j a va2  s. c o m
    Photo photo = null;

    PostMethod post = new PostMethod(constructCloneUrl(namespace, slug));

    try {
        setRequestHeaders(post);
        setParameters(post, newNamespace, newSlug);

        HttpClient client = new HttpClient();
        int status = client.executeMethod(post);

        log.debug("Photo Service create return status: " + post.getStatusLine());
        if (status == HttpStatus.SC_OK) {
            photo = new Photo();
            processResponse(photo, post.getResponseBodyAsStream());
            photo.setPersisted(true);
        }
    } catch (HttpException e) {
        log.fatal("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        log.fatal("Fatal transport error: " + e.getMessage(), e);
    } finally {
        // Release the connection.
        post.releaseConnection();
    }

    return photo;
}

From source file:com.buzzdavidson.spork.client.OWAClient.java

/**
 * Perform login to OWA server given configuration parameters and supplied user/password
 *
 * @param userName  user name for login//from  ww w. jav  a 2 s  . c o m
 * @param password password for login
 * @return true if successfully authenticated
 */
public boolean login(String userName, String password) {
    /**
     * Set NT credentials on client
     */
    Credentials cred;
    cred = new NTCredentials(userName, password, authHost, authDomain);
    client.getState().setCredentials(new AuthScope(authHost, AuthScope.ANY_PORT), cred);

    String authUrl = getBaseUrl() + loginPath;
    boolean retval = false;
    logger.info(String.format("Logging in to OWA using username [%s] at URL [%s] ", userName, authUrl));
    PostMethod post = new PostMethod(authUrl);
    post.setRequestHeader(PARAM_CONTENT_TYPE, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE);
    post.addParameter(PARAM_DEST, getBaseUrl() + docBasePath);
    post.addParameter(PARAM_UNAME, userName);
    post.addParameter(PARAM_PWD, password);
    post.addParameter(PARAM_FLAGS,
            publicComputer ? OWA_FLAG_VALUE_PUBLIC.toString() : OWA_FLAG_VALUE_PRIVATE.toString());

    int status = 0;
    try {
        status = client.executeMethod(post);
        if (logger.isDebugEnabled()) {
            logger.debug("Post returned status code " + status);
        }
    } catch (Exception ex) {
        logger.error("Got error posting to login url", ex);
    }

    if (status == HttpStatus.SC_OK) {
        // We shouldn't see this in normal operation... Evaluate whether this actually ever occurs.
        logger.info("Login succeeded (no redirect specified)");
        retval = true;
    } else if (status == HttpStatus.SC_MOVED_TEMPORARILY) {
        // We typically receive a redirect upon successful authentication; the target url is the user's inbox
        Header locationHeader = post.getResponseHeader(HEADER_LOCATION);
        if (locationHeader != null) {
            String mbxRoot = getMailboxRoot(locationHeader.getValue());
            if (mbxRoot == null || mbxRoot.length() < 1) {
                logger.info("Login failed - Check configuration and credentials.");
                retval = false;
            } else {
                owaRootUrl = mbxRoot;
                inboxAddress = owaRootUrl + "/" + FOLDER_NAME_INBOX; // TODO is this sufficient?
                logger.info("Login succeeded, redirect specified (redirecting to " + owaRootUrl + ")");
                retval = true;
            }
        }
    } else {
        logger.error("Login failed with error code " + status);
    }
    return retval;
}

From source file:ch.ksfx.web.services.spidering.http.HttpClientHelper.java

private HttpMethod executeMethod(HttpMethod httpMethod) {
    for (Header header : this.headers.getHeaders()) {
        httpMethod.setRequestHeader(header);
    }/*from ww w.  java  2s . c om*/

    httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new KsfxHttpRetryHandler(retryCount, retryDelay));

    try {
        int tryCount = 0;
        int statusCode;
        do {
            if (tryCount > 1) {
                httpMethod = createNewHttpMethod(httpMethod);
                try {
                    if (retryDelay == 0) {
                        retryDelay = DEFAULT_RETRY_DELAY;
                    }
                    Thread.sleep(retryDelay);
                } catch (InterruptedException e) {
                    logger.severe("InterruptedException");
                }
            }

            //PROXY Configuration
            /*
            if (torify) {
                    
            String proxyHost = "";
            Integer proxyPort = 0;
                    
            try {
                    proxyHost = SpiderConfiguration.getConfiguration().getString("torifyHost");
                    proxyPort = SpiderConfiguration.getConfiguration().getInt("torifyPort");
            } catch (Exception e) {
                logger.severe("Cannot get Proxy information");
            }
                    
            this.httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
            }
            */

            statusCode = this.httpClient.executeMethod(httpMethod);
            tryCount++;
        } while (!(statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_FORBIDDEN
                || statusCode == HttpStatus.SC_NOT_FOUND) && tryCount < retryCount);
        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("HTTP method failed: " + httpMethod.getStatusLine() + " - "
                    + httpMethod.getURI().toString());
        }
    } catch (HttpException e) {
        e.printStackTrace();
        httpMethod.abort();
        try {
            logger.log(Level.SEVERE, "Redirrex " + e.getClass(), e);
            if (e.getClass().equals(RedirectException.class)) {
                logger.log(Level.SEVERE, "Is real redirect exception", e);
                throw new RuntimeException("HttpRedirectException");
            }
            logger.log(Level.SEVERE, "HTTP protocol error for URL: " + httpMethod.getURI().toString(), e);
        } catch (URIException e1) {
            e.printStackTrace();
            logger.log(Level.SEVERE, "URI exception", e);
        }
        throw new RuntimeException("HttpException");
    } catch (IOException e) {
        try {
            e.printStackTrace();
            logger.log(Level.SEVERE, "HTTP transport error for URL: " + httpMethod.getURI().toString(), e);

        } catch (URIException e1) {
            e.printStackTrace();
            logger.log(Level.SEVERE, "URI exception", e);

        }
        throw new RuntimeException("IOException");
    }
    return httpMethod;
}