List of usage examples for org.apache.commons.httpclient.methods.multipart ByteArrayPartSource ByteArrayPartSource
public ByteArrayPartSource(String paramString, byte[] paramArrayOfByte)
From source file:org.onebusaway.nyc.integration_tests.TraceSupport.java
/**** * /*from w ww . j av a 2 s . c o m*/ ****/ private ByteArrayPartSource getResourceAsPartSource(String fileName, InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int rc = in.read(buffer); if (rc < 0) break; out.write(buffer, 0, rc); } in.close(); return new ByteArrayPartSource(fileName, out.toByteArray()); }
From source file:org.openmicroscopy.is.HttpImageServer.java
public void setPixels(long pixelsID, byte[] buf, boolean bigEndian) throws ImageServerException { MultipartPostMethod post = startCall(); try {/* www . j a v a 2 s . co m*/ post.addParameter("Method", "SetPixels"); post.addParameter("PixelsID", Long.toString(pixelsID)); post.addParameter("UploadSize", Long.toString(buf.length)); post.addParameter("BigEndian", bigEndian ? "1" : "0"); post.addPart(new FilePart("Pixels", new ByteArrayPartSource("pixels", buf))); executeCall(post); return; } finally { finishCall(post); } }
From source file:org.openmicroscopy.is.HttpImageServer.java
public void setStack(long pixelsID, int theC, int theT, byte[] buf, boolean bigEndian) throws ImageServerException { MultipartPostMethod post = startCall(); try {//www . j a v a2s . c o m post.addParameter("Method", "SetStack"); post.addParameter("PixelsID", Long.toString(pixelsID)); post.addParameter("theC", Integer.toString(theC)); post.addParameter("theT", Integer.toString(theT)); post.addParameter("UploadSize", Long.toString(buf.length)); post.addParameter("BigEndian", bigEndian ? "1" : "0"); post.addPart(new FilePart("Pixels", new ByteArrayPartSource("pixels", buf))); executeCall(post); return; } finally { finishCall(post); } }
From source file:org.openmicroscopy.is.HttpImageServer.java
public void setPlane(long pixelsID, int theZ, int theC, int theT, byte[] buf, boolean bigEndian) throws ImageServerException { MultipartPostMethod post = startCall(); try {//from ww w.j ava 2s. c om post.addParameter("Method", "SetPlane"); post.addParameter("PixelsID", Long.toString(pixelsID)); post.addParameter("theZ", Integer.toString(theZ)); post.addParameter("theC", Integer.toString(theC)); post.addParameter("theT", Integer.toString(theT)); post.addParameter("UploadSize", Long.toString(buf.length)); post.addParameter("BigEndian", bigEndian ? "1" : "0"); post.addPart(new FilePart("Pixels", new ByteArrayPartSource("pixels", buf))); executeCall(post); return; } finally { finishCall(post); } }
From source file:org.openmicroscopy.is.HttpImageServer.java
public void setROI(long pixelsID, int x0, int y0, int z0, int c0, int t0, int x1, int y1, int z1, int c1, int t1, byte[] buf, boolean bigEndian) throws ImageServerException { String roi = x0 + "," + y0 + "," + z0 + "," + c0 + "," + t0 + "," + x1 + "," + y1 + "," + z1 + "," + c1 + "," + t1; MultipartPostMethod post = startCall(); try {/* w w w .j a va 2s . c o m*/ post.addParameter("Method", "SetROI"); post.addParameter("PixelsID", Long.toString(pixelsID)); post.addParameter("ROI", roi); post.addParameter("UploadSize", Long.toString(buf.length)); post.addParameter("BigEndian", bigEndian ? "1" : "0"); post.addPart(new FilePart("Pixels", new ByteArrayPartSource("pixels", buf))); executeCall(post); return; } finally { finishCall(post); } }
From source file:org.openmrs.module.sync.server.ServerConnection.java
public static ConnectionResponse sendExportedData(String url, String username, String password, String content, boolean isResponse) { // Default response - default constructor instantiates contains error codes ConnectionResponse syncResponse = new ConnectionResponse(); HttpClient client = new HttpClient(); url = url + SyncConstants.DATA_IMPORT_SERVLET; log.info("POST multipart request to " + url); if (url.startsWith("https")) { try {/*from w ww . j a va 2 s . c o m*/ if (Boolean.parseBoolean(Context.getAdministrationService() .getGlobalProperty(SyncConstants.PROPERTY_ALLOW_SELFSIGNED_CERTS))) { // It is necessary to provide a relative url (from the host name and port to the right) String relativeUrl; URI uri = new URI(url, true); String host = uri.getHost(); int port = uri.getPort(); // URI.getPort() returns -1 if port is not explicitly set if (port <= 0) { port = SyncConstants.DEFAULT_HTTPS_PORT; relativeUrl = url.split(host, 2)[1]; } else { relativeUrl = url.split(host + ":" + port, 2)[1]; } Protocol easyhttps = new Protocol("https", (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), port); client.getHostConfiguration().setHost(host, port, easyhttps); url = relativeUrl; } } catch (IOException ioe) { log.error("Unable to configure SSL to accept self-signed certificates"); } catch (GeneralSecurityException e) { log.error("Unable to configure SSL to accept self-signed certificates"); } } PostMethod method = new PostMethod(url); try { boolean useCompression = Boolean.parseBoolean(Context.getAdministrationService() .getGlobalProperty(SyncConstants.PROPERTY_ENABLE_COMPRESSION, "true")); log.info("use compression: " + useCompression); // Compress content ConnectionRequest request = new ConnectionRequest(content, useCompression); // Create up multipart request Part[] parts = { new FilePart("syncDataFile", new ByteArrayPartSource("syncDataFile", request.getBytes())), new StringPart("username", username), new StringPart("password", password), new StringPart("compressed", String.valueOf(useCompression)), new StringPart("isResponse", String.valueOf(isResponse)), new StringPart("checksum", String.valueOf(request.getChecksum())) }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); // Open a connection to the server and post the data client.getHttpConnectionManager().getParams().setSoTimeout(ServerConnection.getTimeout().intValue()); client.getHttpConnectionManager().getParams() .setConnectionTimeout(ServerConnection.getTimeout().intValue()); int status = client.executeMethod(method); // As long as the response is OK (200) if (status == HttpStatus.SC_OK) { // Decompress the response from the server //log.info("Response from server:" + method.getResponseBodyAsString()); // Check to see if the child/parent sent back a compressed response Header compressionHeader = method.getResponseHeader("Enable-Compression"); useCompression = (compressionHeader != null) ? new Boolean(compressionHeader.getValue()) : false; log.info("Response header Enable-Compression: " + useCompression); // Decompress the data received (if compression is enabled) syncResponse = new ConnectionResponse(method.getResponseBodyAsStream(), useCompression); // Now we want to validate the checksum Header checksumHeader = method.getResponseHeader("Content-Checksum"); long checksumReceived = (checksumHeader != null) ? new Long(checksumHeader.getValue()) : 0; log.info("Response header Content-Checksum: " + checksumReceived); log.info("checksum value received in response header: " + checksumReceived); log.info("checksum of payload: " + syncResponse.getChecksum()); // TODO Need to figure out what to do with this response if (checksumReceived > 0 && (checksumReceived != syncResponse.getChecksum())) { log.error("ERROR: FAILED CHECKSUM!"); syncResponse.setState(ServerConnectionState.CONNECTION_FAILED); // contains error message } } // if there's an error response code we should set the tran else { // HTTP error response code syncResponse .setResponsePayload("HTTP " + status + " Error Code: " + method.getResponseBodyAsString()); syncResponse.setState(ServerConnectionState.CONNECTION_FAILED); // contains error message } } catch (MalformedURLException mue) { log.error("Malformed URL " + url, mue); syncResponse.setState(ServerConnectionState.MALFORMED_URL); } catch (Exception e) { // all other exceptions really just mean that the connection was bad log.error("Error occurred while sending/receiving data ", e); syncResponse.setState(ServerConnectionState.CONNECTION_FAILED); } finally { method.releaseConnection(); } return syncResponse; }
From source file:org.pentaho.platform.util.client.PublisherUtil.java
/** * Publishes a list of files and a datasource to the server with basic authentication to the server * //from w w w.j a va2s . c o m * @param publishURL * The URL of the Pentaho server * @param publishPath * The path in the solution to place the files * @param publishFiles * Array of File objects to post to the server * @param dataSource * The datasource to publish to the server * @param publishPassword * The publishing password for the server * @param serverUserid * The userid to authenticate to the server * @param serverPassword * The password to authenticate with the server * @param overwrite * Whether the server should overwrite the file if it exists already * @param mkdirs * Whether the server should create any missing folders on the publish path * @return Server response as a string */ public static int publish(final String publishURL, final String publishPath, final File[] publishFiles, final String publishPassword, final String serverUserid, final String serverPassword, final boolean overwrite, final boolean mkdirs) { int status = -1; System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "warn"); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "warn"); //$NON-NLS-1$ //$NON-NLS-2$ String fullURL = null; try { fullURL = publishURL + "?publishPath=" + URLEncoder.encode(publishPath, "UTF-8"); } catch (UnsupportedEncodingException e) { fullURL = publishURL + "?publishPath=" + publishPath; } if (publishPassword == null) { throw new IllegalArgumentException( Messages.getInstance().getErrorString("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED")); //$NON-NLS-1$ } fullURL += "&publishKey=" + PublisherUtil.getPasswordKey(publishPassword); //$NON-NLS-1$ fullURL += "&overwrite=" + overwrite; //$NON-NLS-1$ fullURL += "&mkdirs=" + mkdirs; //$NON-NLS-1$ PostMethod filePost = new PostMethod(fullURL); Part[] parts = new Part[publishFiles.length]; for (int i = 0; i < publishFiles.length; i++) { try { File file = publishFiles[i]; FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); String reportNameEncoded = (URLEncoder.encode(file.getName(), "UTF-8")); ByteArrayPartSource source = new ByteArrayPartSource(reportNameEncoded, out.toByteArray()); parts[i] = new FilePart(reportNameEncoded, source, FilePart.DEFAULT_CONTENT_TYPE, "UTF-8"); } catch (Exception e) { PublisherUtil.logger.error(null, e); } } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); try { // If server userid/password was supplied, use basic authentication to // authenticate with the server. if ((serverUserid != null) && (serverUserid.length() > 0) && (serverPassword != null) && (serverPassword.length() > 0)) { Credentials creds = new UsernamePasswordCredentials(serverUserid, serverPassword); client.getState().setCredentials(AuthScope.ANY, creds); client.getParams().setAuthenticationPreemptive(true); } status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { String postResult = filePost.getResponseBodyAsString(); if (postResult != null) { try { return Integer.parseInt(postResult.trim()); } catch (NumberFormatException e) { PublisherUtil.logger.error(null, e); return PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS; } } } else if (status == HttpStatus.SC_UNAUTHORIZED) { return PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS; } } catch (HttpException e) { PublisherUtil.logger.error(null, e); } catch (IOException e) { PublisherUtil.logger.error(null, e); } // return Messages.getString("REPOSITORYFILEPUBLISHER.USER_PUBLISHER_FAILED"); //$NON-NLS-1$ return PublisherUtil.FILE_ADD_FAILED; }
From source file:org.redpill.alfresco.pdfapilot.client.PdfaPilotClientImpl.java
@Override public void create(String filename, InputStream inputStream, OutputStream outputStream, PdfaPilotTransformationOptions options) { HttpClient client = getHttpClient(); String pdfaLevel = options != null ? options.getLevel() : ""; String variant = StringUtils.isBlank(pdfaLevel) ? "pdf" : "pdfa"; String url = _serverUrl + "/bapi/v1/create/" + variant; if (LOG.isDebugEnabled()) { LOG.debug(url);//w w w .j av a2 s . c o m } PostMethod method = new PostMethod(url); method.getParams().setSoTimeout(_aliveCheckTimeout * 1000); method.getHostAuthState().setPreemptive(); method.getParams().setContentCharset("UTF-8"); method.addRequestHeader("Accept-Charset", "UTF-8"); method.addRequestHeader("Accept-Language", "en-ca,en;q=0.8"); // method.addRequestHeader("Accept-Content", "application/text"); try { JSONObject json = new JSONObject(); json.put("nodeRef", options != null && options.getSourceNodeRef() != null ? options.getSourceNodeRef().toString() : null); // create a new array of Part objects List<Part> parts = new ArrayList<Part>(); // add the file part, the actual binary data parts.add(new FilePart("file", new ByteArrayPartSource(FilenameUtils.getName(filename), IOUtils.toByteArray(inputStream)), null, "UTF-8")); // add the filename part parts.add(new StringPart("filename", FilenameUtils.getName(filename), "UTF-8")); // *if* there's a pdfaLavel part, and that if (StringUtils.isNotBlank(pdfaLevel)) { parts.add(new StringPart("level", pdfaLevel, "UTF-8")); } // and last, add the data part, this is a json object parts.add(new StringPart("data", json.toString(), "UTF-8")); method.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), method.getParams())); int status = client.executeMethod(method); if (status != 200) { throw new RuntimeException("Create PDF failed: " + method.getStatusLine() + "\n" + method.getResponseBodyAsString().trim()); } IOUtils.copy(method.getResponseBodyAsStream(), outputStream); } catch (Throwable e) { throw new RuntimeException(e.getMessage(), e); } finally { method.releaseConnection(); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } }
From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java
public String executePost(String url, Map<String, String> parameters, List<UploadItem> uploadItems, IProgressMonitor monitor) throws ReviewboardException { PostMethod postRequest = new PostMethod(stripSlash(location.getUrl()) + url); configureRequestForJson(postRequest); List<Part> parts = new ArrayList<Part>(); for (Map.Entry<String, String> paramEntry : parameters.entrySet()) parts.add(new StringPart(paramEntry.getKey(), paramEntry.getValue())); for (UploadItem uploadItem : uploadItems) { String partName = uploadItem.getName(); parts.add(new FilePart(partName, new ByteArrayPartSource(uploadItem.getFileName(), uploadItem.getContent()))); }//from ww w . ja v a 2s. c om postRequest.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), postRequest.getParams())); return executeMethod(postRequest, monitor); }
From source file:org.safecreative.api.RegisterWork.java
/** * @param fileName File name//from w w w .jav a2 s. co m * @param workFile byte array to register * @param customValues Work containing register parameters to override those of defined profile, * optional if license is defined * @param checksum * @return registration code * @throws Exception */ public String registerWork(String fileName, byte[] workFile, Work work, String checksum) throws Exception { return registerWork(fileName, new ByteArrayPartSource(fileName, workFile), work, checksum); }