Search in sources :

Example 16 with BasicHttpEntityEnclosingRequest

use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project cerberus-source by cerberustesting.

the class SeleniumServerService method getIPOfNode.

private static void getIPOfNode(TestCaseExecution tCExecution) {
    try {
        Session session = tCExecution.getSession();
        HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver()).getCommandExecutor();
        SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId();
        String hostName = ce.getAddressOfRemoteServer().getHost();
        int port = ce.getAddressOfRemoteServer().getPort();
        HttpHost host = new HttpHost(hostName, port);
        HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
        URL sessionURL = new URL(SeleniumServerService.getBaseUrl(session.getHost(), session.getPort()) + "/grid/api/testsession?session=" + sessionId);
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
        HttpResponse response = client.execute(host, r);
        if (!response.getStatusLine().toString().contains("403") && !response.getEntity().getContentType().getValue().contains("text/html")) {
            InputStream contents = response.getEntity().getContent();
            StringWriter writer = new StringWriter();
            IOUtils.copy(contents, writer, "UTF8");
            JSONObject object = new JSONObject(writer.toString());
            URL myURL = new URL(object.getString("proxyId"));
            if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
                tCExecution.setIp(myURL.getHost());
                tCExecution.setPort(String.valueOf(myURL.getPort()));
            }
        }
    } catch (IOException ex) {
        LOG.error(ex.toString());
    } catch (JSONException ex) {
        LOG.error(ex.toString());
    }
}
Also used : RemoteWebDriver(org.openqa.selenium.remote.RemoteWebDriver) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) IOException(java.io.IOException) Point(org.openqa.selenium.Point) URL(java.net.URL) HttpCommandExecutor(org.openqa.selenium.remote.HttpCommandExecutor) StringWriter(java.io.StringWriter) JSONObject(org.json.JSONObject) HttpHost(org.apache.http.HttpHost) HttpClient(org.apache.http.client.HttpClient) SessionId(org.openqa.selenium.remote.SessionId) LaxRedirectStrategy(org.apache.http.impl.client.LaxRedirectStrategy) Session(org.cerberus.engine.entity.Session) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest)

Example 17 with BasicHttpEntityEnclosingRequest

use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project Talon-for-Twitter by klinker24.

the class TwitterMultipleImageHelper method uploadPics.

public boolean uploadPics(File[] pics, String text, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    final String ids_string = getMediaIds(pics, twitter);
    if (ids_string == null) {
        return false;
    }
    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();
        // generate authorization header
        String get_or_post = "POST";
        String oauth_signature_method = "HMAC-SHA1";
        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        // any relatively random alphanumeric string will work here
        String oauth_nonce = uuid_string;
        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        // get current time in milliseconds
        long ts = tempcal.getTimeInMillis();
        // then divide by 1000 to get seconds
        String oauth_timestamp = (new Long(ts / 1000)).toString();
        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
        System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);
        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/update.json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));
        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        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(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
        try {
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, null, null);
                SSLSocketFactory ssf = sslcontext.getSocketFactory();
                Socket socket = ssf.createSocket();
                socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path);
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("media_ids", new StringBody(ids_string));
                reqEntity.addPart("status", new StringBody(text));
                reqEntity.addPart("trim_user", new StringBody("1"));
                request2.setEntity(reqEntity);
                request2.setParams(params);
                request2.addHeader("Authorization", authorization_header_string);
                httpexecutor.preProcess(request2, httpproc, context);
                HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                response2.setParams(params);
                httpexecutor.postProcess(response2, httpproc, context);
                String responseBody = EntityUtils.toString(response2.getEntity());
                System.out.println("response=" + responseBody);
                // error checking here. Otherwise, status should be updated.
                jsonresponse = new JSONObject(responseBody);
                conn.close();
            } catch (HttpException he) {
                System.out.println(he.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage());
            } catch (NoSuchAlgorithmException nsae) {
                System.out.println(nsae.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage());
            } catch (KeyManagementException kme) {
                System.out.println(kme.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage());
            } finally {
                conn.close();
            }
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } catch (Exception e) {
    }
    return true;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) AccessToken(twitter4j.auth.AccessToken) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) Calendar(java.util.Calendar) JSONException(org.json.JSONException) DefaultHttpClientConnection(org.apache.http.impl.DefaultHttpClientConnection) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TwitterException(twitter4j.TwitterException) IOException(java.io.IOException) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) HttpParams(org.apache.http.params.HttpParams) JSONObject(org.json.JSONObject) StringBody(org.apache.http.entity.mime.content.StringBody) Socket(java.net.Socket)

