Search in sources :

Example 1 with UsernamePasswordCredentials

use of org.apache.commons.httpclient.UsernamePasswordCredentials 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 2 with UsernamePasswordCredentials

use of org.apache.commons.httpclient.UsernamePasswordCredentials in project opennms by OpenNMS.

the class CustomHttpClientConfigurer method configureHttpClient.

@Override
public void configureHttpClient(final HttpClient client) {
    try {
        final SSLContext ctx = SSLContext.getInstance("SSL");
        ctx.init(EMPTY_KEYMANAGER_ARRAY, new TrustManager[] { new AnyServerX509TrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getUsername(), getPassword());
        client.getState().setCredentials(AuthScope.ANY, credentials);
        client.getParams().setAuthenticationPreemptive(true);
        LOG.debug("Configuring HTTP client with modified trust manager, username={}, password=xxxxxxxx", getUsername());
    } catch (final Exception e) {
        throw new CustomConfigurerException(e);
    }
}
Also used : SecureRandom(java.security.SecureRandom) AnyServerX509TrustManager(org.opennms.core.utils.AnyServerX509TrustManager) SSLContext(javax.net.ssl.SSLContext) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 3 with UsernamePasswordCredentials

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

the class ExchangeUtils method sendGetRequest.

public static String sendGetRequest(String urlAddress) throws Exception {
    HttpClient httpclient = new HttpClient();
    GetMethod getMethod = new GetMethod(urlAddress);
    TransportClientProperties tcp = TransportClientPropertiesFactory.create("http");
    if (tcp.getProxyHost().length() != 0) {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(tcp.getProxyUser() != null ? tcp.getProxyUser() : "", tcp.getProxyPassword() != null ? tcp.getProxyUser() : "");
        httpclient.getState().setProxyCredentials(AuthScope.ANY, creds);
        HostConfiguration hcf = new HostConfiguration();
        hcf.setProxy(tcp.getProxyHost(), Integer.parseInt(tcp.getProxyPort()));
        httpclient.executeMethod(hcf, getMethod);
    } else {
        httpclient.executeMethod(getMethod);
    }
    String response = getMethod.getResponseBodyAsString();
    getMethod.releaseConnection();
    return response;
}
Also used : HostConfiguration(org.apache.commons.httpclient.HostConfiguration) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) TransportClientProperties(org.apache.axis.components.net.TransportClientProperties) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 4 with UsernamePasswordCredentials

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

the class MDMTransactionClient method getSessionID.

public static String getSessionID(String url, String username, String password) throws IOException {
    HttpClient client = new HttpClient();
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    client.getParams().setAuthenticationPreemptive(true);
    GetMethod get = new GetMethod(url);
    get.setDoAuthentication(true);
    String sessionID;
    try {
        client.executeMethod(get);
        sessionID = parseSessionID(get);
    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        get.releaseConnection();
    }
    return sessionID;
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 5 with UsernamePasswordCredentials

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

the class MDMTransactionClient method newTransaction.

public static MDMTransaction newTransaction(String url, String username, String password) throws IOException {
    HttpClient client = new HttpClient();
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    client.getParams().setAuthenticationPreemptive(true);
    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);
    String tid;
    String sessionID;
    try {
        client.executeMethod(put);
        tid = put.getResponseBodyAsString();
        sessionID = parseSessionID(put);
    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        put.releaseConnection();
    }
    MDMTransaction result = new MDMTransaction();
    result.setUrl(url);
    result.setId(tid);
    result.setUsername(username);
    result.setPassword(password);
    result.setSessionId(sessionID);
    return result;
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) PutMethod(org.apache.commons.httpclient.methods.PutMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Aggregations

UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)113 Credentials (org.apache.commons.httpclient.Credentials)97 ArrayList (java.util.ArrayList)65 NameValuePair (org.apache.commons.httpclient.NameValuePair)61 JsonObject (javax.json.JsonObject)52 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)51 Test (org.junit.Test)51 JsonArray (javax.json.JsonArray)19 HttpClient (org.apache.commons.httpclient.HttpClient)19 AuthScope (org.apache.commons.httpclient.auth.AuthScope)17 HashSet (java.util.HashSet)14 GetMethod (org.apache.commons.httpclient.methods.GetMethod)14 HttpException (org.apache.commons.httpclient.HttpException)9 IOException (java.io.IOException)8 HttpMethod (org.apache.commons.httpclient.HttpMethod)8 HttpState (org.apache.commons.httpclient.HttpState)6 PostMethod (org.apache.commons.httpclient.methods.PostMethod)6 URL (java.net.URL)5 RepositoryException (org.apache.sling.ide.transport.RepositoryException)5 Header (org.apache.commons.httpclient.Header)4