Example usage for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER.

Prototype

String RETRY_HANDLER

To view the source code for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER.

Click Source Link

Usage

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public SaxonDocument delete(String id)
        throws UnsupportedEncodingException, IOException, SaxonApiException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;//from   w  w  w.j a v a 2s  .  c  o  m

    String urlStr = this.solrHost + "/update?stream.body="
            + URLEncoder.encode("<delete><query>id:" + id + "</query></delete>") + "&commit=true";

    Log.debug("The " + id + " item is going to be deleted");
    // Create a method instance.
    method = new GetMethod(urlStr);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString());
    //Log.debug(solrResponse.getXMLDocumentString());

    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()",
                XPathConstants.STRING);
        throw new Exception(errorMessage);
    }

    return solrResponse;
}

From source file:br.org.acessobrasil.silvinha.util.versoes.AtualizadorDeVersoes.java

public boolean baixarVersao() {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair param = new NameValuePair("param", "update");
    method.setRequestBody(new NameValuePair[] { param });
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    JFrame down = new JFrame("Download");
    File downFile = null;/*  www.  j  a  v  a 2  s. c  om*/
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
        }
        Header header = method.getResponseHeader("Content-Disposition");
        String fileName = "silvinha.exe";
        if (header != null) {
            fileName = header.getValue().split("=")[1];
        }
        // Read the response body.
        is = method.getResponseBodyAsStream();
        down.pack();
        ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(down,
                TradAtualizadorDeVersoes.FAZ_DOWNLOAD_FILE + fileName, is);
        pmis.getProgressMonitor().setMinimum(0);
        pmis.getProgressMonitor().setMaximum((int) method.getResponseContentLength());
        downFile = new File(fileName);
        fos = new FileOutputStream(downFile);
        int c;
        while (((c = pmis.read()) != -1) && (!pmis.getProgressMonitor().isCanceled())) {
            fos.write(c);
        }
        fos.flush();
        fos.close();
        String msgOK = TradAtualizadorDeVersoes.DOWNLOAD_EXITO
                + TradAtualizadorDeVersoes.DESEJA_ATUALIZAR_EXECUTAR + TradAtualizadorDeVersoes.ARQUIVO_DE_NOME
                + fileName + TradAtualizadorDeVersoes.LOCALIZADO_NA + TradAtualizadorDeVersoes.PASTA_INSTALACAO
                + TradAtualizadorDeVersoes.APLICACAO_DEVE_SER_ENCERRADA
                + TradAtualizadorDeVersoes.DESEJA_CONTINUAR_ATUALIZACAO;
        if (JOptionPane.showConfirmDialog(null, msgOK, TradAtualizadorDeVersoes.ATUALIZACAO_DO_PROGRAMA,
                JOptionPane.YES_NO_OPTION) == 0) {
            return true;
        } else {
            return false;
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
        return false;
    } catch (InterruptedIOException iioe) {
        method.abort();
        String msg = GERAL.OP_CANCELADA_USUARIO + TradAtualizadorDeVersoes.DIRECIONADO_A_APLICACAO;
        JOptionPane.showMessageDialog(down, msg);
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException ioe) {
            method.releaseConnection();
            System.exit(0);
        }
        if (downFile != null && downFile.exists()) {
            downFile.delete();
        }
        return false;
        //         System.err.println("Fatal transport error: " + iioe.getMessage());
        //         iioe.printStackTrace();
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
        return false;
    } finally {
        //Release the connection.
        method.releaseConnection();
    }
}

From source file:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient.java

public static String getEngineComplianceVersion(String url)
        throws EngineUnavailableException, ServiceInvocationFailedException {
    String version;/* w  ww.j a  v  a2 s  . c o  m*/
    HttpClient client;
    PostMethod method;
    NameValuePair[] nameValuePairs;

    version = null;
    client = new HttpClient();
    method = new PostMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    nameValuePairs = new NameValuePair[] { new NameValuePair("infoType", "complianceVersion") }; //$NON-NLS-1$ //$NON-NLS-2$

    method.setRequestBody(nameValuePairs);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new ServiceInvocationFailedException(
                    Messages.getString("SpagoBITalendEngineClient.serviceFailed"), //$NON-NLS-1$
                    method.getStatusLine().toString(), method.getResponseBodyAsString());
        } else {
            version = method.getResponseBodyAsString();
        }

    } catch (HttpException e) {
        throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient.5", e.getMessage())); //$NON-NLS-1$
    } catch (IOException e) {
        throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient.6", e.getMessage())); //$NON-NLS-1$
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return version;
}

From source file:net.sourceforge.jcctray.model.HTTPCruise.java

