Search in sources :

Example 86 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project pokeraidbot by magnusmickelsson.

the class GymDataImportTool method getGymsFromMapSiteToFile.

private static void getGymsFromMapSiteToFile(String arg, String location) {
    FileOutputStream fis = null;
    try {
        final Integer widthCube = new Integer(arg);
        String ann4Cookie = "1";
        String mapFiltersCookie = "1[##split##]1[##split##]1[##split##]0[##split##]0[##split##]1[##split##]1" + "[##split##]0[##split##]1[##split##]1[##split##]1";
        String ann6Cookie = "1";
        String latlngZoomCookie = "14[##split##]59.84869731029538[##split##]17.579755254187045";
        final BasicCookieStore cookieStore = new BasicCookieStore();
        final CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnPerRoute(10).setMaxConnTotal(10).setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContext.getDefault())).setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultCookieStore(cookieStore).setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36").disableAutomaticRetries().disableContentCompression().disableRedirectHandling().build();
        RestTemplate restTemplate;
        final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        restTemplate = new RestTemplate(requestFactory);
        URI uri;
        String address = "https://www.pokemongomap.info";
        uri = new URI(address);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
        System.out.println("Response code for request to get cookies (200 = OK): " + responseEntity.getStatusCode());
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException("Could not get session cookie from map site!");
        }
        final BasicClientCookie2 announcementnews6 = new BasicClientCookie2("announcementnews6", ann4Cookie);
        announcementnews6.setDomain("www.pokemongomap.info");
        announcementnews6.setPath("/");
        cookieStore.addCookie(announcementnews6);
        final BasicClientCookie2 mapfilters = new BasicClientCookie2("mapfilters", mapFiltersCookie);
        mapfilters.setDomain("www.pokemongomap.info");
        mapfilters.setPath("/");
        cookieStore.addCookie(mapfilters);
        final BasicClientCookie2 announcementnews8 = new BasicClientCookie2("announcementnews8", ann6Cookie);
        announcementnews8.setDomain("www.pokemongomap.info");
        announcementnews8.setPath("/");
        cookieStore.addCookie(announcementnews8);
        final BasicClientCookie2 latlngzoom = new BasicClientCookie2("latlngzoom", latlngZoomCookie);
        latlngzoom.setDomain("www.pokemongomap.info");
        latlngzoom.setPath("/");
        cookieStore.addCookie(latlngzoom);
        // Delays so we don't overload the site and get banned
        Thread.sleep(1000);
        address = "https://www.pokemongomap.info/includes/geocode.php";
        uri = new URI(address);
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.put("searchloc", asList(location));
        body.put("fromlat", asList("59.854661870313116"));
        body.put("tolat", asList("59.85956994867656"));
        body.put("fromlng", asList("17.624897788330145"));
        body.put("tolng", asList("17.63279421166999"));
        final LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.put("DNT", asList("1"));
        headers.put("Accept", asList("application/json", "text/javascript", "*/*; q=0.01"));
        headers.put("Content-Type", asList("application/x-www-form-urlencoded; charset=UTF-8"));
        headers.put("upgrade-insecure-requests", asList("1"));
        headers.put("Host", asList("www.pokemongomap.info"));
        headers.put("Origin", asList("https://www.pokemongomap.info"));
        headers.put("Referer", asList("www.pokemongomap.info/"));
        headers.put("Connection", asList("keep-alive"));
        headers.put("X-Requested-With", asList("XMLHttpRequest"));
        headers.put("Accept-Encoding", asList(""));
        headers.put("Accept-Language", asList("sv-SE", "sv;q=0.8", "en-US;q=0.6", "en;q=0.4", "nb;q=0.2", "de;q=0.2"));
        RequestEntity<MultiValueMap<String, String>> request = new RequestEntity<>(body, headers, HttpMethod.POST, uri);
        responseEntity = restTemplate.postForEntity(address, request, String.class);
        System.out.println("Response code for geocode request (200 = OK): " + responseEntity.getStatusCode());
        final String geoCodeResponseBody = responseEntity.getBody();
        System.out.println("Geocode response: " + geoCodeResponseBody);
        GeocodeResponse geocodeResponse = new ObjectMapper().readValue(geoCodeResponseBody, GeocodeResponse.class);
        Thread.sleep(2000);
        String pokeStopUrl = "https://www.pokemongomap.info/includes/it55nmsq9.php";
        address = new String(pokeStopUrl);
        headers.put("Accept", asList("*/*"));
        body = new LinkedMultiValueMap<>();
        final Double lat = new Double(geocodeResponse.getLat());
        final Double lng = new Double(geocodeResponse.getLng());
        Double cubeInDegrees = widthCube / 111.409d;
        body.put("fromlat", asList("" + (lat - cubeInDegrees)));
        body.put("tolat", asList("" + (lat + cubeInDegrees)));
        body.put("fromlng", asList("" + (lng - cubeInDegrees)));
        body.put("tolng", asList("" + (lng + cubeInDegrees)));
        // 1 = include pokestops
        body.put("fpoke", asList("0"));
        // 1 = include gyms
        body.put("fgym", asList("1"));
        // 1 = ??
        body.put("farm", asList("0"));
        // 1 = include nest locations (don't use this)
        body.put("nests", asList("0"));
        // 1 = include raids
        body.put("raid", asList("1"));
        request = new RequestEntity<>(body, headers, HttpMethod.POST, new URI(pokeStopUrl));
        responseEntity = restTemplate.postForEntity(address, request, String.class);
        System.out.println("Response code for gym query request (200 = OK): " + responseEntity.getStatusCode());
        final String gymsJson = responseEntity.getBody();
        if (gymsJson.equals("[]")) {
            throw new RuntimeException("Empty result set. Try and use different parameters..");
        }
        final Map<String, GymResponse> gymsMap = new ObjectMapper().readValue(gymsJson, gymsTypeReference);
        GymsResponse response = new GymsResponse(gymsMap);
        System.out.println("Read " + response.getGyms().size() + " gyms from this query.");
        final String fileName = "target/" + location + ".csv";
        fis = new FileOutputStream(fileName);
        fis.write(("ID" + separator + "LOCATION" + separator + "NAME" + separator + "AREA\n").getBytes("UTF-8"));
        System.out.println("Saving file: " + fileName);
        for (String id : response.getGyms().keySet()) {
            GymResponse gym = response.getGyms().get(id);
            if (gym == null) {
                throw new RuntimeException("Found null gym for id " + id);
            }
            fis.write((id + separator + "\"" + gym.getLatitude() + separator + gym.getLongitude() + "\"" + separator + gym.getName() + separator + StringUtils.left(location, 1).toUpperCase() + location.substring(1, location.length()) + "\n").getBytes("UTF-8"));
        }
        System.out.println("File: " + fileName + " saved.");
    } catch (Throwable e) {
        e.printStackTrace();
        System.exit(-1);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
Also used : LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URI(java.net.URI) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicClientCookie2(org.apache.http.impl.cookie.BasicClientCookie2) IOException(java.io.IOException) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) FileOutputStream(java.io.FileOutputStream) RestTemplate(org.springframework.web.client.RestTemplate) RequestEntity(org.springframework.http.RequestEntity)

