Example usage for org.apache.http.protocol HttpContext setAttribute

List of usage examples for org.apache.http.protocol HttpContext setAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpContext setAttribute.

Prototype

void setAttribute(String str, Object obj);

Source Link

Usage

From source file:com.jimplush.goose.images.ImageSaver.java

/**
 * stores an image to disk and returns the path where the file was written
 *
 * @param imageSrc/*  w  ww  .  j  a v a  2s .c om*/
 * @return
 */
public static String storeTempImage(HttpClient httpClient, String linkhash, String imageSrc,
        Configuration config) throws SecretGifException {

    String localSrcPath = null;
    HttpGet httpget = null;
    HttpResponse response = null;

    try {

        imageSrc = imageSrc.replace(" ", "%20");
        if (logger.isDebugEnabled()) {
            logger.debug("Starting to download image: " + imageSrc);
        }

        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, HtmlFetcher.emptyCookieStore);

        httpget = new HttpGet(imageSrc);

        response = httpClient.execute(httpget, localContext);

        String respStatus = response.getStatusLine().toString();
        if (!respStatus.contains("200")) {
            return null;
        }

        HttpEntity entity = response.getEntity();

        String fileExtension = "";
        try {
            Header contentType = entity.getContentType();
        } catch (Exception e) {
            logger.error(e.getMessage());

        }

        // generate random token
        Random generator = new Random();
        int randInt = generator.nextInt();

        localSrcPath = config.getLocalStoragePath() + "/" + linkhash + "_" + randInt;

        if (logger.isDebugEnabled()) {
            logger.debug("Storing image locally: " + localSrcPath);
        }
        if (entity != null) {
            InputStream instream = entity.getContent();
            OutputStream outstream = new FileOutputStream(localSrcPath);
            try {
                try {
                    IOUtils.copy(instream, outstream);
                } catch (Exception e) {
                    throw e;
                } finally {
                    entity.consumeContent();
                    instream.close();
                    outstream.close();
                }

                // get mime type and store the image extension based on that shiz
                fileExtension = ImageSaver.getFileExtension(config, localSrcPath);
                if (fileExtension == "" || fileExtension == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("EMPTY FILE EXTENSION: " + localSrcPath);
                    }
                    return null;
                }
                File f = new File(localSrcPath);
                if (f.length() < config.getMinBytesForImages()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("TOO SMALL AN IMAGE: " + localSrcPath + " bytes: " + f.length());
                    }
                    return null;
                }

                File newFile = new File(localSrcPath + fileExtension);
                f.renameTo(newFile);
                localSrcPath = localSrcPath + fileExtension;

                if (logger.isDebugEnabled()) {
                    logger.debug("Image successfully Written to Disk");
                }

            } catch (IOException e) {
                logger.error(e.toString(), e);
            } catch (SecretGifException e) {
                throw e;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }

        }

    } catch (IllegalArgumentException e) {
        logger.warn(e.getMessage());
    } catch (SecretGifException e) {
        raise(e);
    } catch (ClientProtocolException e) {

        logger.error(e.toString());
    } catch (IOException e) {
        logger.error(e.toString());
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.toString());
        e.printStackTrace();
    } finally {

        httpget.abort();

    }

    return localSrcPath;
}

From source file:de.stkl.gbgvertretungsplan.sync.SyncAdapter.java

public static boolean tryLogin(String username, String password) throws CommunicationInterface.ParsingException,
        IOException, CommunicationInterface.CommunicationException {
    AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null);

    CookieStore cookies = new BasicCookieStore();
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookies);

    boolean result = tryLogin(httpClient, localContext, username, password);

    // cleanup//  www.  j  a va 2 s.  c o m
    httpClient.close();

    return result;
}

From source file:com.ryan.ryanreader.account.RedditAccount.java