/**
 * Returns a {@link GetMethod} with some configuration set. Clients may
 * override. Calls {@link #configureMethod(HttpMethod, DashBoardProject)} to
 * configure the {@link HttpMethod} for the particular project.
 * //  ww  w  .jav a  2  s  .com
 * @param project
 *            the project used to configure the {@link HttpMethod}
 * @return a {@link GetMethod}
 */
protected HttpMethod httpMethod(DashBoardProject project) {
    HttpMethod method = new GetMethod(forceBuildURL(project));
    configureMethod(method, project);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    return method;
}

From source file:com.cloud.storage.template.S3TemplateDownloader.java

public S3TemplateDownloader(S3TO s3TO, String downloadUrl, String installPath,
        DownloadCompleteCallback downloadCompleteCallback, long maxTemplateSizeInBytes, String username,
        String password, Proxy proxy, ResourceType resourceType) {
    this.downloadUrl = downloadUrl;
    this.s3TO = s3TO;
    this.resourceType = resourceType;
    this.maxTemplateSizeInByte = maxTemplateSizeInBytes;
    this.httpClient = HTTPUtils.getHTTPClient();
    this.downloadCompleteCallback = downloadCompleteCallback;

    // Create a GET method for the download url.
    this.getMethod = new GetMethod(downloadUrl);

    // Set the retry handler, default to retry 5 times.
    this.getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            HTTPUtils.getHttpMethodRetryHandler(5));

    // Follow redirects
    this.getMethod.setFollowRedirects(true);

    // Set file extension.
    this.fileExtension = StringUtils.substringAfterLast(StringUtils.substringAfterLast(downloadUrl, "/"), ".");

    // Calculate and set S3 Key.
    this.s3Key = join(asList(installPath, StringUtils.substringAfterLast(downloadUrl, "/")), S3Utils.SEPARATOR);

    // Set proxy if available.
    HTTPUtils.setProxy(proxy, this.httpClient);

    // Set credentials if available.
    HTTPUtils.setCredentials(username, password, this.httpClient);
}

From source file:controllers.sparql.SparqlQueryExecuter.java