Example 87 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project ma-modules-public by infiniteautomation.

the class MangoStoreClient method login.

/**
 * Login to the store
 * @param email
 * @param password
 * @param retries
 * @throws ClientProtocolException
 * @throws IOException
 * @throws HttpException
 */
public void login(String email, String password, int retries) throws ClientProtocolException, IOException, HttpException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
    HttpPost httppost = new HttpPost(storeUrl + "/login");
    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    params.add(new BasicNameValuePair("submit", "Login"));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    // Execute and get the response.
    HttpResponse response = executeRequest(httppost, 302, retries);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            for (Header header : response.getAllHeaders()) {
                if (header.getName().equals("Set-Cookie")) {
                    // Set our cookie here
                    String[] cookiePath = header.getValue().split(";");
                    // Now we have JSESSIONID=stuff , Path=/
                    String[] cookie = cookiePath[0].split("=");
                    String[] path = cookiePath[1].split("=");
                    this.sessionId = cookie[1];
                    BasicClientCookie c = new BasicClientCookie(cookie[0], cookie[1]);
                    c.setDomain(storeUrl);
                    c.setPath(path[1]);
                    c.setVersion(0);
                    cookieStore.addCookie(c);
                }
            }
        } finally {
            instream.close();
        }
    }
    return;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 88 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project OpenOLAT by OpenOLAT.

