List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:org.wildfly.core.test.standalone.mgmt.api.core.ResponseAttachmentTestCase.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 ModelNode cmd = Util.createEmptyOperation(LogStreamExtension.STREAM_LOG_FILE, PathAddress.pathAddress(SUBSYSTEM, LogStreamExtension.SUBSYSTEM_NAME)); 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 v a2 s . co m*/ return post; }
From source file:ws.argo.Responder.Responder.java
private void sendResponse(String respondToURL, String payloadType, ResponsePayloadBean response) { // This method will likely need some thought and care in the error handling and error reporting // It's a had job at the moment. String responseStr = null;/*from w w w . ja va2 s. c o m*/ String contentType = null; //MIME type switch (payloadType) { case "XML": { responseStr = response.toXML(); contentType = "application/xml"; break; } case "JSON": { responseStr = response.toJSON(); contentType = "application/json"; break; } default: responseStr = response.toJSON(); } try { HttpPost postRequest = new HttpPost(respondToURL); StringEntity input = new StringEntity(responseStr); input.setContentType(contentType); postRequest.setEntity(input); LOGGER.fine("Sending response"); LOGGER.fine("Response payload:"); LOGGER.fine(responseStr); CloseableHttpResponse httpResponse = httpClient.execute(postRequest); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode > 300) { throw new RuntimeException( "Failed : HTTP error code : " + httpResponse.getStatusLine().getStatusCode()); } if (statusCode != 204) { BufferedReader br = new BufferedReader( new InputStreamReader((httpResponse.getEntity().getContent()))); LOGGER.fine("Successful response from response target - " + respondToURL); String output; LOGGER.fine("Output from Listener .... \n"); while ((output = br.readLine()) != null) { LOGGER.fine(output); } } } finally { httpResponse.close(); } LOGGER.fine("Response payload sent successfully to respondTo address."); } catch (MalformedURLException e) { LOGGER.fine("MalformedURLException occured\nThe respondTo URL was a no good. respondTo URL is: " + respondToURL); // e.printStackTrace(); } catch (IOException e) { LOGGER.fine("An IOException occured: the error message is - " + e.getMessage()); LOGGER.log(Level.SEVERE, e.getMessage()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Some other error occured. the error message is - " + e.getMessage()); LOGGER.log(Level.SEVERE, e.getMessage()); } }
From source file:org.phenotips.remote.client.script.RemoteMatchingScriptService.java
public JSONObject sendRequest(String patientId, String remoteServerId, boolean async, boolean periodic, int addTopNGenes) { this.logger.error("Sending outgoing request for patient [{}] to server [{}]", patientId, remoteServerId); if (async) {// w w w .j a va 2s. c om this.logger.error("Requesting async replies"); } if (periodic) { this.logger.error("Requesting periodic replies"); } XWikiContext context = this.getContext(); BaseObject configurationObject = XWikiAdapter.getRemoteConfigurationGivenRemoteName(remoteServerId, context); if (configurationObject == null) { logger.error("Requested matching server is not configured: [{}]", remoteServerId); return generateScriptErrorReply(ApiConfiguration.ERROR_NOT_SENT, "requested matching server [" + remoteServerId + "] is not configured"); } // TODO: get API version from server configuration String apiVersion = "v1"; ApiDataConverter apiVersionSpecificConverter = this.apiFactory.getApiVersion(apiVersion); DefaultOutgoingSearchRequest request = new DefaultOutgoingSearchRequest(patientId, remoteServerId); if (periodic) { request.setQueryType(ApiConfiguration.REQUEST_QUERY_TYPE_PERIODIC); } if (async) { request.setResponseType(ApiConfiguration.REQUEST_RESPONSE_TYPE_ASYNCHRONOUS); } JSONObject requestJSON; try { requestJSON = apiVersionSpecificConverter.getOutgoingRequestToJSONConverter().toJSON(request, addTopNGenes); } catch (ApiViolationException ex) { return generateScriptErrorReply(ApiConfiguration.ERROR_NOT_SENT, ex.getMessage()); } if (requestJSON == null) { this.logger.error("Unable to convert patient to JSON: [{}]", patientId); return generateScriptErrorReply(ApiConfiguration.ERROR_NOT_SENT, "unable to convert patient with ID [" + patientId.toString() + "] to JSON"); } CloseableHttpClient client = HttpClients.createDefault(); StringEntity jsonEntity = new StringEntity(requestJSON.toString(), ContentType.create("application/json", "utf-8")); // TODO: hack to make charset lower-cased so that GeneMatcher accepts it jsonEntity.setContentType("application/json; charset=utf-8"); this.logger.error("Using content type: [{}]", jsonEntity.getContentType().toString()); String key = configurationObject.getStringValue(ApplicationConfiguration.CONFIGDOC_REMOTE_KEY_FIELD); String baseURL = configurationObject .getStringValue(ApplicationConfiguration.CONFIGDOC_REMOTE_BASE_URL_FIELD); if (baseURL.charAt(baseURL.length() - 1) != '/') { baseURL += "/"; } String targetURL = baseURL + ApiConfiguration.REMOTE_URL_SEARCH_ENDPOINT; this.logger.error("Sending matching request to [" + targetURL + "]: " + requestJSON.toString()); CloseableHttpResponse httpResponse; try { HttpPost httpRequest = new HttpPost(targetURL); httpRequest.setEntity(jsonEntity); httpRequest.setHeader(ApiConfiguration.HTTPHEADER_KEY_PARAMETER, key); httpResponse = client.execute(httpRequest); } catch (javax.net.ssl.SSLHandshakeException ex) { this.logger.error( "Error sending matching request to [" + targetURL + "]: SSL handshake exception: [{}]", ex); return generateScriptErrorReply(ApiConfiguration.ERROR_NOT_SENT, "SSL handshake problem"); } catch (Exception ex) { this.logger.error("Error sending matching request to [" + targetURL + "]: [{}]", ex); return generateScriptErrorReply(ApiConfiguration.ERROR_NOT_SENT, ex.getMessage()); } try { Integer httpStatus = (Integer) httpResponse.getStatusLine().getStatusCode(); String stringReply = EntityUtils.toString(httpResponse.getEntity()); logger.error("Reply to matching request: STATUS: [{}], DATA: [{}]", httpStatus, stringReply); JSONObject replyJSON = getParsedJSON(stringReply); if (StringUtils.equalsIgnoreCase(request.getQueryType(), ApiConfiguration.REQUEST_QUERY_TYPE_PERIODIC) || StringUtils.equalsIgnoreCase(request.getResponseType(), ApiConfiguration.REQUEST_RESPONSE_TYPE_ASYNCHRONOUS)) { // get query ID assigned by the remote server and saveto DB if (!replyJSON.has(ApiConfiguration.JSON_RESPONSE_ID)) { this.logger.error("Can not store outgoing request: no queryID is provided by remote server"); } else { String queruID = replyJSON.getString(ApiConfiguration.JSON_RESPONSE_ID); this.logger.error("Remote server assigned id to the submitted query: [{}]", queruID); request.setQueryID(replyJSON.getString(ApiConfiguration.JSON_RESPONSE_ID)); requestStorageManager.saveOutgoingRequest(request); } } return generateScriptReply(httpStatus, replyJSON); } catch (Exception ex) { this.logger.error("Error processing matching request reply to [" + targetURL + "]: [{}]", ex); return generateScriptReply(ApiConfiguration.ERROR_INTERNAL, null); } }
From source file:org.wso2.carbon.appmgt.mdm.wso2emm.ApplicationOperationsImpl.java
/** * * @param applicationOperationAction holds the information needs to perform an action on mdm *///from w ww . j a va 2 s . co m public String performAction(ApplicationOperationAction applicationOperationAction) { HashMap<String, String> configProperties = applicationOperationAction.getConfigParams(); String serverURL = configProperties.get(Constants.PROPERTY_SERVER_URL); String authUser = configProperties.get(Constants.PROPERTY_AUTH_USER); String authPass = configProperties.get(Constants.PROPERTY_AUTH_PASS); String[] params = applicationOperationAction.getParams(); JSONArray resources = new JSONArray(); for (String param : params) { resources.add(param); } String action = applicationOperationAction.getAction(); String type = applicationOperationAction.getType(); int tenantId = applicationOperationAction.getTenantId(); JSONObject requestObj = new JSONObject(); requestObj.put("action", action); requestObj.put("to", type); requestObj.put("resources", resources); requestObj.put("tenantId", tenantId); JSONObject requestApp = new JSONObject(); App app = applicationOperationAction.getApp(); Method[] methods = app.getClass().getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Property.class)) { try { Object value = method.invoke(app); if (value != null) { requestApp.put(method.getAnnotation(Property.class).name(), value); } } catch (IllegalAccessException e) { String errorMessage = "Illegal Action"; if (log.isDebugEnabled()) { log.error(errorMessage, e); } else { log.error(errorMessage); } } catch (InvocationTargetException e) { String errorMessage = "Target invocation failed"; if (log.isDebugEnabled()) { log.error(errorMessage, e); } else { log.error(errorMessage); } } } } requestObj.put("app", requestApp); String requestURL = serverURL + String.format(Constants.API_OPERATION, tenantId); HttpClient httpClient = AppManagerUtil.getHttpClient(requestURL); StringEntity requestEntity = null; if (log.isDebugEnabled()) log.debug("Request Payload for MDM: " + requestObj.toJSONString()); try { requestEntity = new StringEntity(requestObj.toJSONString(), "UTF-8"); requestEntity.setContentType(Constants.RestConstants.APPLICATION_JSON); } catch (UnsupportedEncodingException e) { String errorMessage = "JSON encoding not supported"; if (log.isDebugEnabled()) { log.error(errorMessage, e); } else { log.error(errorMessage); } } HttpPost postMethod = new HttpPost(requestURL); postMethod.setEntity(requestEntity); postMethod.setHeader(Constants.RestConstants.AUTHORIZATION, Constants.RestConstants.BASIC + new String(Base64.encodeBase64((authUser + ":" + authPass).getBytes()))); try { if (log.isDebugEnabled()) log.debug("Sending POST request to perform operation on MDM. Request path: " + requestURL); HttpResponse response = httpClient.execute(postMethod); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { if (log.isDebugEnabled()) log.debug(action + " operation on WSO2 EMM performed successfully"); } } catch (IOException e) { String errorMessage = "Cannot connect to WSO2 EMM to perform operation"; if (log.isDebugEnabled()) { log.error(errorMessage, e); } else { log.error(errorMessage); } } return null; }
From source file:org.alfresco.test.util.SiteService.java
/** * Set site as favorite//from w ww . j a v a2 s . c o m * * @param userName String identifier * @param password * @param siteName * @return true if marked as favorite * @throws Exception if error */ public boolean setFavorite(final String userName, final String password, final String siteName) throws Exception { if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(siteName)) { throw new IllegalArgumentException("Parameter missing"); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); String nodeRef = getSiteNodeRef(userName, password, siteName); String reqUrl = client.getApiVersionUrl() + "people/" + userName + "/favorites"; HttpPost post = new HttpPost(reqUrl); String jsonInput; jsonInput = "{\"target\": {\"" + "site" + "\" : {\"guid\" : \"" + nodeRef + "\"}}}"; StringEntity se = new StringEntity(jsonInput.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); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_CREATED: return true; case HttpStatus.SC_NOT_FOUND: throw new RuntimeException("Site doesn't exists " + siteName); case HttpStatus.SC_UNAUTHORIZED: throw new RuntimeException("Invalid user name or password"); default: logger.error("Unable to mark as favorite: " + response.toString()); break; } } finally { post.releaseConnection(); client.close(); } return false; }
From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java
protected File createSimpleProject(String projectName) throws IOException { String url = "/project?asFolder"; HttpPost post = new HttpPost(prefix + url); StringEntity entity = new StringEntity("{\"name\":\"" + projectName + "\"}"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity);//w ww . j av a 2 s . co m post.setHeader(defaultHeader); String response = this.simpleCall(post); return convertString2Obj(response, File.class); }
From source file:com.luyaozhou.recognizethisforglass.ViewFinder.java
private void processPictureWhenReady(final String picturePath) { final File pictureFile = new File(picturePath); //Map<String, String > result = new HashMap<String,String>(); if (pictureFile.exists()) { // The picture is ready; process it. Bitmap imageBitmap = null;/* ww w. j a v a2s.c o m*/ try { // Bundle extras = data.getExtras(); // imageBitmap = (Bitmap) extras.get("data"); FileInputStream fis = new FileInputStream(picturePath); //get the bitmap from file imageBitmap = (Bitmap) BitmapFactory.decodeStream(fis); if (imageBitmap != null) { Bitmap lScaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 1600, 1200, false); if (lScaledBitmap != null) { imageBitmap.recycle(); imageBitmap = null; ByteArrayOutputStream lImageBytes = new ByteArrayOutputStream(); lScaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, lImageBytes); lScaledBitmap.recycle(); lScaledBitmap = null; byte[] lImageByteArray = lImageBytes.toByteArray(); HashMap<String, String> lValuePairs = new HashMap<String, String>(); lValuePairs.put("base64Image", Base64.encodeToString(lImageByteArray, Base64.DEFAULT)); lValuePairs.put("compressionLevel", "30"); lValuePairs.put("documentIdentifier", "DRIVER_LICENSE_CA"); lValuePairs.put("documentHints", ""); lValuePairs.put("dataReturnLevel", "15"); lValuePairs.put("returnImageType", "1"); lValuePairs.put("rotateImage", "0"); lValuePairs.put("data1", ""); lValuePairs.put("data2", ""); lValuePairs.put("data3", ""); lValuePairs.put("data4", ""); lValuePairs.put("data5", ""); lValuePairs.put("userName", "zbroyan@miteksystems.com"); lValuePairs.put("password", "google1"); lValuePairs.put("phoneKey", "1"); lValuePairs.put("orgName", "MobileImagingOrg"); String lSoapMsg = formatSOAPMessage("InsertPhoneTransaction", lValuePairs); DefaultHttpClient mHttpClient = new DefaultHttpClient(); // mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.R) HttpPost mHttpPost = new HttpPost(); mHttpPost.setHeader("User-Agent", "UCSD Team"); mHttpPost.setHeader("Content-typURIe", "text/xml;charset=UTF-8"); //mHttpPost.setURI(URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx?op=InsertPhoneTransaction")); mHttpPost.setURI( URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx")); StringEntity se = new StringEntity(lSoapMsg, HTTP.UTF_8); se.setContentType("text/xml; charset=UTF-8"); mHttpPost.setEntity(se); HttpResponse mResponse = mHttpClient.execute(mHttpPost, new BasicHttpContext()); String responseString = new BasicResponseHandler().handleResponse(mResponse); parseXML(responseString); //Todo: this is test code. Need to be implemented //result = parseXML(testStr); Log.i("test", "test:" + " " + responseString); Log.i("test", "test: " + " " + map.size()); } } } catch (Exception e) { e.printStackTrace(); } // this part will be relocated in order to let the the server process picture if (map.size() == 0) { Intent display = new Intent(getApplicationContext(), DisplayInfoFailed.class); display.putExtra("result", (java.io.Serializable) iQAMsg); startActivity(display); } else { Intent display = new Intent(getApplicationContext(), DisplayInfo.class); display.putExtra("result", (java.io.Serializable) map); startActivity(display); } } else { // The file does not exist yet. Before starting the file observer, you // can update your UI to let the user know that the application is // waiting for the picture (for example, by displaying the thumbnail // image and a progress indicator). final File parentDirectory = pictureFile.getParentFile(); FileObserver observer = new FileObserver(parentDirectory.getPath(), FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) { // Protect against additional pending events after CLOSE_WRITE // or MOVED_TO is handled. private boolean isFileWritten; @Override public void onEvent(int event, final String path) { if (!isFileWritten) { // For safety, make sure that the file that was created in // the directory is actually the one that we're expecting. File affectedFile = new File(parentDirectory, path); isFileWritten = affectedFile.equals(pictureFile); if (isFileWritten) { stopWatching(); // Now that the file is ready, recursively call // processPictureWhenReady again (on the UI thread). runOnUiThread(new Runnable() { @Override public void run() { new LongOperation().execute(picturePath); } }); } } } }; observer.startWatching(); } }
From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob.java
/** * Construct the post.//from w ww . j a v a 2 s .c om * * @param reviewInput input * @param reviewEndpoint end point * @return the entity */ private HttpPost createHttpPostEntity(ReviewInput reviewInput, String reviewEndpoint) { HttpPost httpPost = new HttpPost(reviewEndpoint); String asJson = GSON.toJson(reviewInput); StringEntity entity = null; try { entity = new StringEntity(asJson); } catch (UnsupportedEncodingException e) { logger.error("Failed to create JSON for posting to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to create JSON for posting to Gerrit: " + e.toString()); } return null; } entity.setContentType("application/json"); httpPost.setEntity(entity); return httpPost; }
From source file:org.alfresco.test.util.SiteService.java
/** * Add pages to site dashboard//w w w. j a v a 2 s . c om * * @param userName String identifier * @param password * @param siteName * @param multiplePages * @param page - single page to be added * @param pages - list of pages to be added * @return true if the page is added * @throws Exception if error */ private boolean addPages(final String userName, final String password, final String siteName, final boolean multiplePages, final Page page, final List<Page> pages) throws Exception { if (!exists(siteName, userName, password)) { throw new RuntimeException("Site doesn't exists " + siteName); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); String url = client.getAlfrescoUrl() + DashboardCustomization.SITE_PAGES_URL; org.json.JSONObject body = new org.json.JSONObject(); org.json.JSONArray array = new org.json.JSONArray(); body.put("siteId", siteName); // set the default page (Document Library) array.put(new org.json.JSONObject().put("pageId", Page.DOCLIB.pageId)); if (pages != null) { for (int i = 0; i < pages.size(); i++) { if (!Page.DOCLIB.pageId.equals(pages.get(i).pageId)) { array.put(new org.json.JSONObject().put("pageId", pages.get(i).pageId)); } } } // add the new page if (!multiplePages) { array.put(new org.json.JSONObject().put("pageId", page.pageId)); } body.put("pages", array); body.put("themeId", ""); 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("Page " + page.pageId + " was added to site " + siteName); } return true; } else { logger.error("Unable to add page to site " + siteName); return false; } } finally { post.releaseConnection(); client.close(); } }