List of usage examples for org.apache.http.protocol HttpContext setAttribute
void setAttribute(String str, Object obj);
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();/*from w w w. ja v a 2 s .c om*/ 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); }
From source file:com.allblacks.utils.web.HttpUtil.java
/** * Gets data from URL as byte[] throws {@link RuntimeException} If anything * goes wrong// w ww. j av a 2 s. co m * * @return The content of the URL as a byte[] * @throws java.io.IOException */ public byte[] getDataAsByteArray(String url, CredentialsProvider cp) throws IOException { HttpClient httpClient = getNewHttpClient(); URL urlObj = new URL(url); HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol()); HttpContext credContext = new BasicHttpContext(); credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp); HttpGet job = new HttpGet(url); HttpResponse response = httpClient.execute(host, job, credContext); HttpEntity entity = response.getEntity(); return EntityUtils.toByteArray(entity); }
From source file:com.allblacks.utils.web.HttpUtil.java
/** * Gets data from URL as char[] throws {@link RuntimeException} If anything * goes wrong/* ww w. ja v a 2s . c om*/ * * @param url the url from which to retrieve the data. * @param cp the credential provider * * @return The content of the URL as a char[] * @throws java.io.IOException */ public synchronized char[] getDataAsCharArray(String url, CredentialsProvider cp) throws IOException { HttpClient httpClient = getNewHttpClient(); URL urlObj = new URL(url); HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol()); HttpContext credContext = new BasicHttpContext(); credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp); HttpGet job = new HttpGet(url); HttpResponse response = httpClient.execute(host, job, credContext); HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity).toCharArray(); }
From source file:de.stkl.gbgvertretungsplan.sync.SyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {/*from ww w .j a v a 2 s . c o m*/ //android.os.Debug.waitForDebugger(); reportStatus(Sync.SYNC_STATUS.START); String username = account.name; String password = mAccountManager.getPassword(account); AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null); CookieStore cookies = new BasicCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookies); boolean error = false; try { String dataTypeS = mAccountManager.getUserData(account, de.stkl.gbgvertretungsplan.values.Account.PROP_TYPE); int dataType = dataTypeS == null ? 0 : Integer.valueOf(dataTypeS); if (!mComInterface.login(httpClient, localContext, username, password, dataType)) throw new LoginException(); // 4. request and save pages (today + tomorrow) requestAndSaveDay(httpClient, localContext, 0, dataType); // today requestAndSaveDay(httpClient, localContext, 1, dataType); // and tomorrow if (!logout(httpClient, localContext)) throw new CommunicationInterface.LogoutException(); } catch (IOException e) { error = true; } catch (CommunicationInterface.CommunicationException e) { ErrorReporter.reportError(e, mContext); error = true; } catch (CommunicationInterface.ParsingException e) { ErrorReporter.reportError(e, mContext); error = true; } catch (LoginException e) { error = true; } catch (CommunicationInterface.LogoutException e) { ErrorReporter.reportError(e, mContext); error = true; // generic exceptions like NullPointerException should also indicate a failed Sync } catch (Exception e) { error = true; } finally { if (error) reportStatus(Sync.SYNC_STATUS.ERROR); else reportStatus(Sync.SYNC_STATUS.OK); httpClient.close(); } }
From source file:org.mobicents.slee.ra.httpclient.nio.ra.HttpClientNIORequestActivityImpl.java
private HttpContext processHttpContext(HttpContext context) { // Maintains HttpSession on server side if (context == null) { context = new BasicHttpContext(); }/*from w w w. ja v a2 s. c o m*/ if (context.getAttribute(ClientContext.COOKIE_STORE) == null) { BasicCookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); } return context; }
From source file:io.mandrel.requests.http.ApacheHttpRequester.java
public HttpContext prepareContext(Spider spider) { CookieStore store = new BasicCookieStore(); if (cookies() != null) cookies().forEach(cookie -> { BasicClientCookie theCookie = new BasicClientCookie(cookie.name(), cookie.value()); theCookie.setDomain(cookie.domain()); theCookie.setPath(cookie.path()); theCookie.setExpiryDate(new Date(cookie.expires())); theCookie.setSecure(cookie.secure()); store.addCookie(theCookie);/*w ww.java2 s. c o m*/ }); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, store); return localContext; }
From source file:org.callimachusproject.server.AccessLog.java
private String getForensicId(HttpContext context) { String id = (String) context.getAttribute(FORENSIC_ATTR); if (id == null) { id = uid + seq.getAndIncrement(); context.setAttribute(FORENSIC_ATTR, id); }//from w w w . java 2 s . co m return id; }
From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.RestServiceToAPIExecutor.java
/** * Update the APIM DB for the published API. * * @param api/*from ww w .j av a2 s. c o m*/ * @param serviceName */ private void publishDataToAPIM(GenericArtifact api, String serviceName) throws GovernanceException { if (apimEndpoint == null || apimUsername == null || apimPassword == null) { String msg = "APIManager endpoint URL or credentials are not defined"; log.error(msg); throw new RuntimeException(msg + "API Publish might fail"); } CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); authenticateAPIM(httpContext); String addAPIendpoint = apimEndpoint + "publisher/site/blocks/item-add/ajax/add.jag"; try { // 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<NameValuePair>(); for (String key : api.getAttributeKeys()) { if (log.isDebugEnabled()) { log.error(key + " : " + api.getAttribute(key)); } } if (api.getAttribute("overview_endpointURL") != null && api.getAttribute("overview_endpointURL").isEmpty()) { String msg = "Service Endpoint is a must attribute to create an API definition at the APIStore.Publishing at gateway might fail"; log.warn(msg); } //params.add(new BasicNameValuePair(API_ENDPOINT, api.getAttribute("overview_endpointURL"))); params.add(new BasicNameValuePair(API_ACTION, API_ADD_ACTION)); params.add(new BasicNameValuePair(API_NAME, serviceName)); params.add(new BasicNameValuePair(API_CONTEXT, serviceName)); params.add(new BasicNameValuePair(API_VERSION, api.getAttribute(SERVICE_VERSION))); params.add(new BasicNameValuePair("API_PROVIDER", CarbonContext.getThreadLocalCarbonContext().getUsername())); params.add(new BasicNameValuePair(API_TIER, defaultTier)); params.add(new BasicNameValuePair(API_URI_PATTERN, DEFAULT_URI_PATTERN)); params.add(new BasicNameValuePair(API_URI_HTTP_METHOD, DEFAULT_HTTP_VERB)); params.add(new BasicNameValuePair(API_URI_AUTH_TYPE, DEFAULT_AUTH_TYPE)); params.add(new BasicNameValuePair(API_VISIBLITY, DEFAULT_VISIBILITY)); params.add(new BasicNameValuePair(API_THROTTLING_TIER, apiThrottlingTier)); String[] endPoints = api.getAttributes(Constants.ENDPOINTS_ENTRY); if (endPoints != null && endPoints.length > 0) { List<String> endPointsList = Arrays.asList(endPoints); if (endPointsList.size() > 0) { String endpointConfigJson = "{\"production_endpoints\":{\"url\":\"" + getEnvironmentUrl(endPointsList) + "\",\"config\":null},\"endpoint_type\":\"http\"}"; params.add(new BasicNameValuePair(Constants.ENDPOINT_CONFIG, endpointConfigJson)); } else { String msg = "Endpoint is a must attribute to create an API definition at the APIStore"; throw new GovernanceException(msg); } } else { String msg = "Endpoint is a must attribute to create an API definition at the APIStore"; throw new GovernanceException(msg); } httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = httpclient.execute(httppost, httpContext); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } } catch (Exception e) { log.error("Error in updating APIM", e); throw new GovernanceException("Error in updating APIM", e); } // after publishing update the lifecycle status //updateStatus(service, serviceName, httpContext); }
From source file:cz.zcu.kiv.eegdatabase.logic.util.BasicAuthHttpClient.java
@Override protected HttpContext createHttpContext() { HttpContext context = super.createHttpContext(); AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); authCache.put(targetHost, basicAuth); context.setAttribute(ClientContext.AUTH_CACHE, authCache); return context; }