List of usage examples for org.apache.http.entity StringEntity getContent
public InputStream getContent() throws IOException
From source file:project.latex.balloon.writer.HttpDataWriter.java
void sendPostRequest(String rawString) throws IOException { String jsonString = getJsonStringFromRawData(rawString); CloseableHttpClient httpclient = HttpClients.createDefault(); StringEntity entity = new StringEntity(jsonString, ContentType.create("plain/text", Consts.UTF_8)); HttpPost httppost = new HttpPost(receiverUrl); httppost.addHeader("content-type", "application/json"); httppost.setEntity(entity);//from ww w .j a v a 2s .co m ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset)); StringBuilder stringBuilder = new StringBuilder(); String line = reader.readLine(); while (line != null) { stringBuilder.append(line); line = reader.readLine(); } return stringBuilder.toString(); } }; String responseString = httpclient.execute(httppost, responseHandler); logger.info(responseString); }
From source file:no.uka.findmyapp.android.rest.client.RestMethod.java
/** * Execute post./*from ww w . j a va 2 s .c o m*/ * * @param post the post * @param data the data * @return the string * @throws HTTPStatusException the hTTP status exception */ private String executePost(HttpPost post, String data) throws HTTPStatusException { try { StringEntity entity = new StringEntity(data, CHARSET); post.setEntity(entity); this.mClient = new DefaultHttpClient(); try { mConsumer.sign(post); } catch (OAuthMessageSignerException e) { Log.e(debug, e.getMessage()); return ""; } catch (OAuthExpectationFailedException e) { Log.e(debug, e.getMessage()); return ""; } catch (OAuthCommunicationException e) { Log.e(debug, e.getMessage()); return ""; } Log.v(debug, post.getURI().toString()); HttpResponse response = mClient.execute(post); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { this.throwHttpStatusException(status.getStatusCode()); } if (response != null) { response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(mStreamBuffer)) != -1) { content.write(mStreamBuffer, 0, readBytes); } // Return result from buffered stream return new String(content.toByteArray()); } } catch (UnsupportedEncodingException e) { Log.e(debug, "Unsupported encoding: " + e.getMessage()); return ""; } catch (IOException e) { Log.e(debug, "IOException: " + e.getMessage()); return ""; } catch (HTTPStatusException e) { throw e; } return null; }
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 .j av 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:org.forgerock.openam.authentication.modules.impersonation.ImpersonationModule.java
/** * {@inheritDoc}//from w w w .ja v a 2 s .co m */ @Override public int process(Callback[] callbacks, int state) throws LoginException { System.out.println("INSIDE process of ImpersonationModule, state: " + state); if (debug.messageEnabled()) { debug.message("ImpersonationModule::process state: " + state); } int nextState = ISAuthConstants.LOGIN_SUCCEED; switch (state) { case 4: System.out.println("state 4"); // error condition, show page throw new AuthLoginException("Incorrect authorization!"); case 1: substituteUIStrings(); //nextState = ISAuthConstants.LOGIN_SUCCEED; nextState = 2; break; case 3: userName = ((NameCallback) callbacks[0]).getName(); String userPassword = String.valueOf(((PasswordCallback) callbacks[1]).getPassword()); if (userPassword == null || userPassword.length() == 0) { if (debug.messageEnabled()) { debug.message("Impersonation.process: Password is null/empty"); } throw new InvalidPasswordException("amAuth", "invalidPasswd", null); } //store username password both in success and failure case storeUsernamePasswd(userName, userPassword); AMIdentityRepository idrepo = getAMIdentityRepository(getRequestOrg()); Callback[] idCallbacks = new Callback[2]; try { idCallbacks = callbacks; boolean success = idrepo.authenticate(idCallbacks); // proceed if admin authenticated if (success) { validatedUserID = null; // 1. Search for group membership if (checkGroupMembership.equalsIgnoreCase("true")) { AMIdentity amIdentity = getGroupIdentity(groupName); Set<String> attr = (Set<String>) amIdentity.getAttribute("uniqueMember"); Iterator<String> i = attr.iterator(); // check if sign on user is memberof group while (i.hasNext()) { try { String member = (String) i.next(); System.out.println("value of attribute: " + member); // check previously authenticated user is a memberof userName = (String) sharedState.get(getUserKey()); System.out.println("userName to check: " + userName); if (member.indexOf(userName) != -1) { System.out.println("match found! admin: " + userName + " allowed to impersonate user: " + userResponse); // for sanity, ensure the supplied userid is a valid one try { validatedUserID = userResponse; // create session for the userid provided by admin AMIdentity impersonatedId = getIdentity(validatedUserID); // optionally, we default to LOGIN_SUCCEED //nextState = ISAuthConstants.LOGIN_SUCCEED; } catch (Exception ex) { System.out.println("Exception thrown validating impersonated userid " + ex); throw new AuthLoginException( "EImpersonationModule: Exception thrown validating impersonated userid"); } break; } } catch (Exception e) { System.out.println("Cannot parse json. " + e); throw new AuthLoginException( "Cannot parse json..unable to read attribtue value using amIdentity"); } } if (checkGroupMembership.equalsIgnoreCase("true") && validatedUserID == null) { // Admin was not authorized to impersonate other users nextState = 4; throw new AuthLoginException("Admin was not authorized to impersonate other users"); } } // 2. Check for policy evaluation // get the ssoToken first, for use with the REST call String url = openamServer + "/json/" + authnRealm + "/authenticate"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost postRequest = new HttpPost(url); String cookie = ""; try { System.out.println("BEFORE policy1 eval..."); postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); // TBD: replace with admin provided username and password- stick this code into the impersonate auth module postRequest.setHeader("X-OpenAM-Username", userName); postRequest.setHeader("X-OpenAM-Password", userPassword); StringEntity input = new StringEntity("{}"); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); String json = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println("json/" + authnRealm + "/authenticate response-> " + json); try { JSONParser parser = new JSONParser(); Object resultObject = parser.parse(json); if (resultObject instanceof JSONArray) { JSONArray array = (JSONArray) resultObject; for (Object object : array) { JSONObject obj = (JSONObject) object; System.out.println("jsonarray-> " + obj); } } else if (resultObject instanceof JSONObject) { JSONObject obj = (JSONObject) resultObject; System.out.println("tokenId-> " + obj.get("tokenId")); cookie = (String) obj.get("tokenId"); } } catch (Exception e) { // TODO: handle exception nextState = 4; } System.out.println("AFTER policy1 eval..."); // Headers org.apache.http.Header[] headers = response.getAllHeaders(); for (int j = 0; j < headers.length; j++) { System.out.println(headers[j]); } } catch (Exception e) { System.err.println("Fatal error: " + e.getMessage()); e.printStackTrace(); nextState = 4; } System.out.println("BEFORE policy2 eval..."); /*Cookie[] cookies = getHttpServletRequest().getCookies(); if (cookies != null) { for (int m = 0; m < cookies.length; m++) { System.out.println(cookies[m].getName() +":"+cookies[m].getValue()); if (cookies[m].getName().equalsIgnoreCase("iPlanetDirectoryPro")) { cookie = cookies[m].getValue(); break; } } }*/ url = openamServer + "/json/" + policyRealm + "/policies?_action=evaluate"; //httpClient = HttpClientBuilder.create().build(); postRequest = new HttpPost(url); try { postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); postRequest.setHeader("iPlanetDirectoryPro", cookie); StringEntity input = new StringEntity( "{\"resources\": [\"" + new URL(resourceSet) + "\"],\"application\":\"" + policySet + "\", \"subject\": {\"ssoToken\":\"" + cookie + "\"}}"); System.out.println("stringentity-> " + getStringFromInputStream(input.getContent())); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); String json = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println("json/" + policyRealm + "/policies?_action=evaluate response-> " + json); try { JSONParser parser = new JSONParser(); Object resultObject = parser.parse(json); if (resultObject instanceof JSONArray) { JSONArray array = (JSONArray) resultObject; for (Object object : array) { JSONObject obj = (JSONObject) object; System.out.println("jsonarray-> " + obj); JSONObject actions = (JSONObject) obj.get("actions"); Boolean actionGet = (Boolean) actions.get("GET"); Boolean actionPost = (Boolean) actions.get("POST"); System.out.println("actionGet : " + actionGet); System.out.println("actionPost : " + actionPost); if (actionGet != null && actionGet.equals(true) && actionPost != null && actionPost.equals(true)) { nextState = ISAuthConstants.LOGIN_SUCCEED; } else { System.out.println("actionget and actionpost are not true"); nextState = 4; } } } else { // something went wrong! System.out.println("resultObject is not a JSONArray"); nextState = 4; } } catch (Exception e) { // TODO: handle exception nextState = 4; System.out.println("exception invoking json parsing routine"); e.printStackTrace(); } System.out.println("AFTER policy2 eval..."); // Headers org.apache.http.Header[] headers = response.getAllHeaders(); for (int j = 0; j < headers.length; j++) { System.out.println(headers[j]); } // logout the administrator url = openamServer + "/json/" + authnRealm + "/sessions/?_action=logout"; System.out.println("destroying admin session: " + url); postRequest = new HttpPost(url); try { postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); postRequest.setHeader("iPlanetDirectoryPro", cookie); response = httpClient.execute(postRequest); try { JSONParser parser = new JSONParser(); Object resultObject = parser.parse(json); if (resultObject instanceof JSONArray) { JSONArray array = (JSONArray) resultObject; for (Object object : array) { JSONObject obj = (JSONObject) object; System.out.println("logout response-array-> " + obj); } } else { JSONObject obj = (JSONObject) resultObject; System.out.println("logout response-> " + obj); } } catch (Exception e) { System.out.println("unable to read logout json response"); e.printStackTrace(); } } catch (Exception e) { System.out.println( "Issue destroying administrator's session, still proceeding with impersonation"); e.printStackTrace(); } } catch (Exception e) { System.err.println("Fatal error: " + e.getMessage()); e.printStackTrace(); nextState = 4; } // else of admin successful login } else { System.out.println("username:password read from callback: " + userName + " : " + userPassword); nextState = 4; throw new AuthLoginException(amAuthImpersonation, "authFailed", null); } } catch (com.sun.identity.idm.IdRepoException idrepox) { System.out.println("IdRepoException thrown " + idrepox); nextState = 4; throw new AuthLoginException("IdRepoException thrown from Impersonation module"); } catch (SSOException ssoe) { System.out.println("SSOException thrown " + ssoe); nextState = 4; throw new AuthLoginException("SSOException thrown from ImpersonationModule module"); } break; case 2: javax.security.auth.callback.NameCallback response = (javax.security.auth.callback.NameCallback) callbacks[0]; userResponse = new String(response.getName()); // check the response against OpenDJ System.out.println("user to impersonate : state 2: " + userResponse); nextState = 3; break; default: throw new AuthLoginException("invalid state"); } return nextState; }