Example 18 with BasicHttpEntityEnclosingRequest

use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project engine by craftercms.

the class ConfigAwareProxyServlet method newProxyRequestWithEntity.

@Override
protected HttpRequest newProxyRequestWithEntity(String method, String proxyRequestUri, HttpServletRequest request) throws IOException {
    // Check if the request was cached
    if (request instanceof ContentCachingRequestWrapper) {
        // Use the cached content instead of the input stream
        HttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        byte[] cachedContent = ((ContentCachingRequestWrapper) request).getContentAsByteArray();
        // If the cache is empty, the input stream has not been consumed
        if (cachedContent.length != 0) {
            proxyRequest.setEntity(new InputStreamEntity(new ByteArrayInputStream(cachedContent), cachedContent.length));
            return proxyRequest;
        }
    }
    // Use the input stream as usual
    return super.newProxyRequestWithEntity(method, proxyRequestUri, request);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) ContentCachingRequestWrapper(org.springframework.web.util.ContentCachingRequestWrapper) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 19 with BasicHttpEntityEnclosingRequest

use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project selenium_java by sergueik.

the class GridInfoExtracter method getHostNameAndPort.

private static String[] getHostNameAndPort(String hostName, int port, SessionId session) {
    String[] hostAndPort = new String[2];
    String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: ";
    try {
        HttpHost host = new HttpHost(hostName, port);
        @SuppressWarnings("deprecation") DefaultHttpClient client = new DefaultHttpClient();
        URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session);
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
        HttpResponse response = client.execute(host, r);
        JSONObject object = extractObject(response);
        URL myURL = new URL(object.getString("proxyId"));
        if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
            hostAndPort[0] = myURL.getHost();
            hostAndPort[1] = Integer.toString(myURL.getPort());
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, errorMsg, e);
        throw new RuntimeException(errorMsg, e);
    }
    return hostAndPort;
}
Also used : JSONObject(org.json.JSONObject) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) URL(java.net.URL) IOException(java.io.IOException) JSONException(org.json.JSONException) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest)

Example 20 with BasicHttpEntityEnclosingRequest

use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project selenium_java by sergueik.

the class AppTest method getIPOfNode.

private static String getIPOfNode(RemoteWebDriver remoteDriver) {
    String hostFound = null;
    try {
        HttpCommandExecutor ce = (HttpCommandExecutor) remoteDriver.getCommandExecutor();
        String hostName = ce.getAddressOfRemoteServer().getHost();
        int port = ce.getAddressOfRemoteServer().getPort();
        HttpHost host = new HttpHost(hostName, port);
        DefaultHttpClient client = new DefaultHttpClient();
        URL sessionURL = new URL(String.format("http://%s:%d/grid/api/testsession?session=%s", hostName, port, remoteDriver.getSessionId()));
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
        HttpResponse response = client.execute(host, r);
        JSONObject object = extractObject(response);
        URL myURL = new URL(object.getString("proxyId"));
        if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
            hostFound = myURL.getHost();
        }
    } catch (Exception e) {
        System.err.println(e);
    }
    return hostFound;
}
Also used : HttpCommandExecutor(org.openqa.selenium.remote.HttpCommandExecutor) JSONObject(org.json.JSONObject) HttpHost(org.apache.http.HttpHost) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) URL(java.net.URL) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BindException(java.net.BindException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest)

Aggregations

BasicHttpEntityEnclosingRequest (org.apache.http.message.BasicHttpEntityEnclosingRequest)24 IOException (java.io.IOException)14 HttpHost (org.apache.http.HttpHost)10 URL (java.net.URL)8 JSONException (org.json.JSONException)8 JSONObject (org.json.JSONObject)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 GeneralSecurityException (java.security.GeneralSecurityException)6 HttpResponse (org.apache.http.HttpResponse)6 InputStreamEntity (org.apache.http.entity.InputStreamEntity)6 InetSocketAddress (java.net.InetSocketAddress)5 Socket (java.net.Socket)5 SSLContext (javax.net.ssl.SSLContext)5 Calendar (java.util.Calendar)4 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)4 ServletException (javax.servlet.ServletException)4 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)4 DefaultHttpClientConnection (org.apache.http.impl.DefaultHttpClientConnection)4 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)4 BasicHttpRequest (org.apache.http.message.BasicHttpRequest)4