public static LoginResultPair login(final Context context, final String username, final String password,
        final HttpClient client) {

    // ???/*from w w  w  . ja v  a  2s  .  c o  m*/
    final ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>(3);
    fields.add(new BasicNameValuePair("user", username));
    fields.add(new BasicNameValuePair("passwd", password));
    fields.add(new BasicNameValuePair("api_type", "json"));

    // TODO put somewhere else
    final HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context));
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO
    // remove
    // hardcoded
    // params,
    // put
    // in
    // network
    // prefs
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100);
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    params.setParameter(ClientPNames.MAX_REDIRECTS, 5);

    final HttpPost request = new HttpPost("https://ssl.reddit.com/api/login");
    request.setParams(params);

    try {
        request.setEntity(new UrlEncodedFormEntity(fields, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
        return new LoginResultPair(LoginResult.INTERNAL_ERROR);
    }

    final PersistentCookieStore cookies = new PersistentCookieStore();

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookies);

    final StatusLine status;
    final HttpEntity entity;
    try {
        final HttpResponse response = client.execute(request, localContext);
        status = response.getStatusLine();
        entity = response.getEntity();

    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    if (status.getStatusCode() != 200) {
        return new LoginResultPair(LoginResult.REQUEST_ERROR);
    }

    final JsonValue result;

    try {
        result = new JsonValue(entity.getContent());
        result.buildInThisThread();
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    final String modhash;

    try {

        // TODO use the more general reddit error finder
        final JsonBufferedArray errors = result.asObject().getObject("json").getArray("errors");
        errors.join();
        if (errors.getCurrentItemCount() != 0) {

            for (final JsonValue v : errors) {
                for (final JsonValue s : v.asArray()) {

                    // TODO handle unknown messages by concatenating all
                    // Reddit's strings

                    if (s.getType() == JsonValue.Type.STRING) {

                        Log.i("RR DEBUG ERROR", s.asString());

                        // lol, reddit api
                        if (s.asString().equalsIgnoreCase("WRONG_PASSWORD")
                                || s.asString().equalsIgnoreCase("invalid password")
                                || s.asString().equalsIgnoreCase("passwd"))
                            return new LoginResultPair(LoginResult.WRONG_PASSWORD);

                        if (s.asString().contains("too much")) // also
                            // "RATELIMIT",
                            // but
                            // that's
                            // not as
                            // descriptive
                            return new LoginResultPair(LoginResult.RATELIMIT, s.asString());
                    }
                }
            }

            return new LoginResultPair(LoginResult.UNKNOWN_REDDIT_ERROR);
        }

        final JsonBufferedObject data = result.asObject().getObject("json").getObject("data");

        modhash = data.getString("modhash");

    } catch (NullPointerException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (InterruptedException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    }

    return new LoginResultPair(LoginResult.SUCCESS, new RedditAccount(username, modhash, cookies, 0), null);
}

From source file:NIO_HTTP_Client.java

public static void setTargetHost(final HttpContext context, String key, final Object x) {
    HttpHost target_host = (HttpHost) x;
    //System.err.println("inside setTargetHost");
    context.setAttribute(key, target_host);
    //System.err.println("finished setTargetHost");
}

From source file:com.oakesville.mythling.util.HttpHelper.java

public static HttpContext getDigestAuthContext(String host, int port, String user, String password) {
    CredentialsProvider cp = new BasicCredentialsProvider();
    AuthScope scope = new AuthScope(host, port);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
    cp.setCredentials(scope, creds);//from  w  w  w .j  a v a  2  s.com
    HttpContext credContext = new BasicHttpContext();
    credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);
    return credContext;
}

From source file:de.tor.tribes.util.OBSTReportSender.java

public static void sendReport(URL pTarget, String pData) throws Exception {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    HttpHost host = new HttpHost(pTarget.getHost(), pTarget.getPort());

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {//from www  . j a v  a  2s .  c o  m
        HttpEntity[] requestBodies = { new StringEntity(pData) };

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                    pTarget.getPath() + "?" + pTarget.getQuery());

            request.setEntity(requestBodies[i]);
            // System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            //   System.out.println("<< Response: " + response.getStatusLine());
            // System.out.println(EntityUtils.toString(response.getEntity()));
            // System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:com.globo.aclapi.client.ClientAclAPI.java

private static HttpClient newDefaultHttpClient(SSLSocketFactory socketFactory, HttpParams params,
        ProxySelector proxySelector) {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", socketFactory, 443));

    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);

    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params) {
        @Override/*from w  w w. java  2 s  . c o  m*/
        protected HttpContext createHttpContext() {
            HttpContext httpContext = super.createHttpContext();
            AuthSchemeRegistry authSchemeRegistry = new AuthSchemeRegistry();
            authSchemeRegistry.register("Bearer", new BearerAuthSchemeFactory());
            httpContext.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, authSchemeRegistry);
            AuthScope sessionScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM,
                    "Bearer");

            Credentials credentials = new TokenCredentials("");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(sessionScope, credentials);
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
            return httpContext;
        }
    };
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(registry, proxySelector));

    return httpClient;
}

From source file:org.wso2.am.integration.ui.tests.util.TestUtil.java

