List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
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. ja v a 2s . co 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:com.nineash.hutsync.client.NetworkUtilities.java
/** * Connects to the SampleSync test server, authenticates the provided * username and password.// ww w .j a v a 2 s . com * * @param username The server account username * @param password The server account password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String password, Context context) { try { final HttpResponse resp; final HttpResponse init_resp; final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); DefaultHttpClient hClient = getHttpClient(context); final HttpPost init_post = new HttpPost(BASE_URL); final int first_cookies; final ArrayList<SerializableCookie> saveCooks = new ArrayList<SerializableCookie>(); BasicCookieStore bcs = new BasicCookieStore(); params.add(new BasicNameValuePair(PARAM_USERNAME, username)); params.add(new BasicNameValuePair(PARAM_PASSWORD, password)); params.add(new BasicNameValuePair(PARAM_REMEMBER, "yes")); init_resp = hClient.execute(init_post); String respString = EntityUtils.toString(init_resp.getEntity()); List<Cookie> cookies = hClient.getCookieStore().getCookies(); if (cookies.isEmpty()) { Log.e(TAG, "No cookies gathered first time round"); } first_cookies = cookies.size(); if (first_cookies != 2) { Log.e(TAG, "Should be two cookie to start off with"); } Document doc = Jsoup.parse(respString); Elements hiddens = doc.select("div.homepage input[type=hidden]"); for (Element hidden : hiddens) { params.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value"))); } final HttpEntity entity; try { entity = new UrlEncodedFormEntity(params); } catch (final UnsupportedEncodingException e) { // this should never happen. throw new IllegalStateException(e); } Log.i(TAG, "Authenticating to: " + AUTH_URI); final HttpPost post = new HttpPost(AUTH_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); resp = hClient.execute(post); String authToken = null; if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //set authtoken here cookies = hClient.getCookieStore().getCookies(); if (cookies.isEmpty()) { Log.e(TAG, "No cookies gathered"); } else { if (cookies.size() == first_cookies + 2) { //we get two new cookies when we log in for (int i = 0; i < cookies.size(); i++) { Cookie cur_cookie = cookies.get(i); if (cur_cookie.isPersistent()) { saveCooks.add(new SerializableCookie(cur_cookie)); } } authToken = toString(saveCooks); } } } if ((authToken != null) && (authToken.length() > 0)) { Log.v(TAG, "Successful authentication"); return authToken; } else { Log.e(TAG, "Error authenticating" + resp.getStatusLine()); return null; } } catch (final IOException e) { Log.e(TAG, "IOException when getting authtoken", e); return null; } finally { Log.v(TAG, "getAuthtoken completing"); } }
From source file:bear.plugins.java.JenkinsCache.java
public static File download(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri, String user, String pass) { try {/*w ww . j a v a 2 s . c o m*/ Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion); if (!optional.isPresent()) { throw new RuntimeException("could not find: " + jdkVersion); } String uri = optional.get().filepath; SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); Scheme httpScheme = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); schemeRegistry.register(httpsScheme); schemeRegistry.register(httpScheme); DefaultHttpClient httpClient = new DefaultHttpClient( new PoolingClientConnectionManager(schemeRegistry)); CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("gpw_e24", "."); cookie.setDomain("oracle.com"); cookie.setPath("/"); cookie.setSecure(true); cookieStore.addCookie(cookie); httpClient.setCookieStore(cookieStore); HttpPost httppost = new HttpPost("https://login.oracle.com"); httppost.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8")); HttpResponse response = httpClient.execute(httppost); int code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("unable to auth: " + code); } // closes the single connection // EntityUtils.consumeQuietly(response.getEntity()); httppost = new HttpPost(uri); httppost.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8")); response = httpClient.execute(httppost); code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("to download: " + uri); } File file = new File(tempDestDir, optional.get().name); HttpEntity entity = response.getEntity(); final long length = entity.getContentLength(); final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file)); System.out.printf("Downloading %s to %s...%n", uri, file); Thread progressThread = new Thread(new Runnable() { double lastProgress; @Override public void run() { while (!Thread.currentThread().isInterrupted()) { long copied = os.getCount(); double progress = copied * 100D / length; if (progress != lastProgress) { System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1)); } lastProgress = progress; try { Thread.sleep(500); } catch (InterruptedException e) { break; } } } }, "progressThread"); progressThread.start(); ByteStreams.copy(entity.getContent(), os); progressThread.interrupt(); System.out.println("Download complete."); return file; } catch (Exception e) { throw Exceptions.runtime(e); } }
From source file:gov.nih.nci.firebird.commons.selenium2.util.FileDownloadUtils.java
private static void setupCookies(DefaultHttpClient client, WebDriver driver) { CookieStore cookieStore = new BasicCookieStore(); for (Cookie webDriverCookie : driver.manage().getCookies()) { cookieStore.addCookie(translateCookie(webDriverCookie)); }/*from ww w.ja v a 2s.c o m*/ client.setCookieStore(cookieStore); }
From source file:microsoft.exchange.webservices.data.core.ExchangeServiceBase.java
/** * (Re)initializes the HttpContext object. This removes any existing state (mainly cookies). Use an own * cookie store, instead of the httpClient's global store, so cookies get reset on reinitialization *///from ww w .j a v a 2 s. c o m private void initializeHttpContext() { CookieStore cookieStore = new BasicCookieStore(); httpContext = HttpClientContext.create(); httpContext.setCookieStore(cookieStore); }
From source file:org.wso2.carbon.governance.registry.extensions.executors.APIPublishExecutor.java
/** * Publish the data to API Manager/* w ww . 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:com.google.acre.script.AcreFetch.java
@SuppressWarnings("boxing") public void fetch(boolean system, String response_encoding, boolean log_to_user, boolean no_redirect) { if (request_url.length() > 2047) { throw new AcreURLFetchException("fetching URL failed - url is too long"); }//from w w w. ja v a 2 s .c o m DefaultHttpClient client = new DefaultHttpClient(_connectionManager, null); HttpParams params = client.getParams(); // pass the deadline down to the invoked service. // this will be ignored unless we are fetching from another // acre server. // note that we may send a deadline that is already passed: // it's not our job to throw here since we don't know how // the target service will interpret the quota header. // NOTE: this is done *after* the user sets the headers to overwrite // whatever settings they might have tried to change for this value // (which could be a security hazard) long sub_deadline = (HostEnv.LIMIT_EXECUTION_TIME) ? _deadline - HostEnv.SUBREQUEST_DEADLINE_ADVANCE : System.currentTimeMillis() + HostEnv.ACRE_URLFETCH_TIMEOUT; int reentries = _reentries + 1; request_headers.put(HostEnv.ACRE_QUOTAS_HEADER, "td=" + sub_deadline + ",r=" + reentries); // if this is not an internal call, we need to invoke the call thru a proxy if (!_internal) { // XXX No sense wasting the resources to gzip inside the network. // XXX seems that twitter gets upset when we do this /* if (!request_headers.containsKey("accept-encoding")) { request_headers.put("accept-encoding", "gzip"); } */ String proxy_host = Configuration.Values.HTTP_PROXY_HOST.getValue(); int proxy_port = -1; if (!(proxy_host.length() == 0)) { proxy_port = Configuration.Values.HTTP_PROXY_PORT.getInteger(); HttpHost proxy = new HttpHost(proxy_host, proxy_port, "http"); params.setParameter(AllClientPNames.DEFAULT_PROXY, proxy); } } params.setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); // in msec long timeout = _deadline - System.currentTimeMillis(); if (timeout < 0) timeout = 0; params.setParameter(AllClientPNames.CONNECTION_TIMEOUT, (int) timeout); params.setParameter(AllClientPNames.SO_TIMEOUT, (int) timeout); // we're not streaming the request so this should be a win. params.setParameter(AllClientPNames.TCP_NODELAY, true); // reuse an existing socket if it is in TIME_WAIT state. params.setParameter(AllClientPNames.SO_REUSEADDR, true); // set the encoding of our POST payloads to UTF-8 params.setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, "UTF-8"); BasicCookieStore cstore = new BasicCookieStore(); for (AcreCookie cookie : request_cookies.values()) { cstore.addCookie(cookie.toClientCookie()); } client.setCookieStore(cstore); HttpRequestBase method; HashMap<String, String> logmsg = new HashMap<String, String>(); logmsg.put("Method", request_method); logmsg.put("URL", request_url); params.setParameter(AllClientPNames.HANDLE_REDIRECTS, !no_redirect); logmsg.put("Redirect", Boolean.toString(!no_redirect)); try { if (request_method.equals("GET")) { method = new HttpGet(request_url); } else if (request_method.equals("POST")) { method = new HttpPost(request_url); } else if (request_method.equals("HEAD")) { method = new HttpHead(request_url); } else if (request_method.equals("PUT")) { method = new HttpPut(request_url); } else if (request_method.equals("DELETE")) { method = new HttpDelete(request_url); } else if (request_method.equals("PROPFIND")) { method = new HttpPropFind(request_url); } else { throw new AcreURLFetchException("Failed: unsupported (so far) method " + request_method); } method.getParams().setBooleanParameter(AllClientPNames.USE_EXPECT_CONTINUE, false); } catch (java.lang.IllegalArgumentException e) { throw new AcreURLFetchException("Unable to fetch URL; this is most likely an issue with URL encoding."); } catch (java.lang.IllegalStateException e) { throw new AcreURLFetchException("Unable to fetch URL; possibly an illegal protocol?"); } StringBuilder request_header_log = new StringBuilder(); for (Map.Entry<String, String> header : request_headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); // XXX should suppress cookie headers? // content-type and length? if ("content-type".equalsIgnoreCase(key)) { Matcher m = contentTypeCharsetPattern.matcher(value); if (m.find()) { content_type = m.group(1); content_type_charset = m.group(2); } else { content_type_charset = "utf-8"; } method.addHeader(key, value); } else if ("content-length".equalsIgnoreCase(key)) { // ignore user-supplied content-length, which is // probably wrong due to chars vs bytes and is // redundant anyway ArrayList<String> msg = new ArrayList<String>(); msg.add("User-supplied content-length header is ignored"); _acre_response.log("warn", msg); } else if ("user-agent".equalsIgnoreCase(key)) { params.setParameter(AllClientPNames.USER_AGENT, value); } else { method.addHeader(key, value); } if (!("x-acre-auth".equalsIgnoreCase(key))) { request_header_log.append(key + ": " + value + "\r\n"); } } logmsg.put("Headers", request_header_log.toString()); // XXX need more detailed error checking if (method instanceof HttpEntityEnclosingRequestBase && request_body != null) { HttpEntityEnclosingRequestBase em = (HttpEntityEnclosingRequestBase) method; try { if (request_body instanceof String) { StringEntity ent = new StringEntity((String) request_body, content_type_charset); em.setEntity(ent); } else if (request_body instanceof JSBinary) { ByteArrayEntity ent = new ByteArrayEntity(((JSBinary) request_body).get_data()); em.setEntity(ent); } } catch (UnsupportedEncodingException e) { throw new AcreURLFetchException( "Failed to fetch URL. " + " - Unsupported charset: " + content_type_charset); } } if (!system && log_to_user) { ArrayList<Object> msg = new ArrayList<Object>(); msg.add("urlfetch request"); msg.add(logmsg); _acre_response.log("debug", msg); } _logger.info("urlfetch.request", logmsg); long startTime = System.currentTimeMillis(); try { // this sends the http request and waits HttpResponse hres = client.execute(method); status = hres.getStatusLine().getStatusCode(); HashMap<String, String> res_logmsg = new HashMap<String, String>(); res_logmsg.put("URL", request_url); res_logmsg.put("Status", ((Integer) status).toString()); Header content_type_header = null; // translate response headers StringBuilder response_header_log = new StringBuilder(); Header[] rawheaders = hres.getAllHeaders(); for (Header rawheader : rawheaders) { String headername = rawheader.getName().toLowerCase(); if (headername.equalsIgnoreCase("content-type")) { content_type_header = rawheader; // XXX should strip everything after ; content_type = rawheader.getValue(); // XXX don't set content_type_parameters, deprecated? } else if (headername.equalsIgnoreCase("x-metaweb-cost")) { _costCollector.merge(rawheader.getValue()); } else if (headername.equalsIgnoreCase("x-metaweb-tid")) { res_logmsg.put("ITID", rawheader.getValue()); } headers.put(headername, rawheader.getValue()); response_header_log.append(headername + ": " + rawheader.getValue() + "\r\n"); } res_logmsg.put("Headers", response_header_log.toString()); if (!system && log_to_user) { ArrayList<Object> msg = new ArrayList<Object>(); msg.add("urlfetch response"); msg.add(res_logmsg); _acre_response.log("debug", msg); } _logger.info("urlfetch.response", res_logmsg); // read cookies for (Cookie c : cstore.getCookies()) { cookies.put(c.getName(), new AcreCookie(c)); } // get body encoding String charset = null; if (content_type_header != null) { HeaderElement values[] = content_type_header.getElements(); if (values.length == 1) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } if (charset == null) charset = response_encoding; // read body HttpEntity ent = hres.getEntity(); if (ent != null) { InputStream res_stream = ent.getContent(); Header cenc = ent.getContentEncoding(); if (cenc != null && res_stream != null) { HeaderElement[] codecs = cenc.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { res_stream = new GZIPInputStream(res_stream); } } } long firstByteTime = 0; long endTime = 0; if (content_type != null && (content_type.startsWith("image/") || content_type.startsWith("application/octet-stream") || content_type.startsWith("multipart/form-data"))) { // HttpClient's InputStream doesn't support mark/reset, so // wrap it with one that does. BufferedInputStream bufis = new BufferedInputStream(res_stream); bufis.mark(2); bufis.read(); firstByteTime = System.currentTimeMillis(); bufis.reset(); byte[] data = IOUtils.toByteArray(bufis); endTime = System.currentTimeMillis(); body = new JSBinary(); ((JSBinary) body).set_data(data); try { if (res_stream != null) { res_stream.close(); } } catch (IOException e) { // ignore } } else if (res_stream == null || charset == null) { firstByteTime = endTime = System.currentTimeMillis(); body = ""; } else { StringWriter writer = new StringWriter(); Reader reader = new InputStreamReader(res_stream, charset); int i = reader.read(); firstByteTime = System.currentTimeMillis(); writer.write(i); IOUtils.copy(reader, writer); endTime = System.currentTimeMillis(); body = writer.toString(); try { reader.close(); writer.close(); } catch (IOException e) { // ignore } } long waitingTime = firstByteTime - startTime; long readingTime = endTime - firstByteTime; _logger.debug("urlfetch.timings", "waiting time: " + waitingTime + "ms"); _logger.debug("urlfetch.timings", "reading time: " + readingTime + "ms"); Statistics.instance().collectUrlfetchTime(startTime, firstByteTime, endTime); _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw", waitingTime) .collect((system) ? "asub" : "auub", waitingTime); } } catch (IllegalArgumentException e) { Throwable cause = e.getCause(); if (cause == null) cause = e; throw new AcreURLFetchException("failed to fetch URL. " + " - Request Error: " + cause.getMessage()); } catch (IOException e) { Throwable cause = e.getCause(); if (cause == null) cause = e; throw new AcreURLFetchException("Failed to fetch URL. " + " - Network Error: " + cause.getMessage()); } catch (RuntimeException e) { Throwable cause = e.getCause(); if (cause == null) cause = e; throw new AcreURLFetchException("Failed to fetch URL. " + " - Network Error: " + cause.getMessage()); } finally { method.abort(); } }
From source file:ca.nehil.rter.streamingapp.StreamingActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_streaming); poilist = new ArrayList<POI>(); /* Retrieve server URL from stored app values */ storedValues = getSharedPreferences(getString(R.string.sharedPreferences_filename), MODE_PRIVATE); server_url = storedValues.getString("server_url", "not-set"); /* Orientation listenever implementation to orient video */ myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) { @Override/*from w ww. ja v a 2s . co m*/ public void onOrientationChanged(int orientation) { int rotation = getWindowManager().getDefaultDisplay().getRotation(); if (rotation == Surface.ROTATION_270) { flipVideo = true; } else { flipVideo = false; } } }; myOrientationEventListener.enable(); /* Retrieve user auth data from cookie */ cookies = getSharedPreferences("RterUserCreds", MODE_PRIVATE); cookieEditor = cookies.edit(); setUsername = cookies.getString("Username", "not-set"); setRterCredentials = cookies.getString("RterCreds", "not-set"); if (setRterCredentials.equalsIgnoreCase("not-set") || setRterCredentials == null) { Log.e("PREFS", "Login Not successful, please restart"); } Log.d("PREFS", "Prefs ==> rter_Creds:" + setRterCredentials); URL serverURL = null; try { serverURL = new URL(server_url); CookieStore myCookieStore = new BasicCookieStore(); client.setCookieStore(myCookieStore); String[] credentials = setRterCredentials.split("=", 2); BasicClientCookie newCookie = new BasicClientCookie(credentials[0], credentials[1]); newCookie.setDomain(serverURL.getHost()); newCookie.setPath("/"); myCookieStore.addCookie(newCookie); mSensorSource = SensorSource.getInstance(this, GET_LOCATION_FROM_SERVER, serverURL, setRterCredentials, setUsername); POIs = new POIList(this, serverURL, setRterCredentials, mSensorSource); } catch (MalformedURLException e) { e.printStackTrace(); } overlay = new OverlayController(this, POIs, mSensorSource); // OpenGL overlay /* Get location */ Location location = mSensorSource.getLocation(); if (location != null) { lati = (float) (location.getLatitude()); longi = (float) (location.getLongitude()); } else { Toast toast = Toast.makeText(this, "Location not available", Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP, 0, 0); toast.show(); lati = (float) (45.505958f); // Hard coded location for testing purposes. longi = (float) (-73.576254f); } PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, CLASS_LABEL); mWakeLock.acquire(); /* Test, set desired orienation to north */ overlay.setDesiredOrientation(0.0f); }
From source file:com.feigdev.webcom.PersistentCookieStore.java
public BasicCookieStore getCookieStore() { BasicCookieStore cs = new BasicCookieStore(); for (Cookie cookie : getCookies()) { cs.addCookie(cookie);//from w w w . j a v a 2 s .com } return cs; }
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 w w w . j ava2 s . c om*/ 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; }