Search in sources :

Example 1 with HttpException

use of org.apache.commons.httpclient.HttpException in project pinot by linkedin.

the class FileUploadUtils method sendSegmentJsonImpl.

public static int sendSegmentJsonImpl(final String host, final String port, final JSONObject segmentJson) {
    PostMethod postMethod = null;
    try {
        RequestEntity requestEntity = new StringRequestEntity(segmentJson.toString(), ContentType.APPLICATION_JSON.getMimeType(), ContentType.APPLICATION_JSON.getCharset().name());
        postMethod = new PostMethod("http://" + host + ":" + port + "/" + SEGMENTS_PATH);
        postMethod.setRequestEntity(requestEntity);
        postMethod.setRequestHeader(UPLOAD_TYPE, FileUploadType.JSON.toString());
        int statusCode = FILE_UPLOAD_HTTP_CLIENT.executeMethod(postMethod);
        if (statusCode >= 400) {
            String errorString = "POST Status Code: " + statusCode + "\n";
            if (postMethod.getResponseHeader("Error") != null) {
                errorString += "ServletException: " + postMethod.getResponseHeader("Error").getValue();
            }
            throw new HttpException(errorString);
        }
        return statusCode;
    } catch (Exception e) {
        LOGGER.error("Caught exception while sending json: {}", segmentJson.toString(), e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpException(org.apache.commons.httpclient.HttpException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 2 with HttpException

use of org.apache.commons.httpclient.HttpException in project pinot by linkedin.

the class FileUploadUtils method sendSegmentUriImpl.

private static int sendSegmentUriImpl(final String host, final String port, final String uri) {
    SendFileMethod httpMethod = SendFileMethod.POST;
    EntityEnclosingMethod method = null;
    try {
        method = httpMethod.forUri("http://" + host + ":" + port + "/" + SEGMENTS_PATH);
        method.setRequestHeader(UPLOAD_TYPE, FileUploadType.URI.toString());
        method.setRequestHeader(DOWNLOAD_URI, uri);
        FILE_UPLOAD_HTTP_CLIENT.executeMethod(method);
        if (method.getStatusCode() >= 400) {
            String errorString = "POST Status Code: " + method.getStatusCode() + "\n";
            if (method.getResponseHeader("Error") != null) {
                errorString += "ServletException: " + method.getResponseHeader("Error").getValue();
            }
            throw new HttpException(errorString);
        }
        return method.getStatusCode();
    } catch (Exception e) {
        LOGGER.error("Caught exception while sending uri: {}", uri, e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}
Also used : EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpException(org.apache.commons.httpclient.HttpException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 3 with HttpException

use of org.apache.commons.httpclient.HttpException in project pinot by linkedin.

the class FileUploadUtils method sendFile.

public static int sendFile(final String host, final String port, final String path, final String fileName, final InputStream inputStream, final long lengthInBytes, SendFileMethod httpMethod) {
    EntityEnclosingMethod method = null;
    try {
        method = httpMethod.forUri("http://" + host + ":" + port + "/" + path);
        Part[] parts = { new FilePart(fileName, new PartSource() {

            @Override
            public long getLength() {
                return lengthInBytes;
            }

            @Override
            public String getFileName() {
                return fileName;
            }

            @Override
            public InputStream createInputStream() throws IOException {
                return new BufferedInputStream(inputStream);
            }
        }) };
        method.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
        FILE_UPLOAD_HTTP_CLIENT.executeMethod(method);
        if (method.getStatusCode() >= 400) {
            String errorString = "POST Status Code: " + method.getStatusCode() + "\n";
            if (method.getResponseHeader("Error") != null) {
                errorString += "ServletException: " + method.getResponseHeader("Error").getValue();
            }
            throw new HttpException(errorString);
        }
        return method.getStatusCode();
    } catch (Exception e) {
        LOGGER.error("Caught exception while sending file: {}", fileName, e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}
Also used : PartSource(org.apache.commons.httpclient.methods.multipart.PartSource) BufferedInputStream(java.io.BufferedInputStream) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpException(org.apache.commons.httpclient.HttpException) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 4 with HttpException

use of org.apache.commons.httpclient.HttpException in project openhab1-addons by openhab.

the class Telegram method sendTelegramPhoto.

@ActionDoc(text = "Sends a Picture, protected by username/password authentication, via Telegram REST API")
public static boolean sendTelegramPhoto(@ParamDoc(name = "group") String group, @ParamDoc(name = "photoURL") String photoURL, @ParamDoc(name = "caption") String caption, @ParamDoc(name = "username") String username, @ParamDoc(name = "password") String password) {
    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }
    if (photoURL == null) {
        logger.error("photoURL not defined, action skipped");
        return false;
    }
    // load image from url
    byte[] imageFromURL;
    HttpClient getClient = new HttpClient();
    if (username != null && password != null) {
        getClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        getClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
    }
    GetMethod getMethod = new GetMethod(photoURL);
    getMethod.getParams().setSoTimeout(HTTP_PHOTO_TIMEOUT);
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    try {
        int statusCode = getClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: {}", getMethod.getStatusLine());
            return false;
        }
        imageFromURL = getMethod.getResponseBody();
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        getMethod.releaseConnection();
    }
    // parse image type
    String imageType;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(imageFromURL));
        Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
        if (!imageReaders.hasNext()) {
            logger.error("photoURL does not represent a known image type");
            return false;
        }
        ImageReader reader = imageReaders.next();
        imageType = reader.getFormatName();
    } catch (IOException e) {
        logger.error("cannot parse photoURL as image: {}", e.getMessage());
        return false;
    }
    // post photo to telegram
    String url = String.format(TELEGRAM_PHOTO_URL, groupTokens.get(group).getToken());
    PostMethod postMethod = new PostMethod(url);
    try {
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setSoTimeout(HTTP_PHOTO_TIMEOUT);
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        Part[] parts = new Part[caption != null ? 3 : 2];
        parts[0] = new StringPart("chat_id", groupTokens.get(group).getChatId());
        parts[1] = new FilePart("photo", new ByteArrayPartSource(String.format("image.%s", imageType), imageFromURL));
        if (caption != null) {
            parts[2] = new StringPart("caption", caption, "UTF-8");
        }
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        HttpClient client = new HttpClient();
        int statusCode = client.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: {}", postMethod.getStatusLine());
            return false;
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        postMethod.releaseConnection();
    }
    return true;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) ImageInputStream(javax.imageio.stream.ImageInputStream) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) IOException(java.io.IOException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ByteArrayInputStream(java.io.ByteArrayInputStream) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) ImageReader(javax.imageio.ImageReader) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 5 with HttpException

use of org.apache.commons.httpclient.HttpException in project openhab1-addons by openhab.

the class FrontierSiliconRadioConnection method doLogin.

/**
     * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for
     * future requests.
     * 
     * @return <code>true</code> if login was successful; <code>false</code> otherwise.
     */
public boolean doLogin() {
    // reset login flag
    isLoggedIn = false;
    if (httpClient == null) {
        httpClient = new HttpClient();
    }
    final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin;
    logger.trace("opening URL:" + url);
    final HttpMethod method = new GetMethod(url);
    method.getParams().setSoTimeout(SOCKET_TIMEOUT);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    try {
        final int statusCode = httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }
        final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.trace("login response: " + responseBody);
        }
        try {
            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk()) {
                logger.trace("login successful");
                sessionId = result.getSessionId();
                isLoggedIn = true;
                // login successful :-)
                return true;
            }
        } catch (Exception e) {
            logger.error("Parsing response failed");
        }
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }
    // login not successful
    return false;
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Aggregations

HttpException (org.apache.commons.httpclient.HttpException)61 IOException (java.io.IOException)55 HttpClient (org.apache.commons.httpclient.HttpClient)34 GetMethod (org.apache.commons.httpclient.methods.GetMethod)31 HttpMethod (org.apache.commons.httpclient.HttpMethod)22 InputStream (java.io.InputStream)15 Header (org.apache.commons.httpclient.Header)12 PostMethod (org.apache.commons.httpclient.methods.PostMethod)12 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)9 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