Example usage for org.apache.commons.httpclient DefaultHttpMethodRetryHandler DefaultHttpMethodRetryHandler

List of usage examples for org.apache.commons.httpclient DefaultHttpMethodRetryHandler DefaultHttpMethodRetryHandler

Introduction

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

Prototype

public DefaultHttpMethodRetryHandler(int paramInt, boolean paramBoolean) 

Source Link

Usage

From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java

public void testSingleFileImport() {
    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    PostMethod method = new PostMethod(restCommandUrlPrefix + "import");
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("path", "/app:company_home"),
            new NameValuePair("ticket", ticket) };
    method.setQueryString(params);//from   w  ww  . j  a  va  2  s . c  om

    try {
        //method.setRequestBody(new NameValuePair[] {
        //      new NameValuePair("path", "/app:company_home") });
        FileInputStream acpXmlIs = new FileInputStream(SAMPLE_SINGLE_FILE_PATH);
        InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs);
        //InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs, "text/xml; charset=ISO-8859-1");
        method.setRequestEntity(entity);
    } catch (IOException ioex) {
        fail("ACP XML file not found " + ioex.getMessage());
    }

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

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody)); // TODO rm

        HashSet<String> defaultElementSet = new HashSet<String>(
                Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE,
                        RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE }));
        HashMap<String, String> elementValueMap = new HashMap<String, String>(6);

        try {
            XMLEventReader xmlReader = XmlHelper.getXMLInputFactory()
                    .createXMLEventReader(new ByteArrayInputStream(responseBody));
            StringBuffer singleLevelTextBuf = null;
            while (xmlReader.hasNext()) {
                XMLEvent event = xmlReader.nextEvent();
                switch (event.getEventType()) {
                case XMLEvent.CHARACTERS:
                case XMLEvent.CDATA:
                    if (singleLevelTextBuf != null) {
                        singleLevelTextBuf.append(event.asCharacters().getData());
                    } // else element not meaningful
                    break;
                case XMLEvent.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String elementName = startElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)
                            // TODO another command specific level
                            || "ticket".equals(elementName)) {
                        // reinit buffer at start of meaningful elements
                        singleLevelTextBuf = new StringBuffer();
                    } else {
                        singleLevelTextBuf = null; // not useful
                    }
                    break;
                case XMLEvent.END_ELEMENT:
                    if (singleLevelTextBuf == null) {
                        break; // element not meaningful
                    }

                    // TODO or merely put it in the map since the element has been tested at start
                    EndElement endElement = event.asEndElement();
                    elementName = endElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)) {
                        String value = singleLevelTextBuf.toString();
                        elementValueMap.put(elementName, value);
                        // TODO test if it is code and it is not OK, break to error handling
                    }
                    // TODO another command specific level
                    else if ("ticket".equals(elementName)) {
                        ticket = singleLevelTextBuf.toString();
                    }
                    // singleLevelTextBuf = new StringBuffer(); // no ! in start
                    break;
                }
            }
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            t.printStackTrace();
            //throw t;
        }

        String code = elementValueMap.get(RestConstants.TAG_CODE);
        assertTrue(RestConstants.CODE_OK.equals(code));
        System.out.println("got ticket " + ticket);

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

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;// ww  w.  j  av  a 2  s.c  om

    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;//from   www  . j  a va  2s. c o  m
    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;/*  www .  j  a va2  s.co 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.
 * //from   w  w  w. j  av a 2s  .c o  m
 * @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:controllers.sparql.SparqlQueryExecuter.java

public String request(URL url) throws SparqlExecutionException {
    GetMethod method = new GetMethod(url.toString());
    String response = null;/*www.  j  a  v  a 2 s.co  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:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient_0_5_0.java

private String getEngineInfo(String infoType)
        throws EngineUnavailableException, ServiceInvocationFailedException {
    String version;/*from   w  w  w  .j  a  va  2  s. co  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:net.paissad.waqtsalat.utils.DownloadHelper.java

/**
 * <p>/*from  w w w.j  a v a 2  s.c om*/
 * 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:com.unicauca.braim.http.HttpBraimClient.java

public User GET_User(String username, String access_token) throws IOException, Exception {
    User user = null;//from  w  w w.j  av a 2  s . 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   www . ja va2 s.co  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;
}