the class HttpClientFactory method getHttpClientInstance.

/**
 * @param host For basic authentication
 * @param port For basic authentication
 * @param user For basic authentication
 * @param password For basic authentication
 * @param redirect If redirect is allowed
 * @return CloseableHttpClient
 */
public static CloseableHttpClient getHttpClientInstance(String host, int port, String user, String password, boolean redirect) {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketRegistry);
    SocketConfig.Builder socketConfigBuilder = SocketConfig.copy(SocketConfig.DEFAULT);
    socketConfigBuilder.setSoTimeout(10000);
    cm.setDefaultSocketConfig(socketConfigBuilder.build());
    HttpClientBuilder clientBuilder = HttpClientBuilder.create().setConnectionManager(cm).setMaxConnTotal(10).setDefaultCookieStore(new BasicCookieStore());
    if (redirect) {
        clientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
    } else {
        clientBuilder.setRedirectStrategy(new NoRedirectStrategy());
    }
    if (user != null && user.length() > 0) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password));
        clientBuilder.setDefaultCredentialsProvider(provider);
    }
    return clientBuilder.build();
}
Also used : BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SocketConfig(org.apache.http.config.SocketConfig) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) LaxRedirectStrategy(org.apache.http.impl.client.LaxRedirectStrategy) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 89 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project groovity by disney.

the class Http method tag.

