Search in sources :

Example 51 with HttpException

use of org.apache.commons.httpclient.HttpException in project cloudstack by apache.

the class BigSwitchApiTest method executeMethodTestUnauthorized.

@Test(expected = BigSwitchBcfApiException.class)
public void executeMethodTestUnauthorized() throws BigSwitchBcfApiException, IOException {
    GetMethod gm = mock(GetMethod.class);
    when(_client.executeMethod((HttpMethod) any())).thenThrow(new HttpException());
    when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED);
    _api.executeMethod(gm);
}
Also used : GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) Test(org.junit.Test)

Example 52 with HttpException

use of org.apache.commons.httpclient.HttpException in project asterixdb by apache.

the class RunSQLPPFileAction method doPerform.

@Override
public void doPerform() throws Exception {
    FileOutputStream csvFileOut = new FileOutputStream(csvFilePath.toFile());
    PrintWriter printer = new PrintWriter(csvFileOut, true);
    try {
        if (aqlFilePath.toFile().isDirectory()) {
            for (File f : aqlFilePath.toFile().listFiles()) {
                queriesToRun.add(f.toPath());
            }
        } else {
            queriesToRun.add(aqlFilePath);
        }
        for (Path p : queriesToRun) {
            String sqlpp = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(p))).toString();
            String uri = MessageFormat.format(REST_URI_TEMPLATE, restHost, String.valueOf(restPort));
            HttpPost post = new HttpPost(uri);
            post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            post.setEntity(new StringEntity(sqlpp, StandardCharsets.UTF_8));
            long start = System.currentTimeMillis();
            HttpResponse resp = httpClient.execute(post);
            HttpEntity entity = resp.getEntity();
            if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpException("Query returned error" + EntityUtils.toString(entity));
            }
            EntityUtils.consume(entity);
            long end = System.currentTimeMillis();
            long wallClock = end - start;
            String currLine = p.getFileName().toString() + ',' + wallClock;
            System.out.println(currLine);
            printer.print(currLine + '\n');
        }
    } finally {
        printer.close();
    }
}
Also used : Path(java.nio.file.Path) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) HttpException(org.apache.commons.httpclient.HttpException)

Example 53 with HttpException

use of org.apache.commons.httpclient.HttpException in project cloudstack by apache.

the class HttpTemplateDownloader method download.