/**
 * Login to API Store or Publisher/*from w  w w . ja v a2s  .co m*/
 *
 * @param userName
 * @param password
 * @param URL      API Store or Publisher URL
 * @return
 * @throws Exception
 */
public static HttpContext login(String userName, String password, String URL) throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL + APIMTestConstants.APISTORE_LOGIN_URL);
    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(3);

    params.add(new BasicNameValuePair(APIMTestConstants.API_ACTION, APIMTestConstants.API_LOGIN_ACTION));
    params.add(new BasicNameValuePair(APIMTestConstants.APISTORE_LOGIN_USERNAME, userName));
    params.add(new BasicNameValuePair(APIMTestConstants.APISTORE_LOGIN_PASSWORD, password));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    HttpResponse response = httpclient.execute(httppost, httpContext);
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    boolean isError = Boolean.parseBoolean(responseString.split(",")[0].split(":")[1].split("}")[0].trim());

    if (isError) {
        String errorMsg = responseString.split(",")[1].split(":")[1].split("}")[0].trim();
        throw new Exception("Error while Login to API Publisher : " + errorMsg);

    } else {
        return httpContext;
    }

}

From source file:com.tri_voltage.md.io.YoutubeVideoParser.java

private static void play(String videoId, int format, String encoding, String userAgent, File outputdir,
        String extension) throws Throwable {
    log.fine("Retrieving " + videoId);
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("video_id", videoId));
    qparams.add(new BasicNameValuePair("fmt", "" + format));
    URI uri = getUri("get_video_info", qparams);

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpGet httpget = new HttpGet(uri);
    if (userAgent != null && userAgent.length() > 0) {
        httpget.setHeader("User-Agent", userAgent);
    }//from w w w.j a  v  a 2s  .c  o  m

    log.finer("Executing " + uri);
    HttpResponse response = httpclient.execute(httpget, localContext);
    HttpEntity entity = response.getEntity();
    if (entity != null && response.getStatusLine().getStatusCode() == 200) {
        InputStream instream = entity.getContent();
        String videoInfo = getStringFromInputStream(encoding, instream);
        if (videoInfo != null && videoInfo.length() > 0) {
            List<NameValuePair> infoMap = new ArrayList<NameValuePair>();
            URLEncodedUtils.parse(infoMap, new Scanner(videoInfo), encoding);
            String downloadUrl = null;
            String filename = videoId;

            for (NameValuePair pair : infoMap) {
                String key = pair.getName();
                String val = pair.getValue();
                log.finest(key + "=" + val);
                if (key.equals("title")) {
                    filename = val;
                } else if (key.equals("fmt_url_map")) {
                    String[] formats = commaPattern.split(val);
                    boolean found = false;
                    for (String fmt : formats) {
                        String[] fmtPieces = pipePattern.split(fmt);
                        if (fmtPieces.length == 2) {
                            int pieceFormat = Integer.parseInt(fmtPieces[0]);
                            log.fine("Available format=" + pieceFormat);
                            if (pieceFormat == format) {
                                // found what we want
                                downloadUrl = fmtPieces[1];
                                found = true;
                                break;
                            }
                        }
                    }
                    if (!found) {
                        log.warning(
                                "Could not find video matching specified format, however some formats of the video do exist (use -verbose).");
                    }
                }
            }

            filename = cleanFilename(filename);
            if (filename.length() == 0) {
                filename = videoId;
            } else {
                filename += "_" + videoId;
            }
            filename += "." + extension;
            File outputfile = new File(outputdir, filename);

            if (downloadUrl != null) {
                downloadWithHttpClient(userAgent, downloadUrl, outputfile);
            } else {
                log.severe("Could not find video");
            }
        } else {
            log.severe("Did not receive content from youtube");
        }
    } else {
        log.severe("Could not contact youtube: " + response.getStatusLine());
    }
}

From source file:com.vanda.beivandalibnetwork.utils.HttpUtils.java

/**
 * Cookie/*from  w w  w  .j a  va2  s .  co  m*/
 * 
 * @param setAsCurrentContext
 *            ??true?CURRENT_CONTEXT
 * @return
 */
public static HttpContext cookieContext(boolean setAsCurrentContext) {
    if (getCookieStore(CURRENT_CONTEXT) != null)
        return CURRENT_CONTEXT;

    CookieStore store = new BasicCookieStore();
    HttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.COOKIE_STORE, store);
    if (setAsCurrentContext)
        CURRENT_CONTEXT = context;
    return context;
}