@SuppressWarnings({ "rawtypes", "unchecked" })
public Object tag(Map attributes, Closure body) throws Exception {
    Object url = resolve(attributes, "url");
    if (url == null) {
        throw new RuntimeException("<g:http> requires 'url' attribute");
    }
    Object var = resolve(attributes, VAR);
    String method = "GET";
    Object methodAtt = resolve(attributes, "method");
    if (methodAtt != null) {
        method = methodAtt.toString();
    }
    boolean followRedirects = true;
    Object redirectsAtt = resolve(attributes, "redirects");
    if (redirectsAtt != null) {
        followRedirects = Boolean.parseBoolean(redirectsAtt.toString());
    }
    CookieOption cookieOption = CookieOption.DEFAULT;
    Object cookiesAtt = resolve(attributes, "cookies");
    if (cookiesAtt != null) {
        cookieOption = CookieOption.valueOf(cookiesAtt.toString().toUpperCase());
    }
    Object timeout = resolve(attributes, TIMEOUT);
    final int timeoutSeconds = timeout == null ? -1 : timeout instanceof Number ? ((Number) timeout).intValue() : Integer.parseInt(timeout.toString());
    Object target = resolve(attributes, "to");
    if (target instanceof Class) {
        if (!Object.class.equals(target)) {
            target = ((Class) target).newInstance();
        }
    }
    if (target == null) {
        target = Object.class;
    }
    Object async = resolve(attributes, "async");
    if (async != null && !(async instanceof Boolean)) {
        async = Boolean.valueOf(async.toString());
    }
    HttpEntity dataEntity = null;
    Object data = resolve(attributes, "data");
    HttpClientContext clientContext = resolve(attributes, "context", HttpClientContext.class);
    if (clientContext == null) {
        clientContext = HttpClientContext.create();
    }
    if (clientContext.getCookieStore() == null) {
        // we don't want to let cookies be shared across contexts
        clientContext.setCookieStore(new BasicCookieStore());
    }
    if (clientContext.getAuthCache() == null) {
        // we also don't want to share credentials across contexts
        clientContext.setAuthCache(new BasicAuthCache());
    }
    final HttpClientContext fContext = clientContext;
    ScriptHelper context = getScriptHelper(body);
    Object oldOut = get(context, OUT);
    // execute body to assemble URL params, headers, post body
    Map variables = context.getBinding().getVariables();
    URI uri;
    URIBuilder builder;
    ArrayList<Header> headers;
    Optional<UserPass> userPass;
    Optional<HttpSignatureSigner> signer;
    Optional<HttpRequestInterceptor> interceptor;
    try {
        builder = new URIBuilder(url.toString());
        bind(context, Uri.CURRENT_URI_BUILDER, builder);
        headers = new ArrayList<Header>();
        bind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS, headers);
        Credentials.acceptCredentials(variables);
        Signature.acceptSigner(variables);
        acceptInterceptor(variables);
        StringWriter sw = new StringWriter();
        bind(context, OUT, sw);
        try {
            Object rval = body.call();
            if (rval instanceof Writable) {
                ((Writable) rval).writeTo(sw);
            }
        } finally {
            bind(context, OUT, oldOut);
            userPass = Credentials.resolveCredentials(variables);
            signer = Signature.resolveSigner(variables);
            interceptor = resolveInterceptor(variables);
        }
        String val = sw.toString();
        if (val.trim().length() > 0) {
            dataEntity = new StringEntity(val);
        }
        uri = builder.build();
        if (userPass.isPresent()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(userPass.get().getUser(), new String(userPass.get().getPass())));
            clientContext.setCredentialsProvider(credsProvider);
        }
    } catch (URISyntaxException e1) {
        throw new RuntimeException("Invalid URI " + url, e1);
    } finally {
        unbind(context, Uri.CURRENT_URI_BUILDER);
        unbind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS);
    }
    final HttpRequestBase request = "POST".equalsIgnoreCase(method) ? new HttpPost(uri) : "PUT".equalsIgnoreCase(method) ? new HttpPut(uri) : "HEAD".equalsIgnoreCase(method) ? new HttpHead(uri) : "DELETE".equalsIgnoreCase(method) ? new HttpDelete(uri) : "OPTIONS".equalsIgnoreCase(method) ? new HttpOptions(uri) : new HttpGet(uri);
    if (headers.size() > 0) {
        request.setHeaders(headers.toArray(new Header[0]));
    }
    if (request instanceof HttpEntityEnclosingRequest) {
        if (data != null) {
            // decide on strategy to convert data to entity
            if (data instanceof HttpEntity) {
                dataEntity = (HttpEntity) data;
            } else {
                // look at content type for a hint
                Header targetType = request.getFirstHeader("Content-Type");
                if (targetType != null && targetType.getValue().contains("json")) {
                    CharArrayWriter caw = new CharArrayWriter();
                    new ModelJsonWriter(caw).visit(data);
                    dataEntity = new StringEntity(caw.toString());
                } else if (targetType != null && targetType.getValue().contains("xml")) {
                    if (data instanceof groovy.util.Node) {
                        dataEntity = new StringEntity(XmlUtil.serialize((groovy.util.Node) data));
                    } else if (data instanceof GPathResult) {
                        dataEntity = new StringEntity(XmlUtil.serialize((GPathResult) data));
                    } else if (data instanceof Element) {
                        dataEntity = new StringEntity(XmlUtil.serialize((Element) data));
                    } else if (data instanceof Document) {
                        dataEntity = new StringEntity(XmlUtil.serialize(((Document) data).getDocumentElement()));
                    } else {
                        // if it's not an XML model assume it's a well formed XML string
                        dataEntity = new StringEntity(data.toString());
                    }
                } else if ((targetType != null && targetType.getValue().contains("x-www-form-urlencoded")) || (targetType == null && (data instanceof Map || data instanceof List))) {
                    // key/value pairs, accept a map, a list of maps, or a list of NameValuePairs
                    Iterator source = data instanceof Map ? ((Map) data).entrySet().iterator() : ((List) data).iterator();
                    ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
                    while (source.hasNext()) {
                        Object next = source.next();
                        if (next instanceof Map.Entry) {
                            Map.Entry entry = (Entry) next;
                            pairs.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue() != null ? entry.getValue().toString() : ""));
                        } else if (next instanceof NameValuePair) {
                            pairs.add((NameValuePair) next);
                        } else if (next instanceof Map) {
                            Iterator<Map.Entry> sub = ((Map) next).entrySet().iterator();
                            while (sub.hasNext()) {
                                Map.Entry se = sub.next();
                                pairs.add(new BasicNameValuePair(se.getKey().toString(), se.getValue() != null ? se.getValue().toString() : ""));
                            }
                        }
                    }
                    dataEntity = new UrlEncodedFormEntity(pairs);
                } else if (targetType != null && targetType.getValue().contains("multipart/form-data")) {
                    // list of maps, each map must contain "name" and "body", plus optional "type" and "filename"
                    Iterator<Map> parts = ((List<Map>) data).iterator();
                    MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
                    while (parts.hasNext()) {
                        Map part = parts.next();
                        Object pbody = part.get("body");
                        String name = (String) part.get("name");
                        String type = (String) part.get("type");
                        String filename = (String) part.get("filename");
                        ContentType ct = type != null ? ContentType.parse(type) : null;
                        if (pbody instanceof File) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (File) pbody, ct, filename);
                        } else if (pbody instanceof byte[]) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (byte[]) pbody, ct, filename);
                        } else if (pbody instanceof ContentBody) {
                            meBuilder.addPart(name, (ContentBody) pbody);
                        } else if (pbody instanceof InputStream) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (InputStream) pbody, ct, filename);
                        } else {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_TEXT;
                            }
                            meBuilder.addTextBody(name, pbody.toString(), ct);
                        }
                    }
                    dataEntity = meBuilder.build();
                } else {
                    // no help from content type header, check for modeled XML
                    if (data instanceof groovy.util.Node) {
                        dataEntity = new StringEntity(XmlUtil.serialize((groovy.util.Node) data), ContentType.APPLICATION_XML);
                    } else if (data instanceof GPathResult) {
                        dataEntity = new StringEntity(XmlUtil.serialize((GPathResult) data), ContentType.APPLICATION_XML);
                    } else if (data instanceof Element) {
                        dataEntity = new StringEntity(XmlUtil.serialize((Element) data), ContentType.APPLICATION_XML);
                    } else if (data instanceof Document) {
                        dataEntity = new StringEntity(XmlUtil.serialize(((Document) data).getDocumentElement()), ContentType.APPLICATION_XML);
                    } else if (data instanceof byte[]) {
                        dataEntity = new ByteArrayEntity((byte[]) data);
                    } else if (data instanceof InputStream) {
                        dataEntity = new InputStreamEntity((InputStream) data);
                    } else if (data instanceof File) {
                        dataEntity = new FileEntity((File) data);
                    } else {
                        // best option left is to post the toString value of the data
                        dataEntity = new StringEntity(data.toString());
                    }
                }
            }
        }
        if (dataEntity != null) {
            ((HttpEntityEnclosingRequest) request).setEntity(dataEntity);
        }
    }
    RequestConfig.Builder configBuilder = request.getConfig() == null ? RequestConfig.custom() : RequestConfig.copy(request.getConfig());
    if (!followRedirects) {
        configBuilder.setRedirectsEnabled(followRedirects);
    }
    configBuilder.setCookieSpec(cookieOption.getCookieSpec());
    request.setConfig(configBuilder.build());
    final String varName = var != null ? var.toString() : null;
    ResponseHandler handler = null;
    try {
        Function handlerFunction = (Function) get(body, Handler.HANDLER_BINDING);
        if (handlerFunction != null) {
            handler = new ResponseHandler<Object>() {

                @Override
                public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                    return handlerFunction.apply(response);
                }
            };
        }
        unbind(body, Handler.HANDLER_BINDING);
    } catch (Exception e) {
    }
    if (handler == null) {
        handler = new AutoParsingResponseHandler(target);
    }
    final List<HttpRequestInterceptor> interceptors = new ArrayList<>();
    if (signer.isPresent()) {
        interceptors.add(signer.get());
    }
    if (interceptor.isPresent()) {
        interceptors.add(interceptor.get());
    }
    final ResponseHandler rHandler = handler;
    final boolean isAsync = (async != null && Boolean.TRUE.equals(async));
    Callable<Object> requester = new Callable() {

        public Object call() throws Exception {
            TimeoutTask timeoutTask = null;
            if (timeoutSeconds > 0) {
                timeoutTask = new TimeoutTask(request);
                timeoutTimer.schedule(timeoutTask, timeoutSeconds * 1000);
            }
            try {
                Binding oldThreadBinding = null;
                if (isAsync) {
                    oldThreadBinding = ScriptHelper.THREAD_BINDING.get();
                    Binding asyncBinding = new Binding();
                    asyncBinding.setVariable("request", request);
                    ScriptHelper.THREAD_BINDING.set(asyncBinding);
                }
                try {
                    for (HttpRequestInterceptor interceptor : interceptors) {
                        interceptor.process(request, null);
                    }
                    return httpClient.execute(request, rHandler, fContext);
                } finally {
                    if (isAsync) {
                        if (oldThreadBinding == null) {
                            ScriptHelper.THREAD_BINDING.remove();
                        } else {
                            ScriptHelper.THREAD_BINDING.set(oldThreadBinding);
                        }
                    }
                }
            } catch (HttpResponseException e) {
                if (isAsync) {
                    log.error("Async HTTP response error for " + request.getURI() + ": " + e.getMessage());
                }
                throw e;
            } catch (Exception e) {
                if (request.isAborted()) {
                    if (isAsync) {
                        log.error("Async <g:http> request timed out for " + request.getURI());
                    }
                    throw new TimeoutException("Timed out executing <g:http> for " + request.getURI());
                } else {
                    if (isAsync) {
                        log.error("Async <g:http> request error for " + request.getURI(), e);
                    }
                    throw new RuntimeException("Error executing <g:http> for " + request.getURI(), e);
                }
            } finally {
                if (timeoutTask != null) {
                    timeoutTask.cancel();
                }
            }
        }
    };
    Object responseVar = null;
    if (isAsync) {
        // return the Future to the calling code
        Future<Object> f = asyncExecutor.submit(requester);
        responseVar = new Future<Object>() {

            @Override
            public boolean cancel(boolean mayInterruptIfRunning) {
                return f.cancel(mayInterruptIfRunning);
            }

            @Override
            public boolean isCancelled() {
                return f.isCancelled();
            }

            @Override
            public boolean isDone() {
                return f.isDone();
            }

            @Override
            public Object get() throws InterruptedException, ExecutionException {
                GroovityStatistics.startExecution("http(async)");
                try {
                    return f.get();
                } finally {
                    GroovityStatistics.endExecution();
                }
            }

            @Override
            public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                GroovityStatistics.startExecution("http(async)");
                try {
                    return f.get(timeout, unit);
                } finally {
                    GroovityStatistics.endExecution();
                }
            }
        };
    } else {
        // return the parsed/handled response object
        GroovityStatistics.startExecution("http(sync)");
        try {
            responseVar = requester.call();
        } finally {
            GroovityStatistics.endExecution();
        }
    }
    if (varName != null) {
        bind(context, varName, responseVar);
    }
    return responseVar;
}
Also used : Entry(java.util.Map.Entry) HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ContentType(org.apache.http.entity.ContentType) ResponseHandler(org.apache.http.client.ResponseHandler) HttpOptions(org.apache.http.client.methods.HttpOptions) ArrayList(java.util.ArrayList) Writable(groovy.lang.Writable) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Document(org.w3c.dom.Document) HttpPut(org.apache.http.client.methods.HttpPut) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ArrayList(java.util.ArrayList) TimeoutException(java.util.concurrent.TimeoutException) Binding(groovy.lang.Binding) RequestConfig(org.apache.http.client.config.RequestConfig) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) ContentBody(org.apache.http.entity.mime.content.ContentBody) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) AuthScope(org.apache.http.auth.AuthScope) ModelJsonWriter(com.disney.groovity.model.ModelJsonWriter) ScriptHelper(com.disney.groovity.util.ScriptHelper) Map(java.util.Map) File(java.io.File) HttpEntity(org.apache.http.HttpEntity) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpGet(org.apache.http.client.methods.HttpGet) Element(org.w3c.dom.Element) HttpResponseException(org.apache.http.client.HttpResponseException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpHead(org.apache.http.client.methods.HttpHead) CharArrayWriter(java.io.CharArrayWriter) Callable(java.util.concurrent.Callable) Function(java.util.function.Function) Entry(java.util.Map.Entry) StringWriter(java.io.StringWriter) HttpSignatureSigner(com.disney.http.auth.client.signer.HttpSignatureSigner) Iterator(java.util.Iterator) GPathResult(groovy.util.slurpersupport.GPathResult) ExecutionException(java.util.concurrent.ExecutionException) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) FileEntity(org.apache.http.entity.FileEntity) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) UserPass(com.disney.groovity.tags.Credentials.UserPass) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 90 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project oncotree by cBioPortal.

