List of usage examples for org.apache.http.entity.mime.content ByteArrayBody ByteArrayBody
public ByteArrayBody(final byte[] data, final String mimeType, final String filename)
From source file:com.servoy.extensions.plugins.http.BaseEntityEnclosingRequest.java
@Override protected HttpEntity buildEntity() throws Exception { HttpEntity entity = null;/* w w w.j a v a 2s.co m*/ if (files.size() == 0) { if (params != null) { entity = new UrlEncodedFormEntity(params, charset); } else if (!Utils.stringIsEmpty(content)) { entity = new StringEntity(content, mimeType, charset); content = null; } } else if (files.size() == 1 && (params == null || params.size() == 0)) { Object f = files.values().iterator().next(); if (f instanceof File) { entity = new FileEntity((File) f, ContentType.create("binary/octet-stream")); //$NON-NLS-1$ } else if (f instanceof JSFile) { entity = new InputStreamEntity(((JSFile) f).getAbstractFile().getInputStream(), ((JSFile) f).js_size(), ContentType.create("binary/octet-stream")); //$NON-NLS-1$ } else { Debug.error("could not add file to post request unknown type: " + f); } } else { entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // For File parameters for (Entry<Pair<String, String>, Object> e : files.entrySet()) { Object file = e.getValue(); if (file instanceof File) { ((MultipartEntity) entity).addPart(e.getKey().getLeft(), new FileBody((File) file)); } else if (file instanceof JSFile) { ((MultipartEntity) entity).addPart(e.getKey().getLeft(), new ByteArrayBody( Utils.getBytesFromInputStream( ((JSFile) file).getAbstractFile().getInputStream()), "binary/octet-stream", ((JSFile) file).js_getName())); } else { Debug.error("could not add file to post request unknown type: " + file); } } // add the parameters if (params != null) { Iterator<NameValuePair> it = params.iterator(); while (it.hasNext()) { NameValuePair nvp = it.next(); // For usual String parameters ((MultipartEntity) entity).addPart(nvp.getName(), new StringBody(nvp.getValue(), "text/plain", Charset.forName(charset))); } } } // entity may have been set already, see PutRequest.js_setFile return entity; }
From source file:anhttpclient.impl.request.HttpPostWebRequest.java
/** * {@inheritDoc}/* ww w . j av a 2 s .c om*/ */ public void addPart(String partName, byte[] byteArray, String mimeType, String name) { parts.put(partName, new ByteArrayBody(byteArray, getMimeTypeOrDefault(mimeType), name)); formParams.clear(); }
From source file:com.serphacker.serposcope.scraper.captcha.solver.DecaptcherSolver.java
@Override public boolean solve(Captcha cap) { if (!(cap instanceof CaptchaImage)) { return false; }/*from ww w .j av a2 s .com*/ captchaCount.incrementAndGet(); CaptchaImage captcha = (CaptchaImage) cap; captcha.setLastSolver(this); captcha.setStatus(Captcha.Status.CREATED); String filename = null; String textMimeType = captcha.getMimes()[0]; String[] mimes = null; if (textMimeType != null) mimes = textMimeType.split("/"); else textMimeType = "application/octet-stream"; if (mimes != null && mimes.length == 2) { if (isValidImageExtension(mimes[1])) { filename = "image." + mimes[1]; } } else { filename = "image.png"; } Map<String, Object> data = getMapWithCredentials(); data.put("function", "picture2"); data.put("pict", new ByteArrayBody(captcha.getImage(), ContentType.create(textMimeType), filename)); data.put("pict_type", "0"); long started = System.currentTimeMillis(); captcha.setStatus(Captcha.Status.SUBMITTED); try (ScrapClient http = new ScrapClient()) { http.setTimeout((int) timeoutMS); int httpStatus = 0; Answer answer = null; int retry = 0; while (true) { httpStatus = http.post(apiUrl, data, ScrapClient.PostType.MULTIPART); answer = Answer.fromResponse(http.getContentAsString()); if (!isRetryable(httpStatus, answer)) { break; } if (++retry > maxRetryOnOverload) { break; } try { Long sleep = 5000l * retry; LOG.debug("server is overloaded, sleeping {} ms", sleep); Thread.sleep(sleep); } catch (InterruptedException ex) { break; } } if (answer == null) { if (httpStatus == 200) { captcha.setError(Captcha.Error.INVALID_CREDENTIALS); } else { captcha.setError(Captcha.Error.NETWORK_ERROR); } captcha.setStatus(Captcha.Status.ERROR); return false; } captcha.setId(answer.majorId + "-" + answer.minorId); switch (answer.status) { case OK: captcha.setStatus(Captcha.Status.SOLVED); captcha.setError(Captcha.Error.SUCCESS); captcha.setResponse(answer.text); return true; case ERR_OVERLOAD: captcha.setError(Captcha.Error.SERVICE_OVERLOADED); break; case ERR_BALANCE: captcha.setError(Captcha.Error.OUT_OF_CREDITS); break; default: captcha.setError(Captcha.Error.NETWORK_ERROR); } captcha.setStatus(Captcha.Status.ERROR); } catch (IOException ex) { LOG.error("io exception", ex); captcha.setError(EXCEPTION); } finally { captcha.setSolveDuration(System.currentTimeMillis() - started); } return false; }
From source file:org.oscarehr.common.service.E2ESchedulerJob.java
@Override public void run() { DemographicDao demographicDao = SpringUtils.getBean(DemographicDao.class); OscarLogDao oscarLogDao = SpringUtils.getBean(OscarLogDao.class); StringBuilder sb = new StringBuilder(255); int success = 0; int failure = 0; int skipped = 0; int diffDays = 14; List<Integer> ids = null; try {//from w w w. j a va2 s . c o m // Gather demographic numbers for specified mode of operation if (diffMode) { if (e2eDiffDays != null && StringUtils.isNumeric(e2eDiffDays)) { diffDays = Integer.parseInt(e2eDiffDays); } Calendar cal = GregorianCalendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, -diffDays); ids = oscarLogDao.getDemographicIdsOpenedSinceTime(cal.getTime()); } else { ids = demographicDao.getActiveDemographicIds(); } if (ids != null) Collections.sort(ids); // Log Start Header StringBuilder sbStart = reuseStringBuilder(sb); sbStart.append("Starting E2E export job\nE2E Target URL: ").append(e2eUrl); if (diffMode) { sbStart.append("\nExport Mode: Differential - Days: ").append(diffDays); } else { sbStart.append("\nExport Mode: Full"); } logger.info(sbStart.toString()); StringBuilder sbStartRec = reuseStringBuilder(sb); sbStartRec.append(ids.size()).append(" records pending"); if (ids.size() > 0) { sbStartRec.append("\nRange: ").append(ids.get(0)).append(" - ").append(ids.get(ids.size() - 1)); sbStartRec.append(", Median: ").append(ids.get((ids.size() - 1) / 2)); } logger.info(sbStartRec.toString()); long startJob = System.currentTimeMillis(); long endJob = startJob; for (Integer id : ids) { // Select Template E2EVelocityTemplate t = new E2EVelocityTemplate(); // Create and load Patient data long startLoad = System.currentTimeMillis(); E2EPatientExport patient = new E2EPatientExport(); patient.setExAllTrue(); long endLoad = startLoad; long startTemplate = 0; long endTemplate = startTemplate; // Load patient data and merge to template String output = ""; if (patient.loadPatient(id.toString())) { endLoad = System.currentTimeMillis(); if (patient.isActive()) { startTemplate = System.currentTimeMillis(); output = t.export(patient); endTemplate = System.currentTimeMillis(); } else { logger.info("[Demo: ".concat(id.toString()).concat("] Not active - skipped")); skipped++; continue; } } else { endLoad = System.currentTimeMillis(); logger.error("[Demo: ".concat(id.toString()).concat("] Failed to load")); failure++; continue; } long startPost = System.currentTimeMillis(); long endPost = startPost; // Attempt to perform HTTP POST request try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(e2eUrl); // Assemble Multi-part Request StringBuilder sbFile = reuseStringBuilder(sb); sbFile.append("output_").append(id).append(".xml"); ByteArrayBody body = new ByteArrayBody(output.getBytes(), "text/xml", sbFile.toString()); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("content", body); httpPost.setEntity(reqEntity); // Send HTTP POST request HttpResponse response = httpclient.execute(httpPost); if (response != null && response.getStatusLine().getStatusCode() == 201) { success++; } else { logger.warn(response.getStatusLine()); failure++; } } catch (HttpHostConnectException e) { logger.error("Connection to ".concat(e2eUrl).concat(" refused")); failure++; } catch (NoRouteToHostException e) { logger.error("Can't resolve route to ".concat(e2eUrl)); failure++; } catch (Exception e) { logger.error("Error", e); failure++; } finally { endPost = System.currentTimeMillis(); } // Log Record completion + benchmarks StringBuilder sbTimer = reuseStringBuilder(sb); sbTimer.append("[Demo: ").append(id); sbTimer.append("] L:").append((endLoad - startLoad) / 1000.0); sbTimer.append(" T:").append((endTemplate - startTemplate) / 1000.0); sbTimer.append(" P:").append((endPost - startPost) / 1000.0); logger.info(sbTimer.toString()); } endJob = System.currentTimeMillis(); logger.info("Done E2E export job (" + convertTime(endJob - startJob) + ")"); } catch (Throwable e) { logger.error("Error", e); logger.info("E2E export job aborted"); } finally { // Log final record counts int unaccounted = ids.size() - success - failure - skipped; sb = reuseStringBuilder(sb); sb.append(success).append(" records processed"); if (failure > 0) sb.append("\n").append(failure).append(" records failed"); if (skipped > 0) sb.append("\n").append(skipped).append(" records skipped"); if (unaccounted > 0) sb.append("\n").append(unaccounted).append(" records unaccounted"); logger.info(sb.toString()); DbConnectionFilter.releaseAllThreadDbResources(); } }
From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java
private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken) throws URISyntaxException, UnsupportedEncodingException { String host = msgRequest.getTargetHost(); if (host == null) throw new URISyntaxException(host, "null URI"); if (!host.endsWith("/")) host += '/'; String address = msgRequest.getTargetAddress(); if (address == null) address = ""; if (address.startsWith("/")) address = address.substring(1);//w w w .ja v a2s . c o m String uriString = host + address; try { URL url = new URL(uriString); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); uriString = uri.toURL().toString(); } catch (MalformedURLException e) { throw new URISyntaxException(uriString, e.getMessage()); } if (msgRequest.getQuery() != null) uriString += "?" + msgRequest.getQuery(); // new URI(uriString); HttpRequestBase request = null; if (msgRequest.getMethod().equals(Method.POST)) { HttpPost post = new HttpPost(uriString); HttpEntity httpEntity = null; if (msgRequest.getRequestParams() != null) { // if body and requestparams are either not null there is an // exception if (msgRequest.getBody() != null && msgRequest != null) { throw new IllegalArgumentException("body and requestParams cannot be either populated"); } httpEntity = new MultipartEntity(); for (RequestParam param : msgRequest.getRequestParams()) { if (param.getParamName() == null || param.getParamName().trim().length() == 0) { throw new IllegalArgumentException("paramName cannot be null or empty"); } if (param instanceof FileRequestParam) { FileRequestParam fileparam = (FileRequestParam) param; ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody( fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename())); } if (param instanceof ObjectRequestParam) { ObjectRequestParam objectparam = (ObjectRequestParam) param; ((MultipartEntity) httpEntity).addPart(param.getParamName(), new StringBody(convertObject(objectparam.getVars()))); } } // mpe.addPart("file", // new ByteArrayBody(msgRequest.getFileContent(), "")); // post.setEntity(mpe); } if (msgRequest.getBody() != null) { httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET); ((StringEntity) httpEntity).setContentType(msgRequest.getContentType()); } post.setEntity(httpEntity); request = post; } else if (msgRequest.getMethod().equals(Method.PUT)) { HttpPut put = new HttpPut(uriString); if (msgRequest.getBody() != null) { StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET); se.setContentType(msgRequest.getContentType()); put.setEntity(se); } request = put; } else if (msgRequest.getMethod().equals(Method.DELETE)) { request = new HttpDelete(uriString); } else { // default: GET request = new HttpGet(uriString); } Map<String, String> headers = new HashMap<String, String>(); // default headers if (appToken != null) { headers.put(RequestHeader.APP_TOKEN.toString(), appToken); } if (authToken != null) { // is here for compatibility headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken); headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken); } headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType()); if (msgRequest.getCustomHeaders() != null) { headers.putAll(msgRequest.getCustomHeaders()); } for (String key : headers.keySet()) { request.addHeader(key, headers.get(key)); } return request; }
From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java
@Override public final <RS> Will<Response<RS>> post(String resource, MultiPartRequest request, Class<RS> clazz) throws RestEndpointIOException { HttpPost post = new HttpPost(spliceUrl(resource)); try {/* w ww. j a va 2 s.c o m*/ MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (MultiPartRequest.MultiPartSerialized<?> serializedPart : request.getSerializedRQs()) { Serializer serializer = getSupportedSerializer(serializedPart); builder.addPart(serializedPart.getPartName(), new StringBody(new String(serializer.serialize(serializedPart.getRequest())), ContentType.parse(serializer.getMimeType()))); } for (MultiPartRequest.MultiPartBinary partBinaty : request.getBinaryRQs()) { builder.addPart(partBinaty.getPartName(), new ByteArrayBody(partBinaty.getData().read(), ContentType.parse(partBinaty.getContentType()), partBinaty.getFilename())); } /* Here is some dirty hack to avoid problem with MultipartEntity and asynchronous http client * Details can be found here: http://comments.gmane.org/gmane.comp.apache.httpclient.user/2426 * * The main idea is to replace MultipartEntity with NByteArrayEntity once first * doesn't support #getContent method * which is required for async client implementation. So, we are copying response * body as byte array to NByteArrayEntity to * leave it unmodified. * * Alse we need to add boundary value to content type header. Details are here: * http://en.wikipedia.org/wiki/Delimiter#Content_boundary * MultipartEntity generates correct header by yourself, but we need to put it * manually once we replaced entity type to NByteArrayEntity */ String boundary = "-------------" + UUID.randomUUID().toString(); builder.setBoundary(boundary); ByteArrayOutputStream baos = new ByteArrayOutputStream(); builder.build().writeTo(baos); post.setEntity(new NByteArrayEntity(baos.toByteArray(), ContentType.MULTIPART_FORM_DATA)); post.setHeader("Content-Type", "multipart/form-data;boundary=" + boundary); } catch (Exception e) { throw new RestEndpointIOException("Unable to build post multipart request", e); } return executeInternal(post, new ClassConverterCallback<RS>(serializers, clazz)); }
From source file:net.sf.jaceko.mock.it.helper.request.HttpRequestSender.java
private void constructMultipartRequest(HttpEntityEnclosingRequestBase httpRequest, String requestBody, String mediaType, List<RestAttachment> attachments) throws UnsupportedEncodingException { MultipartEntity multipartEntity = new MultipartEntity(); if (requestBody != null) { multipartEntity.addPart("payload", new StringBody(requestBody, mediaType, Charset.forName("UTF-8"))); }//w ww.jav a 2 s .c o m int attachmentCount = 0; for (RestAttachment attachment : attachments) { String attachmentName = "attachment" + (++attachmentCount); multipartEntity.addPart(attachmentName, new ByteArrayBody(attachment.getBinaryContent(), attachment.getMediaType(), attachmentName)); } httpRequest.setEntity(multipartEntity); }
From source file:org.opendatakit.aggregate.externalservice.REDCapServer.java
public void submitFile(String recordID, String fileField, BlobSubmissionType blob_value, CallingContext cc) throws MalformedURLException, IOException, EntityNotFoundException, ODKDatastoreException { String contentType = blob_value.getContentType(1, cc); String filename = blob_value.getUnrootedFilename(1, cc); filename = fileField + filename.substring(filename.lastIndexOf('.')); /**/*w w w . ja v a2 s . c o m*/ * REDCap server appears to be highly irregular in the structure of the * form-data submission it will accept from the client. The following should * work, but either resets the socket or returns a 403 error. */ MultipartEntity postentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, UTF_CHARSET); FormBodyPart fb; fb = new FormBodyPart("token", new StringBody(getApiKey(), UTF_CHARSET)); postentity.addPart(fb); fb = new FormBodyPart("content", new StringBody("file", UTF_CHARSET)); postentity.addPart(fb); fb = new FormBodyPart("action", new StringBody("import", UTF_CHARSET)); postentity.addPart(fb); fb = new FormBodyPart("record", new StringBody(recordID, UTF_CHARSET)); postentity.addPart(fb); fb = new FormBodyPart("field", new StringBody(fileField, UTF_CHARSET)); postentity.addPart(fb); fb = new FormBodyPart("file", new ByteArrayBody(blob_value.getBlob(1, cc), contentType, filename)); postentity.addPart(fb); submitPost("File import", postentity, null, cc); }
From source file:com.ibm.ws.lars.rest.RepositoryContext.java
public String doPostMultipart(String url, String name, String json, byte[] content, ContentType contentType, int expectedStatusCode) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(fullURL + url); HttpEntity requestEntity = MultipartEntityBuilder.create() .addPart("attachmentInfo", new StringBody(json, ContentType.APPLICATION_JSON)) .addPart(name, new ByteArrayBody(content, contentType, name)).build(); post.setEntity(requestEntity);/* w w w . j a v a 2 s. c o m*/ return doRequest(post, expectedStatusCode); }
From source file:it.greenvulcano.gvesb.virtual.gv_multipart.MultipartCallOperation.java
/** * // w ww . java 2 s . c o m * @param gvBuffer * for transport data in GreenVulcano * @return the GVBuffer * * @see it.greenvulcano.gvesb.virtual.CallOperation#perform(it.greenvulcano.gvesb.buffer.GVBuffer) */ @Override public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException { StringBuffer callDump = new StringBuffer(); callDump.append("Performing RestCallOperation " + name).append("\n ").append("URL: ").append(url); if (isByteArray == true && gvBuffer.getObject() != null) { byte[] requestData; if (gvBuffer.getObject() instanceof byte[]) { requestData = (byte[]) gvBuffer.getObject(); } else { requestData = gvBuffer.getObject().toString().getBytes(); } callDump.append("\n ").append("Content-Length: " + requestData.length); ByteArrayBody byteArrayPart = new ByteArrayBody(requestData, contentType, fileName); multipartEntityBuilder.addPart(name, byteArrayPart); } else if (isFileProperty == true) { file = new File(gvBuffer.getProperty("DIR")); FileBody filePart = new FileBody(file, this.contentType, fileName); multipartEntityBuilder.addPart(filePartName, filePart); } try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpEntity = multipartEntityBuilder.build(); String responseString = EntityUtils.toString(httpEntity); httpPost.setEntity(multipartEntityBuilder.build()); for (Map.Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); httpPost.setHeader(key, value); } CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); Header[] responseHeaders = response.getAllHeaders(); Header contentType = responseEntity.getContentType(); InputStream responseStream = null; response.getStatusLine(); responseStream = responseEntity.getContent(); for (Header header : response.getAllHeaders()) { if (Objects.nonNull(header)) { gvBuffer.setProperty(header.getName(), header.getValue()); } } if (responseStream != null) { byte[] responseData = IOUtils.toByteArray(responseStream); String responseContentType = Optional .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse(""); if (responseContentType.startsWith("application/json") || responseContentType.startsWith("application/javascript")) { gvBuffer.setObject(new String(responseData, "UTF-8")); } else { gvBuffer.setObject(responseData); } } else { gvBuffer.setObject(null); } gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(response.getStatusLine())); gvBuffer.setProperty(RESPONSE_MESSAGE, String.valueOf(response)); callDump.append("\n " + gvBuffer); response.close(); logger.debug(callDump.toString()); } catch (Exception exc) { throw new CallException("GV_CALL_SERVICE_ERROR", new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() }, { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } }, exc); } return gvBuffer; }