public String request(URL url) throws SparqlExecutionException {
    GetMethod method = new GetMethod(url.toString());
    String response = null;/* w  w w . j ava2 s .  c  o m*/

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("SparqlQuery failed: " + method.getStatusLine());
            throw new SparqlExecutionException(String.format("%s (%s). %s", method.getStatusLine(),
                    method.getURI(), method.getResponseBodyAsString()));
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        response = new String(responseBody);

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        throw new SparqlExecutionException(e);
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        throw new SparqlExecutionException(e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:net.paissad.waqtsalat.utils.DownloadHelper.java

/**
 * <p>/*  w  w w. ja v  a  2 s  .  c  o  m*/
 * Download a resource from the specified url and save it to the specified
 * file.
 * </p>
 * <b>Note</b>: If you plan to cancel the download at any time, then this
 * method should be embed into it's own thread.
 * <p>
 * <b>Example</b>:
 * 
 * <pre>
 *  final DownloadHelper downloader = new DownloadHelper();
 *  Thread t = new Thread() {
 *      public void run() {
 *          try {
 *              downloader.download("http://domain.com/file.zip", new File("/tmp/output.zip"));
 *          } catch (Exception e) {
 *              ...
 *          }
 *      }
 *  };
 *  t.start();
 *  // Waits 3 seconds and then cancels the download.
 *  Thread.sleep(3 * 1000L);
 *  downloader.cancel();
 *  ...
 * </pre>
 * 
 * </p>
 * 
 * @param url
 *            - The url of the file to download.
 * @param file
 *            - The downloaded file (where it will be stored).
 * @throws IOException
 * @throws HttpException
 */
public void download(final String url, final File file) throws HttpException, IOException {

    GetMethod method = null;
    InputStream responseBody = null;
    OutputStream out = null;

    try {
        final boolean fileExisted = file.exists();

        HttpClient client = new HttpClient();
        method = new GetMethod(url);
        method.setFollowRedirects(true);
        method.setRequestHeader("User-Agent", WSConstants.WS_USER_AGENT);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        method.getParams().setParameter(HttpMethodParams.WARN_EXTRA_INPUT, Boolean.TRUE);

        // Execute the method.
        int responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK) {
            logger.error("Http method failed : {}.", method.getStatusLine().toString());
        }

        // Read the response body.
        responseBody = method.getResponseBodyAsStream();

        // Let's try to compute the amount of total bytes of the file to
        // download.
        URL u = new URL(url);
        URLConnection urlc = u.openConnection();
        this.totalBytes = urlc.getContentLength();
        long lastModified = urlc.getLastModified();

        // The OutputStream for the 'downloaded' file.
        out = new BufferedOutputStream(new FileOutputStream(file));

        this.updateState(DownloadState.IN_PROGRESS);

        byte[] data = new byte[BUFFER_SIZE];
        int length;
        while ((length = responseBody.read(data, 0, BUFFER_SIZE)) != -1 && !isCancelled) {
            out.write(data, 0, length);
            this.bytesDownloaded += length;
            setChanged();
            notifyObservers(getBytesDownloaded());
        }

        if (isCancelled) {
            this.updateState(DownloadState.CANCELED);
            logger.info("The download has been cancelled.");

        } else {
            // The download was not cancelled.
            out.flush();
            if (lastModified > 0) {
                file.setLastModified(lastModified);
            }

            if (bytesDownloaded != totalBytes) {
                logger.warn("The expected bytes to download is {}, but got {}.", getTotalBytes(),
                        getBytesDownloaded());
                this.updateState(DownloadState.ERROR);
            }

            this.updateState(DownloadState.FINISHED);
            logger.info("Download of '{}' finished successfully.", url);
        }

        // If the file did not exist before the download but does exit now,
        // we must remove it if an error occurred or if the download was
        // cancelled.
        if (getState() == DownloadState.CANCELED || getState() == DownloadState.ERROR) {
            if (!fileExisted && file.exists()) {
                FileUtils.forceDelete(file);
            }
        }

    } catch (HttpException he) {
        this.updateState(DownloadState.ERROR);
        logger.error("Fatal protocol violation : " + he);
        throw new HttpException("Error while downloading from the url '" + url + "'", he);

    } catch (IOException ioe) {
        this.updateState(DownloadState.ERROR);
        logger.error("Fatal transport error : " + ioe);
        throw new IOException(ioe);

    } finally {
        if (method != null)
            method.releaseConnection();
        if (responseBody != null)
            responseBody.close();
        if (out != null)
            out.close();
    }
}

From source file:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient_0_5_0.java

private String getEngineInfo(String infoType)
        throws EngineUnavailableException, ServiceInvocationFailedException {
    String version;//from w  ww  .  j  a  va2  s . c o  m
    HttpClient client;
    PostMethod method;
    NameValuePair[] nameValuePairs;

    version = null;
    client = new HttpClient();
    method = new PostMethod(getServiceUrl(ENGINE_INFO_SERVICE));

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    nameValuePairs = new NameValuePair[] { new NameValuePair("infoType", infoType) }; //$NON-NLS-1$

    method.setRequestBody(nameValuePairs);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new ServiceInvocationFailedException(
                    Messages.getString("SpagoBITalendEngineClient_0_5_0.serviceExcFailed") //$NON-NLS-1$
                            + ENGINE_INFO_SERVICE,
                    method.getStatusLine().toString(),
                    method.getResponseBodyAsString());
        } else {
            version = method.getResponseBodyAsString();
        }

    } catch (HttpException e) {
        throw new EngineUnavailableException(
                Messages.getString("SpagoBITalendEngineClient_0_5_0.protocolViolation") + e.getMessage()); //$NON-NLS-1$
    } catch (IOException e) {
        throw new EngineUnavailableException(
                Messages.getString("SpagoBITalendEngineClient_0_5_0.transportError") + e.getMessage()); //$NON-NLS-1$
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return version;
}

From source file:com.unicauca.braim.http.HttpBraimClient.java

public User GET_User(String username, String access_token) throws IOException, Exception {
    User user = null;//ww w . java  2s  .com
    Gson gson = new Gson();

    String token_data = "?braim_token=" + access_token;

    GetMethod method = new GetMethod(api_url + "/api/v1/users/" + username + token_data);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    int statusCode = client.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
        throw new Exception("The username or password are invalid");
    }

    byte[] responseBody = method.getResponseBody();
    String response = new String(responseBody, "UTF-8");
    user = gson.fromJson(response, User.class);
    System.out.println(user.getEmail() + "Has been retrieved");

    return user;
}

From source file:eu.eco2clouds.scheduler.bonfire.BFClientSchedulerImpl.java

private String putMethod(String url, String payload, Boolean exception) {
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    PutMethod method = new PutMethod(url);
    setHeaders(method);/*from   ww w . ja v a  2 s  .c  o  m*/

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    String response = "";

    try {
        RequestEntity entity = new StringRequestEntity(payload, SchedulerDictionary.CONTENT_TYPE_BONFIRE_XML,
                "UTF-8");
        method.setRequestEntity(entity);
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_ACCEPTED) { //TODO test for this case... 
            logger.warn(
                    "get managed experiments information... : " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}