@Override
public long download(boolean resume, DownloadCompleteCallback callback) {
    switch(status) {
        case ABORTED:
        case UNRECOVERABLE_ERROR:
        case DOWNLOAD_FINISHED:
            return 0;
        default:
    }
    int bytes = 0;
    File file = new File(toFile);
    try {
        long localFileSize = 0;
        if (file.exists() && resume) {
            localFileSize = file.length();
            s_logger.info("Resuming download to file (current size)=" + localFileSize);
        }
        Date start = new Date();
        int responseCode = 0;
        if (localFileSize > 0) {
            // require partial content support for resume
            request.addRequestHeader("Range", "bytes=" + localFileSize + "-");
            if (client.executeMethod(request) != HttpStatus.SC_PARTIAL_CONTENT) {
                errorString = "HTTP Server does not support partial get";
                status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
                return 0;
            }
        } else if ((responseCode = client.executeMethod(request)) != HttpStatus.SC_OK) {
            status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
            errorString = " HTTP Server returned " + responseCode + " (expected 200 OK) ";
            //FIXME: retry?
            return 0;
        }
        Header contentLengthHeader = request.getResponseHeader("Content-Length");
        boolean chunked = false;
        long remoteSize2 = 0;
        if (contentLengthHeader == null) {
            Header chunkedHeader = request.getResponseHeader("Transfer-Encoding");
            if (chunkedHeader == null || !"chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
                status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
                errorString = " Failed to receive length of download ";
                //FIXME: what status do we put here? Do we retry?
                return 0;
            } else if ("chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
                chunked = true;
            }
        } else {
            remoteSize2 = Long.parseLong(contentLengthHeader.getValue());
            if (remoteSize2 == 0) {
                status = TemplateDownloader.Status.DOWNLOAD_FINISHED;
                String downloaded = "(download complete remote=" + remoteSize + "bytes)";
                errorString = "Downloaded " + totalBytes + " bytes " + downloaded;
                downloadTime = 0;
                return 0;
            }
        }
        if (remoteSize == 0) {
            remoteSize = remoteSize2;
        }
        if (remoteSize > maxTemplateSizeInBytes) {
            s_logger.info("Remote size is too large: " + remoteSize + " , max=" + maxTemplateSizeInBytes);
            status = Status.UNRECOVERABLE_ERROR;
            errorString = "Download file size is too large";
            return 0;
        }
        if (remoteSize == 0) {
            remoteSize = maxTemplateSizeInBytes;
        }
        InputStream in = request.getResponseBodyAsStream();
        RandomAccessFile out = new RandomAccessFile(file, "rw");
        out.seek(localFileSize);
        s_logger.info("Starting download from " + getDownloadUrl() + " to " + toFile + " remoteSize=" + remoteSize + " , max size=" + maxTemplateSizeInBytes);
        byte[] block = new byte[CHUNK_SIZE];
        long offset = 0;
        boolean done = false;
        boolean verifiedFormat = false;
        status = TemplateDownloader.Status.IN_PROGRESS;
        while (!done && status != Status.ABORTED && offset <= remoteSize) {
            if ((bytes = in.read(block, 0, CHUNK_SIZE)) > -1) {
                out.write(block, 0, bytes);
                offset += bytes;
                out.seek(offset);
                totalBytes += bytes;
                if (!verifiedFormat && (offset >= 1048576 || offset >= remoteSize)) {
                    //let's check format after we get 1MB or full file
                    String uripath = null;
                    try {
                        URI str = new URI(getDownloadUrl());
                        uripath = str.getPath();
                    } catch (URISyntaxException e) {
                        s_logger.warn("Invalid download url: " + getDownloadUrl() + ", This should not happen since we have validated the url before!!");
                    }
                    String unsupportedFormat = ImageStoreUtil.checkTemplateFormat(file.getAbsolutePath(), uripath);
                    if (unsupportedFormat == null || !unsupportedFormat.isEmpty()) {
                        try {
                            request.abort();
                            out.close();
                            in.close();
                        } catch (Exception ex) {
                            s_logger.debug("Error on http connection : " + ex.getMessage());
                        }
                        status = Status.UNRECOVERABLE_ERROR;
                        errorString = "Template content is unsupported, or mismatch between selected format and template content. Found  : " + unsupportedFormat;
                        return 0;
                    }
                    s_logger.debug("Verified format of downloading file " + file.getAbsolutePath() + " is supported");
                    verifiedFormat = true;
                }
            } else {
                done = true;
            }
        }
        out.getFD().sync();
        Date finish = new Date();
        String downloaded = "(incomplete download)";
        if (totalBytes >= remoteSize) {
            status = TemplateDownloader.Status.DOWNLOAD_FINISHED;
            downloaded = "(download complete remote=" + remoteSize + "bytes)";
        }
        errorString = "Downloaded " + totalBytes + " bytes " + downloaded;
        downloadTime += finish.getTime() - start.getTime();
        in.close();
        out.close();
        return totalBytes;
    } catch (HttpException hte) {
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
        errorString = hte.getMessage();
    } catch (IOException ioe) {
        //probably a file write error?
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
        errorString = ioe.getMessage();
    } finally {
        if (status == Status.UNRECOVERABLE_ERROR && file.exists() && !file.isDirectory()) {
            file.delete();
        }
        request.releaseConnection();
        if (callback != null) {
            callback.downloadComplete(status);
        }
    }
    return 0;
}
Also used : InputStream(java.io.InputStream) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) NoHttpResponseException(org.apache.commons.httpclient.NoHttpResponseException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) Header(org.apache.commons.httpclient.Header) RandomAccessFile(java.io.RandomAccessFile) HttpException(org.apache.commons.httpclient.HttpException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 54 with HttpException

use of org.apache.commons.httpclient.HttpException in project tdi-studio-se by Talend.

the class MDMTransaction method rollback.

public void rollback() throws IOException {
    HttpClient client = new HttpClient();
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    HttpMethod method = new DeleteMethod(url + "/" + id);
    method.setDoAuthentication(true);
    try {
        //$NON-NLS-1$ //$NON-NLS-2$
        method.setRequestHeader("Cookie", getStickySession() + "=" + sessionId);
        client.executeMethod(method);
    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }
    int statuscode = method.getStatusCode();
    if (statuscode >= 400) {
        throw new MDMTransactionException("Rollback failed. The rollback operation has returned the code " + statuscode + ".");
    }
}
Also used : DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 55 with HttpException

use of org.apache.commons.httpclient.HttpException in project zm-mailbox by Zimbra.

the class ElasticSearchIndexTest method cleanupForIndexStore.

@Override
protected void cleanupForIndexStore() {
    String key = testAcct.getId();
    String indexUrl = String.format("%s%s/", LC.zimbra_index_elasticsearch_url_base.value(), key);
    HttpMethod method = new DeleteMethod(indexUrl);
    try {
        ElasticSearchConnector connector = new ElasticSearchConnector();
        int statusCode = connector.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            boolean ok = connector.getBooleanAtJsonPath(new String[] { "ok" }, false);
            boolean acknowledged = connector.getBooleanAtJsonPath(new String[] { "acknowledged" }, false);
            if (!ok || !acknowledged) {
                ZimbraLog.index.debug("Delete index status ok=%b acknowledged=%b", ok, acknowledged);
            }
        } else {
            String error = connector.getStringAtJsonPath(new String[] { "error" });
            if (error != null && error.startsWith("IndexMissingException")) {
                ZimbraLog.index.debug("Unable to delete index for key=%s.  Index is missing", key);
            } else {
                ZimbraLog.index.error("Problem deleting index for key=%s error=%s", key, error);
            }
        }
    } catch (HttpException e) {
        ZimbraLog.index.error("Problem Deleting index with key=" + key, e);
    } catch (IOException e) {
        ZimbraLog.index.error("Problem Deleting index with key=" + key, e);
    }
}
Also used : DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) ElasticSearchConnector(com.zimbra.cs.index.elasticsearch.ElasticSearchConnector) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Aggregations

HttpException (org.apache.commons.httpclient.HttpException)62 IOException (java.io.IOException)55 HttpClient (org.apache.commons.httpclient.HttpClient)35 GetMethod (org.apache.commons.httpclient.methods.GetMethod)32 HttpMethod (org.apache.commons.httpclient.HttpMethod)22 InputStream (java.io.InputStream)16 Header (org.apache.commons.httpclient.Header)12 PostMethod (org.apache.commons.httpclient.methods.PostMethod)12 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)10 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)8 DeleteMethod (org.apache.commons.httpclient.methods.DeleteMethod)6 Test (org.junit.Test)5 ServiceException (com.zimbra.common.service.ServiceException)4 Server (com.zimbra.cs.account.Server)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Date (java.util.Date)4 HashMap (java.util.HashMap)4 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)4 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 XStream (com.thoughtworks.xstream.XStream)3