List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build
public HttpEntity build()
From source file:com.lgallardo.qbittorrentclient.JSONParser.java
public String postCommand(String command, String hash) throws JSONParserStatusCodeException { String key = "hash"; String urlContentType = "application/x-www-form-urlencoded"; String limit = ""; String tracker = ""; String boundary = null;/* w w w . j ava 2 s . c o m*/ String fileId = ""; String filePriority = ""; String result = ""; StringBuilder fileContent = null; HttpResponse httpResponse; DefaultHttpClient httpclient; String url = ""; String label = ""; if ("start".equals(command) || "startSelected".equals(command)) { url = "command/resume"; } if ("pause".equals(command) || "pauseSelected".equals(command)) { url = "command/pause"; } if ("delete".equals(command) || "deleteSelected".equals(command)) { url = "command/delete"; key = "hashes"; } if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) { url = "command/deletePerm"; key = "hashes"; } if ("addTorrent".equals(command)) { url = "command/download"; key = "urls"; } if ("addTracker".equals(command)) { url = "command/addTrackers"; key = "hash"; } if ("addTorrentFile".equals(command)) { url = "command/upload"; key = "urls"; boundary = "-----------------------" + (new Date()).getTime(); urlContentType = "multipart/form-data; boundary=" + boundary; } if ("pauseall".equals(command)) { url = "command/pauseall"; } if ("pauseAll".equals(command)) { url = "command/pauseAll"; } if ("resumeall".equals(command)) { url = "command/resumeall"; } if ("resumeAll".equals(command)) { url = "command/resumeAll"; } if ("increasePrio".equals(command)) { url = "command/increasePrio"; key = "hashes"; } if ("decreasePrio".equals(command)) { url = "command/decreasePrio"; key = "hashes"; } if ("maxPrio".equals(command)) { url = "command/topPrio"; key = "hashes"; } if ("minPrio".equals(command)) { url = "command/bottomPrio"; key = "hashes"; } if ("setFilePrio".equals(command)) { url = "command/setFilePrio"; String[] tmpString = hash.split("&"); hash = tmpString[0]; fileId = tmpString[1]; filePriority = tmpString[2]; // Log.d("Debug", "hash: " + hash); // Log.d("Debug", "fileId: " + fileId); // Log.d("Debug", "filePriority: " + filePriority); } if ("setQBittorrentPrefefrences".equals(command)) { url = "command/setPreferences"; key = "json"; } if ("setUploadRateLimit".equals(command)) { url = "command/setTorrentsUpLimit"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { limit = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { limit = "-1"; } } if ("setDownloadRateLimit".equals(command)) { url = "command/setTorrentsDlLimit"; key = "hashes"; Log.d("Debug", "Hash before: " + hash); String[] tmpString = hash.split("&"); hash = tmpString[0]; try { limit = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { limit = "-1"; } // Log.d("Debug", "url: " + url); // Log.d("Debug", "Hashes: " + hash + " | limit: " + limit); } if ("recheckSelected".equals(command)) { url = "command/recheck"; } if ("toggleFirstLastPiecePrio".equals(command)) { url = "command/toggleFirstLastPiecePrio"; key = "hashes"; } if ("toggleSequentialDownload".equals(command)) { url = "command/toggleSequentialDownload"; key = "hashes"; } if ("toggleAlternativeSpeedLimits".equals(command)) { // Log.d("Debug", "Toggling alternative rates"); url = "command/toggleAlternativeSpeedLimits"; key = "hashes"; } if ("setLabel".equals(command)) { url = "command/setLabel"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { label = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { label = ""; } // Log.d("Debug", "Hash2: " + hash + "| label2: " + label); } if ("setCategory".equals(command)) { url = "command/setCategory"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { label = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { label = ""; } // Log.d("Debug", "Hash2: " + hash + "| label2: " + label); } if ("alternativeSpeedLimitsEnabled".equals(command)) { // Log.d("Debug", "Getting alternativeSpeedLimitsEnabled"); url = "command/alternativeSpeedLimitsEnabled"; key = "hashes"; } // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; } HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpPost httpget = new HttpPost(url); if ("addTorrent".equals(command)) { URI hash_uri = new URI(hash); hash = hash_uri.toString(); } if ("addTracker".equals(command)) { String[] tmpString = hash.split("&"); hash = tmpString[0]; URI hash_uri = new URI(hash); hash = hash_uri.toString(); try { tracker = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { tracker = ""; } // Log.d("Debug", "addTracker - hash: " + hash); // Log.d("Debug", "addTracker - tracker: " + tracker); } // In order to pass the hash we must set the pair name value BasicNameValuePair bnvp = new BasicNameValuePair(key, hash); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(bnvp); // Add limit if (!limit.equals("")) { Log.d("Debug", "JSONParser - Limit: " + limit); nvps.add(new BasicNameValuePair("limit", limit)); } // Set values for setting file priority if ("setFilePrio".equals(command)) { nvps.add(new BasicNameValuePair("id", fileId)); nvps.add(new BasicNameValuePair("priority", filePriority)); } // Add label if (label != null && !label.equals("")) { label = Uri.decode(label); if ("setLabel".equals(command)) { nvps.add(new BasicNameValuePair("label", label)); } else { nvps.add(new BasicNameValuePair("category", label)); } // Log.d("Debug", "Hash3: " + hash + "| label3: >" + label + "<"); } // Add tracker if (tracker != null && !tracker.equals("")) { nvps.add(new BasicNameValuePair("urls", tracker)); // Log.d("Debug", ">Tracker: " + key + " | " + hash + " | " + tracker + "<"); } String entityValue = URLEncodedUtils.format(nvps, HTTP.UTF_8); // This replaces encoded char "+" for "%20" so spaces can be passed as parameter entityValue = entityValue.replaceAll("\\+", "%20"); StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8); stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE); httpget.setEntity(stringEntity); // Set content type and urls if ("addTorrent".equals(command) || "increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command) || "setFilePrio".equals(command) || "toggleAlternativeSpeedLimits".equals(command) || "alternativeSpeedLimitsEnabled".equals(command) || "setLabel".equals(command) || "setCategory".equals(command) || "addTracker".equals(command)) { httpget.setHeader("Content-Type", urlContentType); } // Set cookie if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } // Set content type and urls if ("addTorrentFile".equals(command)) { httpget.setHeader("Content-Type", urlContentType); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Add boundary builder.setBoundary(boundary); // Add torrent file as binary File file = new File(hash); // FileBody fileBody = new FileBody(file); // builder.addPart("file", fileBody); builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, hash); // Build entity HttpEntity entity = builder.build(); // Set entity to http post httpget.setEntity(entity); } httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); // Log.d("Debug", "JSONPArser - mStatusCode: " + mStatusCode); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); // Log.d("Debug", "JSONPArser - command result: " + result); return result; } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("Debug", "Client: " + e.toString()); e.printStackTrace(); } catch (SSLPeerUnverifiedException e) { Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString()); throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE); } catch (IOException e) { Log.e("Debug", "IO: " + e.toString()); httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(TIMEOUT_ERROR); } catch (JSONParserStatusCodeException e) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(e.getCode()); } catch (Exception e) { Log.e("Debug", "Generic: " + e.toString()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } return null; }
From source file:org.rundeck.api.ApiCall.java
private <T> T requestWithEntity(ApiPathBuilder apiPath, Handler<HttpResponse, T> handler, HttpEntityEnclosingRequestBase httpPost) { if (null != apiPath.getAccept()) { httpPost.setHeader("Accept", apiPath.getAccept()); }/*from ww w . j ava2s .co m*/ // POST a multi-part request, with all attachments if (apiPath.getAttachments().size() > 0 || apiPath.getFileAttachments().size() > 0) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ArrayList<File> tempfiles = new ArrayList<>(); //attach streams for (Entry<String, InputStream> attachment : apiPath.getAttachments().entrySet()) { if (client.isUseIntermediateStreamFile()) { //transfer to file File f = copyToTempfile(attachment.getValue()); multipartEntityBuilder.addBinaryBody(attachment.getKey(), f); tempfiles.add(f); } else { multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue()); } } if (tempfiles.size() > 0) { handler = TempFileCleanupHandler.chain(handler, tempfiles); } //attach files for (Entry<String, File> attachment : apiPath.getFileAttachments().entrySet()) { multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue()); } httpPost.setEntity(multipartEntityBuilder.build()); } else if (apiPath.getForm().size() > 0) { try { httpPost.setEntity(new UrlEncodedFormEntity(apiPath.getForm(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RundeckApiException("Unsupported encoding: " + e.getMessage(), e); } } else if (apiPath.getContentStream() != null && apiPath.getContentType() != null) { if (client.isUseIntermediateStreamFile()) { ArrayList<File> tempfiles = new ArrayList<>(); File f = copyToTempfile(apiPath.getContentStream()); tempfiles.add(f); httpPost.setEntity(new FileEntity(f, ContentType.create(apiPath.getContentType()))); handler = TempFileCleanupHandler.chain(handler, tempfiles); } else { InputStreamEntity entity = new InputStreamEntity(apiPath.getContentStream(), ContentType.create(apiPath.getContentType())); httpPost.setEntity(entity); } } else if (apiPath.getContents() != null && apiPath.getContentType() != null) { ByteArrayEntity bae = new ByteArrayEntity(apiPath.getContents(), ContentType.create(apiPath.getContentType())); httpPost.setEntity(bae); } else if (apiPath.getContentFile() != null && apiPath.getContentType() != null) { httpPost.setEntity( new FileEntity(apiPath.getContentFile(), ContentType.create(apiPath.getContentType()))); } else if (apiPath.getXmlDocument() != null) { httpPost.setHeader("Content-Type", "application/xml"); httpPost.setEntity(new EntityTemplate(new DocumentContentProducer(apiPath.getXmlDocument()))); } else if (apiPath.isEmptyContent()) { //empty content } else { throw new IllegalArgumentException("No Form or Multipart entity for POST content-body"); } return execute(httpPost, handler); }
From source file:com.intuit.karate.http.apache.ApacheHttpClient.java
@Override protected HttpEntity getEntity(List<MultiPartItem> items, String mediaType) { boolean hasNullName = false; for (MultiPartItem item : items) { if (item.getName() == null) { hasNullName = true;//from w w w . j a v a 2 s . co m break; } } if (hasNullName) { // multipart/related String boundary = createBoundary(); String text = getAsStringEntity(items, boundary); ContentType ct = ContentType.create(mediaType) .withParameters(new BasicNameValuePair("boundary", boundary)); return new StringEntity(text, ct); } else { MultipartEntityBuilder builder = MultipartEntityBuilder.create() .setContentType(ContentType.create(mediaType)); for (MultiPartItem item : items) { if (item.getValue() == null || item.getValue().isNull()) { logger.warn("ignoring null multipart value for key: {}", item.getName()); continue; } String name = item.getName(); ScriptValue sv = item.getValue(); if (name == null) { // builder.addPart(bodyPart); } else { FormBodyPartBuilder formBuilder = FormBodyPartBuilder.create().setName(name); ContentBody contentBody; switch (sv.getType()) { case INPUT_STREAM: InputStream is = (InputStream) sv.getValue(); contentBody = new InputStreamBody(is, ContentType.APPLICATION_OCTET_STREAM, name); break; case XML: contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_XML); break; case JSON: contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_JSON); break; default: contentBody = new StringBody(sv.getAsString(), ContentType.TEXT_PLAIN); } formBuilder = formBuilder.setBody(contentBody); builder = builder.addPart(formBuilder.build()); } } return builder.build(); } }
From source file:org.wso2.store.client.ArtifactPublisher.java
/** * Upload assets to ES//from w w w.ja va 2 s .c om * POST asset details to asset upload REST API * If attribute is a physical file seek a file in a resources directory and upload as multipart attachment. * @param assetArr Array of assets * @param dir resource files directory */ private void uploadAssets(Asset[] assetArr, File dir) { HashMap<String, String> attrMap; MultipartEntityBuilder multiPartBuilder; List<String> fileAttributes; File imageFile; String responseJson; StringBuilder publisherUrlBuilder; String uploadUrl = hostUrl + ArtifactUploadClientConstants.PUBLISHER_URL + "/"; HttpPost httpPost; CloseableHttpClient httpClient = clientBuilder.build(); CloseableHttpResponse response = null; for (Asset asset : assetArr) { publisherUrlBuilder = new StringBuilder(); if (asset.getId() != null) { publisherUrlBuilder.append(uploadUrl).append(asset.getId()).append("?type=") .append(asset.getType()); } else { publisherUrlBuilder.append(uploadUrl).append("?type=").append(asset.getType()); } multiPartBuilder = MultipartEntityBuilder.create(); multiPartBuilder.addTextBody("sessionId", sessionId); multiPartBuilder.addTextBody("asset", gson.toJson(asset)); attrMap = asset.getAttributes(); httpPost = new HttpPost(publisherUrlBuilder.toString()); //get file type attributes list for asset type fileAttributes = rxtFileAttributesMap.get(asset.getType()); for (String attrKey : attrMap.keySet()) { //check attribute one by one whether is it a file type if (fileAttributes != null && fileAttributes.contains(attrKey)) { imageFile = new File(dir + File.separator + ArtifactUploadClientConstants.RESOURCE_DIR_NAME + File.separator + attrMap.get(attrKey)); multiPartBuilder.addBinaryBody(attrKey, imageFile); } } httpPost.setEntity(multiPartBuilder.build()); try { response = httpClient.execute(httpPost, httpContext); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { log.info("Asset " + asset.getName() + " uploaded successfully"); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) { log.info("Asset " + asset.getName() + " updated successfully"); } else { responseJson = EntityUtils.toString(response.getEntity()); log.info("Asset " + asset.getName() + " not uploaded successfully " + responseJson); } } catch (IOException ex) { log.error("Asset Id:" + asset.getId() + " Name;" + asset.getName()); log.error("Error in asset Upload", ex); log.debug("Asset upload fail:" + asset); } finally { IOUtils.closeQuietly(response); } } IOUtils.closeQuietly(response); IOUtils.closeQuietly(httpClient); }
From source file:com.lehman.ic9.net.httpClient.java
/** * Sets request information for the type of POST request. This is determined * by the post type provided./*from www . j av a 2 s . co m*/ * @param postTypeStr is a String with the postType. * @param Obj is a Javascript object to set for the request. * @param ContentType is a String with the content-type for the custom request. * @throws ic9exception Exception * @throws UnsupportedEncodingException Exception */ @SuppressWarnings("unchecked") private void setPostInfo(String postTypeStr, Object Obj, String ContentType) throws ic9exception, UnsupportedEncodingException { postType pt = this.getPostType(postTypeStr); if (pt == postType.URL_ENCODED) { Map<String, Object> jobj = (Map<String, Object>) Obj; List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (String key : jobj.keySet()) { Object val = jobj.get(key); nvps.add(new BasicNameValuePair(key, val.toString())); } this.respEnt = new UrlEncodedFormEntity(nvps); } else if (pt == postType.MULTIPART) { MultipartEntityBuilder mpEntBuilder = MultipartEntityBuilder.create(); Map<String, Object> jobj = (Map<String, Object>) Obj; for (String key : jobj.keySet()) { Map<String, Object> part = (Map<String, Object>) jobj.get(key); if (part.containsKey("name") && part.containsKey("data")) { String pkey = (String) part.get("name"); if (part.get("data") instanceof byte[]) { byte[] data = (byte[]) part.get("data"); mpEntBuilder.addPart(key, new ByteArrayBody(data, pkey)); } else if (part.get("data") instanceof String) { String data = (String) part.get("data"); mpEntBuilder.addPart(key, new StringBody(data, org.apache.http.entity.ContentType.DEFAULT_TEXT)); } } else throw new ic9exception( "httpClient.setPotInfo(): Multipart from data expects and object of httpPart objects."); } this.respEnt = mpEntBuilder.build(); } else { if (Obj instanceof String) { StringEntity se = new StringEntity((String) Obj); if (ContentType != null) se.setContentType(ContentType); else throw new ic9exception( "httpClient.setPostInfo(): For custom postType, the third argument for content-type must be set."); this.respEnt = se; } else if (Obj instanceof Map) { Map<String, Object> tobj = (Map<String, Object>) Obj; if (tobj.containsKey("data") && tobj.get("data") instanceof byte[]) { if (ContentType != null) { ByteArrayEntity bae = new ByteArrayEntity((byte[]) Obj); bae.setContentType(ContentType); this.respEnt = bae; } else throw new ic9exception( "httpClient.setPostInfo(): For custom postType, the third argument for content-type must be set."); } else throw new ic9exception( "httpClient.setPostInfo(): Provided object is not of type Buffer or is missing 'data' attribute. (data should be byte[])"); } else throw new ic9exception( "httpClient.setPostInfo(): Second argument to POST call expecting String or Buffer object."); } }
From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java
/** * @see org.opentravel.schemacompiler.repository.Repository#commit(org.opentravel.schemacompiler.repository.RepositoryItem) *///from ww w .j a v a 2 s. c o m @Override public void commit(RepositoryItem item) throws RepositoryException { InputStream wipContent = null; try { validateRepositoryItem(item); // Obtain a file stream for the item's WIP content File wipFile = manager.getFileManager().getLibraryWIPContentLocation(item.getBaseNamespace(), item.getFilename()); if (!wipFile.exists()) { throw new RepositoryException("The work-in-process file does not exist: " + item.getFilename()); } wipContent = new FileInputStream(wipFile); // Build the HTTP request for the remote service RepositoryItemIdentityType itemIdentity = createItemIdentity(item); Marshaller marshaller = RepositoryFileManager.getSharedJaxbContext().createMarshaller(); HttpPost request = newPostRequest(COMMIT_ENDPOINT); MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create(); StringWriter xmlWriter = new StringWriter(); marshaller.marshal(objectFactory.createRepositoryItemIdentity(itemIdentity), xmlWriter); mpEntity.addTextBody("item", xmlWriter.toString(), ContentType.TEXT_XML); mpEntity.addBinaryBody("fileContent", toByteArray(wipContent), ContentType.DEFAULT_BINARY, item.getFilename()); // mpEntity.addPart( "fileContent", new InputStreamBody(wipContent, item.getFilename()) // ); request.setEntity(mpEntity.build()); // Send the web service request and check the response log.info("Sending commit request to HTTP endpoint: " + endpointUrl); HttpResponse response = executeWithAuthentication(request); if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) { throw new RepositoryException(getResponseErrorMessage(response)); } log.info("Commit response received - Status OK"); // Update the local cache with the content we just sent to the remote web service downloadContent(item, true); } catch (JAXBException e) { throw new RepositoryException("The format of the library meta-data is unreadable.", e); } catch (IOException e) { throw new RepositoryException("The remote repository is unavailable.", e); } finally { try { if (wipContent != null) wipContent.close(); } catch (Throwable t) { } } }
From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java
/** * @see org.opentravel.schemacompiler.repository.Repository#publish(java.io.InputStream, * java.lang.String, java.lang.String, java.lang.String, java.lang.String, * java.lang.String, org.opentravel.schemacompiler.model.TLLibraryStatus) *///from w w w .j ava 2 s.com @Override public RepositoryItem publish(InputStream unmanagedContent, String filename, String libraryName, String namespace, String versionIdentifier, String versionScheme, TLLibraryStatus initialStatus) throws RepositoryException { try { // Build a repository item to represent the content that we are attempting to publish String targetNS = RepositoryNamespaceUtils.normalizeUri(namespace); RepositoryItemImpl item = new RepositoryItemImpl(); String baseNamespace = targetNS; if (versionScheme != null) { VersionScheme vScheme = VersionSchemeFactory.getInstance().getVersionScheme(versionScheme); baseNamespace = vScheme.getBaseNamespace(targetNS); } item.setRepository(this); item.setNamespace(targetNS); item.setBaseNamespace(baseNamespace); item.setFilename(filename); item.setVersion(versionIdentifier); item.setStatus(initialStatus); item.setState(RepositoryItemState.MANAGED_UNLOCKED); // Invoke the remote web service call to perform the publication HttpPost postRequest = newPostRequest(PUBLISH_ENDPOINT); MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create(); if (versionScheme != null) { mpEntity.addTextBody("versionScheme", versionScheme); } mpEntity.addBinaryBody("fileContent", toByteArray(unmanagedContent), ContentType.DEFAULT_BINARY, filename); mpEntity.addTextBody("namespace", targetNS); mpEntity.addTextBody("libraryName", libraryName); mpEntity.addTextBody("version", versionIdentifier); mpEntity.addTextBody("status", initialStatus.toRepositoryStatus().toString()); postRequest.setEntity(mpEntity.build()); log.info("Sending publish request to HTTP endpoint: " + endpointUrl); HttpResponse response = executeWithAuthentication(postRequest); if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) { throw new RepositoryException(getResponseErrorMessage(response)); } log.info("Publish response received - Status OK"); return item; } catch (VersionSchemeException e) { throw new RepositoryException(e.getMessage(), e); } catch (IOException e) { throw new RepositoryException("The remote repository is unavailable.", e); } finally { try { if (unmanagedContent != null) unmanagedContent.close(); } catch (Throwable t) { } } }
From source file:gov.osti.services.Metadata.java
/** * Send this Metadata to the ARCHIVER external support process. * * Needs a CODE ID and one of either an ARCHIVE FILE or REPOSITORY LINK. * * If nothing supplied to archive, do nothing. * * @param codeId the CODE ID for this METADATA * @param repositoryLink (optional) the REPOSITORY LINK value, or null if none * @param archiveFile (optional) the File recently uploaded to ARCHIVE, or null if none * @param archiveContainer (optional) the Container recently uploaded to ARCHIVE, or null if none * @throws IOException on IO transmission errors *//* w w w.ja v a2 s . c o m*/ private static void sendToArchiver(Long codeId, String repositoryLink, File archiveFile, File archiveContainer) throws IOException { if ("".equals(ARCHIVER_URL)) return; // Nothing sent? if (StringUtils.isBlank(repositoryLink) && null == archiveFile && null == archiveContainer) return; // set up a connection CloseableHttpClient hc = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom() .setSocketTimeout(300000).setConnectTimeout(300000).setConnectionRequestTimeout(300000).build()) .build(); try { HttpPost post = new HttpPost(ARCHIVER_URL); // attributes to send ObjectNode request = mapper.createObjectNode(); request.put("code_id", codeId); request.put("repository_link", repositoryLink); // determine if there's a file to send or not if (null == archiveFile && null == archiveContainer) { post.setHeader("Content-Type", "application/json"); post.setHeader("Accept", "application/json"); post.setEntity(new StringEntity(request.toString(), "UTF-8")); } else { MultipartEntityBuilder mpe = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart("project", new StringBody(request.toString(), ContentType.APPLICATION_JSON)); if (archiveFile != null) mpe.addPart("file", new FileBody(archiveFile, ContentType.DEFAULT_BINARY)); if (archiveContainer != null) mpe.addPart("container", new FileBody(archiveContainer, ContentType.DEFAULT_BINARY)); post.setEntity(mpe.build()); } HttpResponse response = hc.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK != statusCode && HttpStatus.SC_CREATED != statusCode) { throw new IOException("Archiver Error: " + EntityUtils.toString(response.getEntity())); } } catch (IOException e) { log.warn("Archiver request error: " + e.getMessage()); throw e; } finally { try { if (null != hc) hc.close(); } catch (IOException e) { log.warn("Close Error: " + e.getMessage()); } } }
From source file:com.ibm.devops.dra.PublishTest.java
/** * * Send POST request to DLMS back end with the result file * @param bluemixToken - the Bluemix token * @param contents - the result file/*from www . ja va 2 s . c om*/ * @param jobUrl - the build url of the build job in Jenkins * @param timestamp * @return - response/error message from DLMS */ public String sendFormToDLMS(String bluemixToken, FilePath contents, String lifecycleStage, String jobUrl, String timestamp) throws IOException { // create http client and post method CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(this.dlmsUrl); postMethod = addProxyInformation(postMethod); // build up multi-part forms MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); if (contents != null) { File file = new File(root, contents.getName()); FileBody fileBody = new FileBody(file); builder.addPart("contents", fileBody); builder.addTextBody("test_artifact", file.getName()); if (this.isDeploy) { builder.addTextBody("environment_name", environmentName); } //Todo check the value of lifecycleStage builder.addTextBody("lifecycle_stage", lifecycleStage); builder.addTextBody("url", jobUrl); builder.addTextBody("timestamp", timestamp); String fileExt = FilenameUtils.getExtension(contents.getName()); String contentType; switch (fileExt) { case "json": contentType = CONTENT_TYPE_JSON; break; case "xml": contentType = CONTENT_TYPE_XML; break; default: return "Error: " + contents.getName() + " is an invalid result file type"; } builder.addTextBody("contents_type", contentType); HttpEntity entity = builder.build(); postMethod.setEntity(entity); postMethod.setHeader("Authorization", bluemixToken); } else { return "Error: File is null"; } CloseableHttpResponse response = null; try { response = httpClient.execute(postMethod); // parse the response json body to display detailed info String resStr = EntityUtils.toString(response.getEntity()); JsonParser parser = new JsonParser(); JsonElement element = parser.parse(resStr); if (!element.isJsonObject()) { // 401 Forbidden return "Error: Upload is Forbidden, please check your org name. Error message: " + element.toString(); } else { JsonObject resJson = element.getAsJsonObject(); if (resJson != null && resJson.has("status")) { return String.valueOf(response.getStatusLine()) + "\n" + resJson.get("status"); } else { // other cases return String.valueOf(response.getStatusLine()); } } } catch (IOException e) { e.printStackTrace(); throw e; } }
From source file:co.beem.project.beem.FbTextService.java
private void uploadPicture(ImageMessageInQueue imageMessageInQueue, String pageId, String accessToken, String message) throws ClientProtocolException, IOException { String url = String.format( "https://graph.facebook.com/v2.3/%s/photos/?access_token=%s&published=false&message=%s", pageId, accessToken, message);// www. j a va 2 s. co m HttpPost post = new HttpPost(url); HttpClient client = new DefaultHttpClient(); //Image attaching MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); File file = new File(imageMessageInQueue.getLocalPath()); Bitmap bi = decodeFile(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bi.compress(Bitmap.CompressFormat.JPEG, 65, baos); byte[] data = baos.toByteArray(); ByteArrayBody byteArrayBody = new ByteArrayBody(data, file.getName()); //multipartEntity.addBinaryBody("source", file, ContentType.create("image/jpeg"), file.getName()); multipartEntity.addPart("source", byteArrayBody); post.setEntity(multipartEntity.build()); HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); final String response_str = EntityUtils.toString(resEntity); if (FbTextApplication.isDebug) Log.v(TAG, "response entity: " + response_str); int statusCode = response.getStatusLine().getStatusCode(); if (FbTextApplication.isDebug) Log.v(TAG, "response status code: " + statusCode); //get image link here if (200 != statusCode) { sendBroadcastPhotoResult(false, imageMessageInQueue, ""); // update database this failure saveMessageImageSentStatus(imageMessageInQueue, false); } else try { String photoPostId = new Gson().fromJson(response_str, FbPost.class).getId(); URL fbPhoto = new URL( String.format("https://graph.facebook.com/v2.3/%s?access_token=%s&fields=images", photoPostId, accessToken)); HttpURLConnection urlConnection = (HttpURLConnection) fbPhoto.openConnection(); InputStream inputStream = urlConnection.getInputStream(); String postDetailString = ""; if (null != inputStream) postDetailString = getStringFromInputStream(inputStream); if (FbTextApplication.isDebug) Log.v(TAG, postDetailString); if (postDetailString != null && postDetailString.length() > 1) { FbPhoto photo = new Gson().fromJson(postDetailString, FbPhoto.class); if (photo != null && photo.getImages() != null) { boolean isSentLinkSuccess = true; try { BeemChatManager chatManager = getChatManager(); if (chatManager != null) { ChatAdapter adapter = chatManager.getChat(imageMessageInQueue.getjIdWithRes()); Log.e(TAG, "jId with res: " + imageMessageInQueue.getjIdWithRes()); BeemMessage msgToSend = new BeemMessage(imageMessageInQueue.getjIdWithRes(), BeemMessage.MSG_TYPE_CHAT); msgToSend.setBody(" sent you a photo " + photo.getImages().get(0).getSource()); if (adapter != null) { adapter.sendMessage(msgToSend); } else { IChat newChat = chatManager.createChat(imageMessageInQueue.getjIdWithRes(), null); newChat.sendMessage(msgToSend); } } } catch (Exception e) { e.printStackTrace(); isSentLinkSuccess = false; } sendBroadcastPhotoResult(isSentLinkSuccess, imageMessageInQueue, photo.getImages().get(0).getSource()); // save image as sent saveMessageImageSentStatus(imageMessageInQueue, isSentLinkSuccess); //sleep a while after sent successfull try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { System.out.println(e.getMessage()); sendBroadcastPhotoResult(false, imageMessageInQueue, " "); saveMessageImageSentStatus(imageMessageInQueue, false); } }