List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:org.apache.stratos.integration.common.rest.RestClient.java
public HttpResponse doPut(URI resourcePath, String jsonParamString) throws Exception { HttpPut putRequest = null;// ww w . j a v a 2s . c o m try { putRequest = new HttpPut(resourcePath); StringEntity input = new StringEntity(jsonParamString); input.setContentType("application/json"); putRequest.setEntity(input); String userPass = getUsernamePassword(); String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8")); putRequest.addHeader("Authorization", basicAuth); return httpClient.execute(putRequest, new HttpResponseHandler()); } finally { releaseConnection(putRequest); } }
From source file:org.apache.stratos.integration.common.rest.RestClient.java
/** * Handle http post request. Return String * * @param resourcePath This should be REST endpoint * @param jsonParamString The json string which should be executed from the post request * @return The HttpResponse/* www .ja v a 2 s . c o m*/ * @throws Exception if any errors occur when executing the request */ public HttpResponse doPost(URI resourcePath, String jsonParamString) throws Exception { HttpPost postRequest = null; try { postRequest = new HttpPost(resourcePath); StringEntity input = new StringEntity(jsonParamString); input.setContentType("application/json"); postRequest.setEntity(input); String userPass = getUsernamePassword(); String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8")); postRequest.addHeader("Authorization", basicAuth); return httpClient.execute(postRequest, new HttpResponseHandler()); } finally { releaseConnection(postRequest); } }
From source file:org.jboss.as.test.integration.domain.suites.ResponseStreamTestCase.java
private HttpPost getHttpPost(URL url) throws URISyntaxException, UnsupportedEncodingException { // For POST we are using the custom op instead read-attribute that we use for GET // but this is just a convenient way to exercise the op (GET can't call custom ops), // and isn't some limitation of POST PathAddress base = PathAddress.pathAddress(HOST, "slave").append(SERVER, "main-three"); ModelNode cmd = createReadAttributeOp(base); String cmdStr = cmd.toJSONString(true); HttpPost post = new HttpPost(url.toURI()); StringEntity entity = new StringEntity(cmdStr); entity.setContentType(APPLICATION_JSON); post.setEntity(entity);/*from ww w. ja va 2 s .co m*/ return post; }
From source file:es.uma.lcc.tasks.EncryptionUploaderTask.java
@Override public String doInBackground(Void... voids) { String dst = null;//from w w w. j a v a 2 s . c o m String filename = mSrc.substring(mSrc.lastIndexOf("/") + 1, mSrc.lastIndexOf(".")); ArrayList<Rectangle> rects = new ArrayList<Rectangle>(); for (String s : mRectangles) rects.add(new Rectangle(s)); mSquareNum = rects.size(); mHorizStarts = new int[mSquareNum]; mHorizEnds = new int[mSquareNum]; mVertStarts = new int[mSquareNum]; mVertEnds = new int[mSquareNum]; mKeys = new String[mSquareNum]; for (int i = 0; i < mSquareNum; i++) { mHorizStarts[i] = rects.get(i).x0 / 16; mHorizEnds[i] = rects.get(i).xEnd / 16; mVertStarts[i] = rects.get(i).y0 / 16; mVertEnds[i] = rects.get(i).yEnd / 16; } mNewId = null; boolean permissionToSelf = false; JSONArray permissions = new JSONArray(); try { JSONObject obj = new JSONObject(); JSONArray usernames; obj.put(JSON_PROTOCOLVERSION, CURRENT_VERSION); obj.put(JSON_FILENAME, filename); obj.put(JSON_IMGHEIGHT, mHeight); obj.put(JSON_IMGWIDTH, mWidth); permissions.put(obj); for (int i = 0; i < mSquareNum; i++) { TreeSet<String> auxSet = new TreeSet<String>(); // helps in checking a permission is not granted twice obj = new JSONObject(); obj.put(JSON_HSTART, mHorizStarts[i]); obj.put(JSON_HEND, mHorizEnds[i]); obj.put(JSON_VSTART, mVertStarts[i]); obj.put(JSON_VEND, mVertEnds[i]); usernames = new JSONArray(); usernames.put(mMainActivity.getUserEmail().toLowerCase(Locale.ENGLISH)); auxSet.add(mMainActivity.getUserEmail().toLowerCase(Locale.ENGLISH)); for (String str : rects.get(i).getPermissionsArrayList()) { if (!auxSet.contains(str.toLowerCase(Locale.ENGLISH))) { usernames.put(str.toLowerCase(Locale.ENGLISH)); auxSet.add(str.toLowerCase(Locale.ENGLISH)); } else if (str.equalsIgnoreCase(mMainActivity.getUserEmail())) permissionToSelf = true; } obj.put(JSON_USERNAME, usernames); permissions.put(obj); } } catch (JSONException jsonex) { // Will never happen: every value is either a number, or a correctly formatted email } if (permissionToSelf) { publishProgress(5); } DefaultHttpClient httpclient = new DefaultHttpClient(); final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); httpclient.setParams(params); String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_ONESTEPUPLOAD; HttpPost httppost = new HttpPost(target); while (mCookie == null) { // loop until authentication finishes, if necessary mCookie = mMainActivity.getCurrentCookie(); } try { StringEntity permissionsEntity = new StringEntity(permissions.toString()); permissionsEntity.setContentType(new BasicHeader("Content-Type", "application/json")); httppost.setEntity(permissionsEntity); httppost.setHeader("Cookie", mCookie.getName() + "=" + mMainActivity.getCurrentCookie().getValue()); System.out.println("Cookie in header: " + mMainActivity.getCurrentCookie().getValue()); HttpResponse response = httpclient.execute(httppost); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { mConnectionSucceeded = false; throw new IOException("Invalid response from server: " + status.toString()); } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; byte[] sBuffer = new byte[256]; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } String result = new String(content.toByteArray()); try { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() == 0) { // should never happen Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server"); mConnectionSucceeded = false; } else { // Elements in a JSONArray keep their order JSONObject successState = jsonArray.getJSONObject(0); if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) { if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) { mIsAuthError = true; Log.e(APP_TAG, LOG_ERROR + ": Server found an auth error: " + successState.get(JSON_REASON)); } else { mConnectionSucceeded = false; Log.e(APP_TAG, LOG_ERROR + ": Server found an error: " + successState.get("reason")); } } else { // everything went OK mNewId = jsonArray.getJSONObject(1).getString(JSON_PICTUREID); for (int i = 0; i < mSquareNum; i++) { mKeys[i] = jsonArray.getJSONObject(i + 2).getString(JSON_KEY); } if (mNewId == null) { mConnectionSucceeded = false; Log.e(APP_TAG, "Encryption: Error connecting to server"); } else { publishProgress(10); String date = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(new Date()); File directory = new File( Environment.getExternalStorageDirectory() + "/" + APP_TAG); if (!directory.exists()) { directory.mkdir(); } dst = Environment.getExternalStorageDirectory() + "/" + APP_TAG + "/" + ENCRYPTED_FILE_PREFIX + filename + "_" + date + ".jpg"; mSuccess = MainActivity.encodeWrapperRegions(mSrc, dst, mSquareNum, mHorizStarts, mHorizEnds, mVertStarts, mVertEnds, mKeys, mNewId); addToGallery(dst); } } } } catch (JSONException jsonEx) { mConnectionSucceeded = false; Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server"); } } } catch (ClientProtocolException e) { mConnectionSucceeded = false; } catch (IOException e) { mConnectionSucceeded = false; } return dst; }
From source file:org.alfresco.test.util.SiteService.java
/** * Add dashlet to site dashboard/* w w w . j a v a2s.c om*/ * * @param userName String identifier * @param password * @param siteName * @param dashlet * @param layout * @param column * @param position * @return true if the dashlet is added * @throws Exception if error */ public boolean addDashlet(final String userName, final String password, final String siteName, final SiteDashlet dashlet, final DashletLayout layout, final int column, final int position) throws Exception { if (!exists(siteName, userName, password)) { throw new RuntimeException("Site doesn't exists " + siteName); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); String url = client.getAlfrescoUrl() + DashboardCustomization.ADD_DASHLET_URL; org.json.JSONObject body = new org.json.JSONObject(); org.json.JSONArray array = new org.json.JSONArray(); body.put("dashboardPage", "site/" + siteName + "/dashboard"); body.put("templateId", layout.id); Hashtable<String, String> defaultDashlets = new Hashtable<String, String>(); defaultDashlets.put(SiteDashlet.SITE_MEMBERS.id, "component-1-1"); defaultDashlets.put(SiteDashlet.SITE_CONNTENT.id, "component-2-1"); defaultDashlets.put(SiteDashlet.SITE_ACTIVITIES.id, "component-2-2"); Iterator<Map.Entry<String, String>> entries = defaultDashlets.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); org.json.JSONObject jDashlet = new org.json.JSONObject(); jDashlet.put("url", entry.getKey()); jDashlet.put("regionId", entry.getValue()); jDashlet.put("originalRegionId", entry.getValue()); array.put(jDashlet); } org.json.JSONObject newDashlet = new org.json.JSONObject(); newDashlet.put("url", dashlet.id); String region = "component-" + column + "-" + position; newDashlet.put("regionId", region); array.put(newDashlet); body.put("dashlets", array); HttpPost post = new HttpPost(url); StringEntity se = new StringEntity(body.toString(), AlfrescoHttpClient.UTF_8_ENCODING); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, AlfrescoHttpClient.MIME_TYPE_JSON)); post.setEntity(se); HttpClient clientWithAuth = client.getHttpClientWithBasicAuth(userName, password); try { HttpResponse response = clientWithAuth.execute(post); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { if (logger.isTraceEnabled()) { logger.trace("Dashlet " + dashlet.name + " was added to site " + siteName); } return true; } else { logger.error("Unable to add dashlet to site " + siteName); } } finally { post.releaseConnection(); client.close(); } return false; }
From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java
private String createResumableUpload(String title, HasDescription description, HasId parentId, HasMimeType mimeType) throws IOException { logger.info("Creating resumable upload..."); String postUri = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable"; if (useOldApi) { postUri = "https://docs.google.com/feeds/upload/create-session/default/private/full?convert=false"; if (parentId != null && org.apache.commons.lang3.StringUtils.isNotEmpty(parentId.getId())) { // https://developers.google.com/google-apps/documents-list/ postUri = "https://docs.google.com/feeds/upload/create-session/default/private/full" + "/folder%3A" + parentId.getId() + "/contents" + "?convert=false"; }//ww w . j av a2 s .c om } else { // TODO: new api // ... throw new IllegalStateException("Not implemented"); } CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; try { httpclient = getHttpClient(); HttpPost httpPost = new HttpPost(postUri); httpPost.addHeader("Authorization", auth.getAuthHeader()); httpPost.addHeader("X-Upload-Content-Type", mimeType.getMimeType()); httpPost.addHeader("X-Upload-Content-Length", getFileSizeString()); String entityString = new JSONObject().put("title", title).toString(); BasicHeader entityHeader = new BasicHeader(HTTP.CONTENT_TYPE, "application/json"); if (useOldApi) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sb.append( "<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:docs=\"http://schemas.google.com/docs/2007\">"); sb.append( "<category scheme=\"http://schemas.google.com/g/2005#kind\" term=\"http://schemas.google.com/docs/2007#document\"/>"); // title sb.append("<title>").append(title).append("</title>"); // description if (description != null && org.apache.commons.lang3.StringUtils.isNotEmpty(description.getDescription())) { sb.append("<docs:description>").append(description.getDescription()) .append("</docs:description>"); } sb.append("</entry>"); entityString = sb.toString(); httpPost.addHeader("GData-Version", "3"); entityHeader = new BasicHeader(HTTP.CONTENT_TYPE, "application/atom+xml"); } else { // TODO: new api // ... throw new IllegalStateException("Not implemented"); } StringEntity se = new StringEntity(entityString); se.setContentType(entityHeader); httpPost.setEntity(se); //logger.info("Create Resumable: " + httpPost.toString()); response = httpclient.execute(httpPost); @SuppressWarnings("unused") BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); EntityUtils.consume(response.getEntity()); String location = ""; if (response.getStatusLine().getStatusCode() == 200) { location = response.getHeaders("Location")[0].getValue(); //logger.info("Location: " + location); } return location; } finally { if (response != null) { response.close(); } if (httpclient != null) { httpclient.close(); } } }
From source file:org.callimachusproject.auth.AuthorizationManager.java
public HttpResponse authorize(ResourceOperation request, Set<Group> groups, CalliContext ctx) throws OpenRDFException, IOException { InetAddress clientAddr = ctx.getClientAddr(); long now = ctx.getReceivedOn(); String m = request.getMethod(); RDFObject target = request.getRequestedResource(); String or = request.getVaryHeader("Origin"); Map<String, String[]> map = getAuthorizationMap(request, now, clientAddr, groups); List<String> from = getAgentFrom(map.get("via")); if (isAnonymousAllowed(from, groups)) return null; // loop through first to see if further authorisation is needed DetachedRealm realm = getRealm(request); HttpResponse unauth = null;/*from w ww . j a v a 2 s. c o m*/ boolean validOrigin = false; boolean noRealm = true; if (realm != null) { String cred = null; Collection<String> allowed = realm.allowOrigin(); try { if (or == null || isOriginAllowed(allowed, or)) { ObjectConnection con = ctx.getObjectConnection(); cred = realm.authenticateRequest(m, target, map, con); if (cred != null && isMember(cred, from, groups)) { ctx.setCredential(cred); return null; // this request is good } } } catch (TooManyRequests e) { StringEntity body = new StringEntity(e.getDetailMessage(), Charset.forName("UTF-8")); body.setContentType("text/plain"); BasicStatusLine line = new BasicStatusLine(HttpVersion.HTTP_1_1, e.getStatusCode(), e.getShortMessage()); HttpResponse resp = new BasicHttpResponse(line); resp.setHeader("Content-Type", "text/plain;charset=UTF-8"); for (Header hd : e.getResponseHeaders()) { resp.addHeader(hd); } resp.setEntity(body); return resp; } noRealm = false; validOrigin = or == null || isOriginAllowed(allowed, or); try { if (cred == null) { unauth = choose(unauth, realm.unauthorized(m, target, map, request.getEntity())); } else { unauth = choose(unauth, realm.forbidden(m, target, map)); } } catch (ResponseException exc) { if (unauth != null) { EntityUtils.consumeQuietly(unauth.getEntity()); } throw exc; } catch (Exception exc) { logger.error(exc.toString(), exc); } } if (unauth != null) return unauth; if (noRealm) { logger.info("No active realm for {}", request); } else if (!validOrigin) { logger.info("Origin {} not allowed for {}", or, request); } StringEntity body = new StringEntity("Forbidden", Charset.forName("UTF-8")); body.setContentType("text/plain"); HttpResponse resp = new BasicHttpResponse(_403); resp.setHeader("Content-Type", "text/plain;charset=UTF-8"); resp.setEntity(body); return resp; }
From source file:org.apache.stratos.integration.common.rest.RestClient.java
public boolean addPropertyToApplication(String appId, String propertyKey, String propertyValue, String accessToken) throws Exception { log.info(String.format(/*from w w w .j ava2s . com*/ "Adding property to application [application-id] %s, [key] %s, [value] %s, [token] %s", appId, propertyKey, propertyValue, accessToken)); URI uri = new URIBuilder( this.securedEndpoint + RestConstants.METADATA_API + "/applications/" + appId + "/properties") .build(); PropertyBean property = new PropertyBean(propertyKey, propertyValue); HttpResponse response; HttpPost postRequest = null; String requestBody = gson.toJson(property, PropertyBean.class); try { postRequest = new HttpPost(uri); StringEntity input = new StringEntity(requestBody); input.setContentType("application/json"); postRequest.setEntity(input); String bearerAuth = "Bearer " + accessToken; postRequest.addHeader("Authorization", bearerAuth); response = httpClient.execute(postRequest, new HttpResponseHandler()); } finally { releaseConnection(postRequest); } if (response != null) { if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) { return true; } else { throw new RuntimeException(response.getContent()); } } throw new Exception("Null response received. Could not add property to application: " + appId); }
From source file:org.apache.stratos.integration.common.rest.RestClient.java
public boolean addPropertyToCluster(String appId, String clusterId, String propertyKey, String propertyValue, String accessToken) throws Exception { log.info(String.format(// w ww . ja v a 2 s. co m "Adding property to cluster [application-id] %s, [cluster-id] %s, [key] %s, [value] %s, [token] %s", appId, clusterId, propertyKey, propertyValue, accessToken)); URI uri = new URIBuilder(this.securedEndpoint + RestConstants.METADATA_API + "/applications/" + appId + "/clusters/" + clusterId + "/properties").build(); PropertyBean property = new PropertyBean(propertyKey, propertyValue); HttpResponse response; HttpPost postRequest = null; String requestBody = gson.toJson(property); try { postRequest = new HttpPost(uri); StringEntity input = new StringEntity(requestBody); input.setContentType("application/json"); postRequest.setEntity(input); String bearerAuth = "Bearer " + accessToken; postRequest.addHeader("Authorization", bearerAuth); response = httpClient.execute(postRequest, new HttpResponseHandler()); } finally { releaseConnection(postRequest); } if (response != null) { if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) { return true; } else { throw new RuntimeException(response.getContent()); } } throw new Exception("Null response received. Could not add property to cluster: " + clusterId); }
From source file:com.mondora.chargify.controller.ChargifyAdapter.java
public MeteredUsage componentCreateUsage(String sub, String comp, Integer quantity, String memo) throws ChargifyException { String xml = "<usage>" + "<id>" + AUTO_GENERATED + "</id>" + "<quantity type=\"integer\">" + Integer.toString(quantity) + "</quantity>" + "<memo>" + String.valueOf(memo) + "</memo>" + "</usage>"; HttpPost method = new HttpPost("/subscriptions/" + sub + "/components/" + comp + "/usages.xml"); try {//from www.j a v a2 s . co m StringEntity entity = new StringEntity(xml); entity.setContentEncoding(charset); entity.setContentType(contentType); method.setEntity(entity); HttpResponse response = executeHttpMethod(method); handleResponseCode(response, method); return (MeteredUsage) parse(MeteredUsage.class, response, method); } catch (Exception e) { throw new ChargifyException(e); } }