List of usage examples for org.apache.http.client.protocol ClientContext COOKIE_STORE
String COOKIE_STORE
To view the source code for org.apache.http.client.protocol ClientContext COOKIE_STORE.
Click Source Link
From source file:org.quickconnectfamily.sync.SynchronizedDB.java
/** * Creates a SynchronizedDB object used to interact with a local database and a remote HTTP service. It * sends a login request to the /*from w w w.j a v a 2s .c o m*/ * @param theActivityRef - the activity that the database is associated with. This is usually your initial Acivity class. * @param aDbName - the name of the SQLite file to be kept in sync. * @param aRemoteURL - the URL of the service that will respond to synchronization requests including the port number if not port 80. * For security reasons it is suggested that your URL be an HTTPS URL but this is not required. * @param port - the port number of the remote HTTP service. * @param aRemoteUname - a security credential used in the remote service * @param aRemotePword - a security credential used in the remote service * @param syncTimeout - the amount of time in seconds to attempt all sync requests before timing out. * @throws DataAccessException * @throws URISyntaxException * @throws InterruptedException */ public SynchronizedDB(WeakReference<Context> theActivityRef, String aDbName, URL aRemoteURL, int port, String aRemoteUname, String aRemotePword, long syncTimeout) throws DataAccessException, URISyntaxException, InterruptedException { dbName = aDbName; remoteURL = aRemoteURL.toURI(); remoteUname = aRemoteUname; remotePword = aRemotePword; this.theActivityRef = theActivityRef; SchemeRegistry schemeRegistry = new SchemeRegistry(); if (aRemoteURL.toExternalForm().indexOf("http") == 0) { schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), port)); } else if (aRemoteURL.toExternalForm().indexOf("https") == 0) { schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), port)); } HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); httpClient = new DefaultHttpClient(cm, params); startTransaction(); String errorMessage = null; //insert the required tables if they don't exist try { DataAccessResult aResult = DataAccessObject.transact(theActivityRef, aDbName, "CREATE TABLE IF NOT EXISTS sync_info(int id PRIMARY KEY NOT NULL, last_sync TIMESTAMP);", null); if (aResult.getErrorDescription().equals("not an error")) { aResult = DataAccessObject.transact(theActivityRef, aDbName, "CREATE TABLE IF NOT EXISTS sync_values(timeStamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, sql_key TEXT, sql_params TEXT)", null); if (!aResult.getErrorDescription().equals("not an error")) { allTransactionStatementsExecuted = false; errorMessage = aResult.getErrorDescription(); } } else { allTransactionStatementsExecuted = false; errorMessage = aResult.getErrorDescription(); } } catch (DataAccessException e) { e.printStackTrace(); errorMessage = e.getLocalizedMessage(); allTransactionStatementsExecuted = false; errorMessage = e.getLocalizedMessage(); } endTransaction(); if (allTransactionStatementsExecuted == false) { throw new DataAccessException("Error: Transaction failure. " + errorMessage); } /* * Do login and store context */ // Create a local instance of cookie store CookieStore cookieStore = new BasicCookieStore(); // Create local HTTP context localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); }
From source file:org.wso2.carbon.governance.registry.extensions.executors.APIPublishExecutor.java
/** * Publish the data to API Manager/*from w w w . j ava2 s . c o m*/ * * @param api API registry artifact. * @param xmlContent url Pattern value iterator. */ private void publishData(GenericArtifact api, OMElement xmlContent) throws RegistryException { if (apimEndpoint == null || apimUsername == null || apimPassword == null) { throw new RuntimeException(ExecutorConstants.APIM_LOGIN_UNDEFINED); } CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); Utils.authenticateAPIM(httpContext, apimEndpoint, apimUsername, apimPassword); String publishEndpoint = apimEndpoint + ExecutorConstants.APIM_PUBLISH_URL; // create a post request to addAPI. HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(publishEndpoint); // Request parameters and other properties. List<NameValuePair> params = getRequestParameters(api, xmlContent); if (api.getAttribute(ExecutorConstants.SERVICE_ENDPOINT_URL) != null && api.getAttribute(ExecutorConstants.SERVICE_ENDPOINT_URL).isEmpty()) { log.warn(ExecutorConstants.EMPTY_ENDPOINT); } try { httppost.setEntity(new UrlEncodedFormEntity(params, ExecutorConstants.DEFAULT_CHAR_ENCODING)); HttpResponse response = httpclient.execute(httppost, httpContext); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } } catch (ClientProtocolException e) { throw new RegistryException(ExecutorConstants.APIM_POST_REQ_FAIL, e); } catch (UnsupportedEncodingException e) { throw new RegistryException(ExecutorConstants.ENCODING_FAIL, e); } catch (IOException e) { throw new RegistryException(ExecutorConstants.APIM_POST_REQ_FAIL, e); } }
From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.APIDeleteExecutor.java
private boolean deleteAPIFromAPIM(GenericArtifact genericArtifact, String serviceName) throws GovernanceException { if (apimEndpoint == null || apimUsername == null || apimPassword == null) { String msg = ExecutorConstants.APIM_LOGIN_UNDEFINED; throw new RuntimeException(msg + "API delete might fail"); }//from ww w .j a va 2 s.com CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // APIUtils apiUtils = new APIUtils(); authenticateAPIM(httpContext); String addAPIendpoint = apimEndpoint + ExecutorConstants.APIM_REMOVE_URL; // create a post request to addAPI. HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(addAPIendpoint); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair(API_ACTION, "removeAPI")); params.add(new BasicNameValuePair(API_NAME, serviceName)); params.add(new BasicNameValuePair(API_PROVIDER, apimUsername)); params.add(new BasicNameValuePair(API_VERSION, genericArtifact.getAttribute("overview_version"))); ResponseAPIM responseAPIM = callAPIMToPublishAPI(httpclient, httppost, params, httpContext); if (responseAPIM.getError().equalsIgnoreCase(Constants.TRUE_CONSTANT)) { throw new RuntimeException( "Error occured while deleting the api from API Manager. " + responseAPIM.getMessage()); } return true; }
From source file:com.appassit.http.AndroidHttpClient.java
private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) { this.delegate = new DefaultHttpClient(ccm, params) { @Override//from www.j a v a 2s . c o m protected BasicHttpProcessor createHttpProcessor() { // Add interceptor to prevent making requests from main thread. BasicHttpProcessor processor = super.createHttpProcessor(); processor.addRequestInterceptor(sThreadCheckInterceptor); processor.addRequestInterceptor(new CurlLogger()); return processor; } @Override protected HttpContext createHttpContext() { // Same as DefaultHttpClient.createHttpContext() minus the // cookie store. HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes()); context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs()); context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider()); context.setAttribute(ClientContext.COOKIE_STORE, getCookieStore()); return context; } }; }
From source file:de.micromata.genome.tpsb.soapui.DelegateToSoapUiTestBuilderHttpClientRequestTransport.java
@Override public Response sendRequest(SubmitContext submitContext, Request request) throws Exception { boolean useSuper = false; if (useSuper == true) { return super.sendRequest(submitContext, request); }/* www .j a v a 2 s. co m*/ AbstractHttpRequestInterface<?> httpRequest = (AbstractHttpRequestInterface<?>) request; RequestMethod rm = httpRequest.getMethod(); ExtendedHttpMethod httpMethod; switch (rm) { case POST: { ExtendedPostMethod extendedPostMethod = new ExtendedPostMethod(); extendedPostMethod.setAfterRequestInjection(httpRequest.getAfterRequestInjection()); httpMethod = extendedPostMethod; break; } case GET: { ExtendedGetMethod extendedGetMethod = new ExtendedGetMethod(); // extendedGetMethod.setAfterRequestInjection(httpRequest.getAfterRequestInjection()); httpMethod = extendedGetMethod; break; } default: throw new IllegalArgumentException("Unsupported HTTP methd: " + rm); } HttpClientSupport.SoapUIHttpClient httpClient = HttpClientSupport.getHttpClient(); boolean createdContext = false; HttpContext httpContext = (HttpContext) submitContext.getProperty(SubmitContext.HTTP_STATE_PROPERTY); if (httpContext == null) { httpContext = new BasicHttpContext(); submitContext.setProperty(SubmitContext.HTTP_STATE_PROPERTY, httpContext); createdContext = true; // always use local cookie store so we don't share cookies with other threads/executions/requests CookieStore cookieStore = new BasicCookieStore(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); } String localAddress = System.getProperty("soapui.bind.address", httpRequest.getBindAddress()); if (localAddress == null || localAddress.trim().length() == 0) { localAddress = SoapUI.getSettings().getString(HttpSettings.BIND_ADDRESS, null); } org.apache.http.HttpResponse httpResponse = null; if (localAddress != null && localAddress.trim().length() > 0) { try { httpMethod.getParams().setParameter(ConnRoutePNames.LOCAL_ADDRESS, InetAddress.getByName(localAddress)); } catch (Exception e) { SoapUI.logError(e, "Failed to set localAddress to [" + localAddress + "]"); } } Map<String, String> httpRequestParameter = new HashMap<>(); if (httpRequest instanceof HttpTestRequest) { HttpTestRequest tr = (HttpTestRequest) httpRequest; for (String key : tr.getParams().keySet()) { RestParamProperty val = tr.getParams().get(key); String sval = val.getValue(); sval = PropertyExpander.expandProperties(submitContext, sval); httpRequestParameter.put(key, sval); } } submitContext.removeProperty(RESPONSE); submitContext.setProperty(HTTP_METHOD, httpMethod); submitContext.setProperty(POST_METHOD, httpMethod); submitContext.setProperty(HTTP_CLIENT, httpClient); submitContext.setProperty(REQUEST_CONTENT, httpRequest.getRequestContent()); submitContext.setProperty(WSDL_REQUEST, httpRequest); submitContext.setProperty(RESPONSE_PROPERTIES, new StringToStringMap()); List<RequestFilter> filters = getFilters(); for (RequestFilter filter : filters) { filter.filterRequest(submitContext, httpRequest); } try { Settings settings = httpRequest.getSettings(); // custom http headers last so they can be overridden StringToStringsMap headers = httpRequest.getRequestHeaders(); // first remove so we don't get any unwanted duplicates for (String header : headers.keySet()) { httpMethod.removeHeaders(header); } // now add for (String header : headers.keySet()) { for (String headerValue : headers.get(header)) { headerValue = PropertyExpander.expandProperties(submitContext, headerValue); httpMethod.addHeader(header, headerValue); } } // do request WsdlProject project = (WsdlProject) ModelSupport.getModelItemProject(httpRequest); WssCrypto crypto = null; if (project != null && project.getWssContainer() != null) { crypto = project.getWssContainer().getCryptoByName( PropertyExpander.expandProperties(submitContext, httpRequest.getSslKeystore())); } if (crypto != null && WssCrypto.STATUS_OK.equals(crypto.getStatus())) { httpMethod.getParams().setParameter(SoapUIHttpRoute.SOAPUI_SSL_CONFIG, crypto.getSource() + " " + crypto.getPassword()); } // dump file? httpMethod.setDumpFile(PathUtils.expandPath(httpRequest.getDumpFile(), (AbstractWsdlModelItem<?>) httpRequest, submitContext)); // include request time? if (settings.getBoolean(HttpSettings.INCLUDE_REQUEST_IN_TIME_TAKEN)) { httpMethod.initStartTime(); } if (httpMethod.getMetrics() != null) { httpMethod.getMetrics().setHttpMethod(httpMethod.getMethod()); PrivateBeanUtils.invokeMethod(this, "captureMetrics", httpMethod, httpClient); httpMethod.getMetrics().getTotalTimer().start(); } // submit! httpResponse = execute(submitContext, httpMethod, httpContext, httpRequestParameter); if (httpMethod.getMetrics() != null) { httpMethod.getMetrics().getReadTimer().stop(); httpMethod.getMetrics().getTotalTimer().stop(); } // if (isRedirectResponse(httpResponse.getStatusLine().getStatusCode()) && httpRequest.isFollowRedirects()) { // if (httpResponse.getEntity() != null) { // EntityUtils.consume(httpResponse.getEntity()); // } // // ExtendedGetMethod returnMethod = followRedirects(httpClient, 0, httpMethod, httpResponse, httpContext); // httpMethod = returnMethod; // submitContext.setProperty(HTTP_METHOD, httpMethod); // } } catch (Throwable t) { // NOSONAR "Illegal Catch" framework httpMethod.setFailed(t); if (t instanceof Exception) { throw (Exception) t; } SoapUI.logError(t); throw new Exception(t); } finally { if (!httpMethod.isFailed()) { if (httpMethod.getMetrics() != null) { if (httpMethod.getMetrics().getReadTimer().getStop() == 0) { httpMethod.getMetrics().getReadTimer().stop(); } if (httpMethod.getMetrics().getTotalTimer().getStop() == 0) { httpMethod.getMetrics().getTotalTimer().stop(); } } } else { httpMethod.getMetrics().reset(); httpMethod.getMetrics().setTimestamp(System.currentTimeMillis()); // captureMetrics(httpMethod, httpClient); } for (int c = filters.size() - 1; c >= 0; c--) { RequestFilter filter = filters.get(c); filter.afterRequest(submitContext, httpRequest); } if (!submitContext.hasProperty(RESPONSE)) { createDefaultResponse(submitContext, httpRequest, httpMethod); } Response response = (Response) submitContext.getProperty(BaseHttpRequestTransport.RESPONSE); StringToStringMap responseProperties = (StringToStringMap) submitContext .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES); for (String key : responseProperties.keySet()) { response.setProperty(key, responseProperties.get(key)); } if (createdContext) { submitContext.setProperty(SubmitContext.HTTP_STATE_PROPERTY, null); } } return (Response) submitContext.getProperty(BaseHttpRequestTransport.RESPONSE); }
From source file:com.farmafene.commons.cas.LoginTGT.java
/** * @return/* ww w.j ava2s . co m*/ */ private LoginTicketContainer processInitRequest() { LoginTicketContainer processInitRequest = null; HttpResponse res = null; HttpClientFactory f = new HttpClientFactory(); f.setLoginURL(getCasServerURL()); DefaultHttpClient client = null; client = f.getClient(); HttpContext localContext = new BasicHttpContext(); BasicCookieStore cs = new BasicCookieStore(); HttpPost post = new HttpPost(getURL("login")); client.setCookieStore(cs); localContext.setAttribute(ClientContext.COOKIE_STORE, cs); try { res = client.execute(post, localContext); } catch (ClientProtocolException e) { AuriusAuthException ex = new AuriusAuthException("ClientProtocolException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } catch (IOException e) { AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } InputStream is = null; try { is = res.getEntity().getContent(); } catch (IllegalStateException e) { AuriusAuthException ex = new AuriusAuthException("IllegalStateException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } catch (IOException e) { AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } byte[] buffer = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int leido = 0; try { while ((leido = is.read(buffer)) > 0) { baos.write(buffer, 0, leido); } } catch (IOException e) { AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } String html = baos.toString().replace("\n", "").replace("\r", ""); /* * Buscamos los tipos de "input" */ String[] inputs = html.split("<\\s*input\\s+"); processInitRequest = new LoginTicketContainer(); for (String input : inputs) { String value = null; if (null != (value = search(input, "lt"))) { processInitRequest.setLoginTicket(value); } else if (null != (value = search(input, "execution"))) { processInitRequest.setExecution(value); } } /* * Obtenemos la session Cookie */ if (client.getCookieStore().getCookies() != null) { for (Cookie c : client.getCookieStore().getCookies()) { if (getJSessionCookieName().equals(c.getName())) { processInitRequest.setSessionCookie(c); } } } if (null != baos) { try { baos.close(); } catch (IOException e) { logger.error("Error al cerrar el OutputStream", e); } } if (null != is) { try { is.close(); } catch (IOException e) { logger.error("Error al cerrar el InputStream", e); } } if (logger.isDebugEnabled()) { logger.debug("Obtenido: " + processInitRequest); } return processInitRequest; }
From source file:intelligentWebAlgorithms.util.internet.crawling.transport.http.HTTPTransport.java
public void init() { P.println("Initializing HTTPTransport ..."); httpclient = new DefaultHttpClient(); // Create a local instance of cookie store cookieStore = new BasicCookieStore(); // Create local HTTP context localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); // httpclient.getHttpConnectionManager().getParams().setSoTimeout(30000); // httpclient.setState(initialState); // httpclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); ///*w ww . j a v a 2s. c om*/ // //httpclient.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, // Boolean.TRUE); // // // Set default number of connections per host to 1 // httpclient.getHttpConnectionManager(). // getParams().setMaxConnectionsPerHost( // HostConfiguration.ANY_HOST_CONFIGURATION, 1); // // Set max for total number of connections // httpclient.getHttpConnectionManager().getParams().setMaxTotalConnections(10); }
From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.ApiStore2Executor.java
/** * Update the APIM DB for the published API. * * @param resource//w w w.j av a 2s. c om * @param serviceName */ private boolean publishDataToAPIM(Resource resource, String serviceName) throws GovernanceException { boolean valid = true; if (apimEndpoint == null || apimUsername == null || apimPassword == null || apimEnv == null) { throw new GovernanceException(ExecutorConstants.APIM_LOGIN_UNDEFINED); } CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); String sessionCookie = APIUtils.authenticateAPIM_2(httpContext, apimEndpoint, apimUsername, apimPassword); String addAPIendpoint = apimEndpoint + Constants.APIM_2_0_0_ENDPOINT; try { // create a post request to addAPI. HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(addAPIendpoint); httppost.setHeader("Cookie", "JSESSIONID=" + sessionCookie); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(); addParameters(params, resource, serviceName); LOG.info(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE)); APIUtils.callAPIMToPublishAPI2(httpclient, httppost, params, httpContext); } catch (Exception e) { LOG.error("Exception occurred while publishing to APIM", e); throw new GovernanceException(e.getMessage(), e); } return valid; }
From source file:MinimalServerTest.java
License:asdf
public void testStartOfSession() throws Exception { //Create client HttpClient client = new DefaultHttpClient(); HttpPost mockRequest = new HttpPost("http://localhost:5555/login"); CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); mockRequest.setHeader("Content-type", "application/x-www-form-urlencoded"); //Add parameters List<NameValuePair> urlParameters = new ArrayList<>(); urlParameters.add(new BasicNameValuePair("email", "test")); urlParameters.add(new BasicNameValuePair("deviceUID", "BD655C43-3A73-4DFB-AA1F-074A4F0B0DCE")); mockRequest.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8")); //Execute the request HttpResponse mockResponse = client.execute(mockRequest, httpContext); //Test if normal login is successful BufferedReader rd = new BufferedReader(new InputStreamReader(mockResponse.getEntity().getContent())); rd.close();// w w w .j av a 2 s . c o m URL newURL = new URL("http://127.0.0.1:5555/start"); final Request request = Request.Post(newURL.toURI()); ExecutorService executor = Executors.newFixedThreadPool(1); Async async = Async.newInstance().use(executor); Future<Content> future = async.execute(request, new FutureCallback<Content>() { @Override public void failed(final Exception e) { e.printStackTrace(); } @Override public void completed(final Content content) { System.out.println("Done"); } @Override public void cancelled() { } }); server.startSession(); String asyncResponse = future.get().asString(); JSONObject jsonTest = new JSONObject(); // "status": "1", //0 if the app should keep waiting, 1 for success, 2 if the votong session has fininshed // "sessionType": "normal", //alternatively Yes/No or winner // "rangeBottom": "0", // "rangeTop": "15", // "description": "image discription here", // "comments": "True", //True if comments are allowed, False if not // "imgPath": "path/to/image.jpg" //the path where the image resides on the server jsonTest.put("status", "1"); jsonTest.put("sessionType", "normal"); jsonTest.put("rangeBottom", 0); jsonTest.put("rangeTop", 10); jsonTest.put("description", "helo"); jsonTest.put("comments", "true"); jsonTest.put("imgPath", "temp/1.jpg"); assertEquals("Testing if login was correctly failed due to incorrect username", jsonTest.toString(), asyncResponse); }