the class TopBraidSessionConfiguration method getSessionIdCookie.

private Cookie getSessionIdCookie(String url, Cookie initialSessionIdCookie) {
    try {
        HttpClientContext context = HttpClientContext.create();
        if (initialSessionIdCookie != null) {
            BasicCookieStore requestCookieStore = new BasicCookieStore();
            requestCookieStore.addCookie(initialSessionIdCookie);
            context.setCookieStore(requestCookieStore);
        }
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(new HttpHead(url), context);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != HttpStatus.OK.value()) {
            logger.error("Response status: '" + statusLine + "'");
            return null;
        }
        // get the cookie
        List<Cookie> cookies = context.getCookieStore().getCookies();
        for (Cookie cookie : cookies) {
            logger.debug("Cookie name: '" + cookie.getName() + "' value: '" + cookie.getValue() + "'");
            if (cookie.getName().equals("JSESSIONID")) {
                return cookie;
            }
        }
        // close stuff
        client.close();
        response.close();
    } catch (Exception e) {
        logger.error("Unable to secure connection: '" + e + "'");
    }
    return null;
}
Also used : StatusLine(org.apache.http.StatusLine) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Cookie(org.apache.http.cookie.Cookie) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpHead(org.apache.http.client.methods.HttpHead)

Aggregations

BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)138 HttpResponse (org.apache.http.HttpResponse)54 HttpGet (org.apache.http.client.methods.HttpGet)51 Test (org.junit.Test)44 BasicClientCookie (org.apache.http.impl.cookie.BasicClientCookie)40 RequestConfig (org.apache.http.client.config.RequestConfig)36 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)36 CookieStore (org.apache.http.client.CookieStore)26 Header (org.apache.http.Header)25 HttpClient (org.apache.http.client.HttpClient)25 IOException (java.io.IOException)23 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)22 Cookie (org.apache.http.cookie.Cookie)19 HttpPost (org.apache.http.client.methods.HttpPost)15 CredentialsProvider (org.apache.http.client.CredentialsProvider)14 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)14 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)14 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)13 URI (java.net.URI)12 HttpEntity (org.apache.http.HttpEntity)12