List of usage examples for org.apache.http.entity ContentType create
private static ContentType create(HeaderElement headerElement)
From source file:org.keycloak.testsuite.oauth.ClientAuthSignedJWTTest.java
private void testUploadKeystore(String keystoreFormat, String filePath, String keyAlias, String storePassword) throws Exception { ClientRepresentation client = getClient(testRealm.getRealm(), app3.getId()).toRepresentation(); final String certOld = client.getAttributes().get(JWTClientAuthenticator.CERTIFICATE_ATTR); // Load the keystore file URL fileUrl = (getClass().getClassLoader().getResource(filePath)); if (fileUrl == null) { throw new IOException("File not found: " + filePath); }//from www.j a v a 2 s . c o m File keystoreFile = new File(fileUrl.getFile()); ContentType keystoreContentType = ContentType.create(Files.probeContentType(keystoreFile.toPath())); // Get admin access token, no matter it's master realm's admin OAuthClient.AccessTokenResponse accessTokenResponse = oauth.doGrantAccessTokenRequest(AuthRealm.MASTER, AuthRealm.ADMIN, AuthRealm.ADMIN, null, "admin-cli", null); assertEquals(200, accessTokenResponse.getStatusCode()); final String url = suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/realms/" + testRealm.getRealm() + "/clients/" + client.getId() + "/certificates/jwt.credential/upload-certificate"; // Prepare the HTTP request FileBody fileBody = new FileBody(keystoreFile, keystoreContentType); HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody) .addTextBody("keystoreFormat", keystoreFormat).addTextBody("keyAlias", keyAlias) .addTextBody("storePassword", storePassword).addTextBody("keyPassword", "undefined").build(); HttpPost httpRequest = new HttpPost(url); httpRequest.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessTokenResponse.getAccessToken()); httpRequest.setEntity(entity); // Send the request HttpClient httpClient = HttpClients.createDefault(); HttpResponse httpResponse = httpClient.execute(httpRequest); assertEquals(200, httpResponse.getStatusLine().getStatusCode()); client = getClient(testRealm.getRealm(), client.getId()).toRepresentation(); String pem; // Assert the uploaded certificate if (!keystoreFormat.equals(CERTIFICATE_PEM)) { InputStream keystoreIs = new FileInputStream(keystoreFile); KeyStore keyStore = getKeystore(keystoreIs, storePassword, keystoreFormat); keystoreIs.close(); pem = KeycloakModelUtils.getPemFromCertificate((X509Certificate) keyStore.getCertificate(keyAlias)); } else { pem = new String(Files.readAllBytes(keystoreFile.toPath())); } assertCertificate(client, certOld, pem); }
From source file:org.opendatakit.briefcase.util.AggregateUtils.java
public static final boolean uploadFilesToServer(ServerConnectionInfo serverInfo, URI u, String distinguishedFileTagName, File file, List<File> files, DocumentDescription description, SubmissionResponseAction action, TerminationFuture terminationFuture, FormStatus formToTransfer) { boolean allSuccessful = true; formToTransfer.setStatusString("Preparing for upload of " + description.getDocumentDescriptionType() + " with " + files.size() + " media attachments", true); EventBus.publish(new FormStatusEvent(formToTransfer)); boolean first = true; // handles case where there are no media files int lastJ = 0; int j = 0;/*from w w w .ja v a2 s . c o m*/ while (j < files.size() || first) { lastJ = j; first = false; if (terminationFuture.isCancelled()) { formToTransfer.setStatusString("Aborting upload of " + description.getDocumentDescriptionType() + " with " + files.size() + " media attachments", true); EventBus.publish(new FormStatusEvent(formToTransfer)); return false; } HttpPost httppost = WebUtils.createOpenRosaHttpPost(u); long byteCount = 0L; // mime post MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // add the submission file first... FileBody fb = new FileBody(file, ContentType.TEXT_XML); builder.addPart(distinguishedFileTagName, fb); log.info("added " + distinguishedFileTagName + ": " + file.getName()); byteCount += file.length(); for (; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } // we will be processing every one of these, so // we only need to deal with the content type determination... if (extension.equals("xml")) { fb = new FileBody(f, ContentType.TEXT_XML); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, ContentType.create("image/jpeg")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, ContentType.create("audio/3gpp")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, ContentType.create("video/3gpp")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, ContentType.create("video/mp4")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, ContentType.create("text/csv")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added csv file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, ContentType.create("application/vnd.ms-excel")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added xls file " + f.getName()); } else { fb = new FileBody(f, ContentType.create("application/octet-stream")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.warn("added unrecognized file (application/octet-stream) " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if ((j - lastJ + 1) > 100 || byteCount + files.get(j + 1).length() > 10000000L) { // more than 100 attachments or the next file would exceed the 10MB threshold... log.info("Extremely long post is being split into multiple posts"); try { StringBody sb = new StringBody("yes", ContentType.DEFAULT_TEXT.withCharset(Charset.forName("UTF-8"))); builder.addPart("*isIncomplete*", sb); } catch (Exception e) { log.error("impossible condition", e); throw new IllegalStateException("never happens"); } ++j; // advance over the last attachment added... break; } } } httppost.setEntity(builder.build()); int[] validStatusList = { 201 }; try { if (j != files.size()) { formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and media files " + (lastJ + 1) + " through " + (j + 1) + " of " + files.size() + " media attachments", true); } else if (j == 0) { formToTransfer.setStatusString( "Uploading " + description.getDocumentDescriptionType() + " with no media attachments", true); } else { formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and " + (j - lastJ) + ((lastJ != 0) ? " remaining" : "") + " media attachments", true); } EventBus.publish(new FormStatusEvent(formToTransfer)); httpRetrieveXmlDocument(httppost, validStatusList, serverInfo, false, description, action); } catch (XmlDocumentFetchException e) { allSuccessful = false; log.error("upload failed", e); formToTransfer.setStatusString("UPLOAD FAILED: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(formToTransfer)); if (description.isCancelled()) return false; } } return allSuccessful; }
From source file:org.opennms.protocols.http.HttpUrlConnection.java
@Override public InputStream getInputStream() throws IOException { try {/*from w w w . ja v a2 s. c o m*/ if (m_clientWrapper == null) { connect(); } // Build URL int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort(); URIBuilder ub = new URIBuilder(); ub.setPort(port); ub.setScheme(m_url.getProtocol()); ub.setHost(m_url.getHost()); ub.setPath(m_url.getPath()); if (m_url.getQuery() != null && !m_url.getQuery().trim().isEmpty()) { final List<NameValuePair> params = URLEncodedUtils.parse(m_url.getQuery(), Charset.forName("UTF-8")); if (!params.isEmpty()) { ub.addParameters(params); } } // Build Request HttpRequestBase request = null; if (m_request != null && m_request.getMethod().equalsIgnoreCase("post")) { final Content cnt = m_request.getContent(); HttpPost post = new HttpPost(ub.build()); ContentType contentType = ContentType.create(cnt.getType()); LOG.info("Processing POST request for {}", contentType); if (contentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { FormFields fields = JaxbUtils.unmarshal(FormFields.class, cnt.getData()); post.setEntity(fields.getEntity()); } else { StringEntity entity = new StringEntity(cnt.getData(), contentType); post.setEntity(entity); } request = post; } else { request = new HttpGet(ub.build()); } if (m_request != null) { // Add Custom Headers for (final Header header : m_request.getHeaders()) { request.addHeader(header.getName(), header.getValue()); } } // Get Response CloseableHttpResponse response = m_clientWrapper.execute(request); return response.getEntity().getContent(); } catch (Exception e) { throw new IOException( "Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage(), e); } }
From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.tasks.APIUsageFileUploadTask.java
/** * Uploads the API Usage file to Upload Service * * @param compressedFilePath File Path to the compressed file * @param fileName Name of the uploading file * @return Returns boolean true if uploading is successful *//*from w ww .j av a2s . co m*/ private boolean uploadCompressedFile(Path compressedFilePath, String fileName) { String response; try { String uploadServiceUrl = configManager .getProperty(MicroGatewayAPIUsageConstants.USAGE_UPLOAD_SERVICE_URL); uploadServiceUrl = (uploadServiceUrl != null && !uploadServiceUrl.isEmpty()) ? uploadServiceUrl : MicroGatewayAPIUsageConstants.DEFAULT_UPLOAD_SERVICE_URL; URL uploadServiceUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(uploadServiceUrl); HttpClient httpClient = APIUtil.getHttpClient(uploadServiceUrlValue.getPort(), uploadServiceUrlValue.getProtocol()); HttpPost httppost = new HttpPost(uploadServiceUrl); InputStream zipStream = new FileInputStream(compressedFilePath.toString()); MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create(); mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); mBuilder.addBinaryBody("file", zipStream, ContentType.create("application/zip"), fileName); HttpEntity entity = mBuilder.build(); httppost.setHeader(MicroGatewayAPIUsageConstants.FILE_NAME_HEADER, fileName); APIManagerConfiguration config = ServiceReferenceHolder.getInstance() .getAPIManagerConfigurationService().getAPIManagerConfiguration(); String username = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME); char[] password = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD).toCharArray(); String authHeaderValue = TokenUtil.getBasicAuthHeaderValue(username, password); MicroGatewayCommonUtil.cleanPasswordCharArray(password); httppost.setHeader(MicroGatewayAPIUsageConstants.AUTHORIZATION_HEADER, authHeaderValue); httppost.setHeader(MicroGatewayAPIUsageConstants.ACCEPT_HEADER, MicroGatewayAPIUsageConstants.ACCEPT_HEADER_APPLICATION_JSON); httppost.setEntity(entity); response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httppost, MicroGatewayAPIUsageConstants.MAX_RETRY_COUNT); log.info("API Usage file : " + compressedFilePath.getFileName() + " uploaded successfully. " + "Server Response : " + response); return true; } catch (OnPremiseGatewayException e) { log.error("Error occurred while uploading API Usage file.", e); } catch (FileNotFoundException e) { log.error("Error occurred while reading API Usage file from the path.", e); } return false; }
From source file:ste.web.http.handlers.BugFreeFileHandler.java
@Test public void mime_type_based_on_file_extension() throws Exception { FileHandler h = new FileHandler("src/test/mime"); BasicHttpRequest request = HttpUtils.getSimpleGet("/test.txt"); BasicHttpResponse response = HttpUtils.getBasicResponse(); h.handle(request, response, new HttpSessionContext()); then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); then(response.getEntity().getContentType().getValue()).isEqualTo(ContentType.TEXT_PLAIN.getMimeType()); request = HttpUtils.getSimpleGet("/test.html"); h.handle(request, response, new HttpSessionContext()); then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); then(response.getEntity().getContentType().getValue()).isEqualTo(ContentType.TEXT_HTML.getMimeType()); request = HttpUtils.getSimpleGet("/test.png"); h.handle(request, response, new HttpSessionContext()); then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); then(response.getEntity().getContentType().getValue()) .isEqualTo(ContentType.create("image/png").getMimeType()); }
From source file:ste.web.http.handlers.FileHandler.java
@Override public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { checkHttpMethod(request);/* w w w.jav a 2 s . com*/ String target = request.getRequestLine().getUri(); for (String exclude : excludePatterns) { if (target.matches(exclude)) { notFound(target, response); return; } } if (StringUtils.isNotBlank(webContext) && target.startsWith(webContext)) { target = target.substring(webContext.length()); } if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); } URI uri = null; try { uri = new URI(target); } catch (URISyntaxException x) { throw new HttpException("malformed URL '" + target + "'"); } final File file = new File(this.docRoot, uri.getPath()); if (!file.exists()) { notFound(target, response); } else if (!file.canRead() || file.isDirectory()) { response.setStatusCode(HttpStatus.SC_FORBIDDEN); StringEntity entity = new StringEntity("<html><body><h1>Access denied</h1></body></html>", ContentType.TEXT_HTML); response.setEntity(entity); } else { response.setStatusCode(HttpStatus.SC_OK); String mimeType = MimeUtils.getInstance().getMimeType(file); ContentType type = MimeUtils.MIME_UNKNOWN.equals(mimeType) ? ContentType.APPLICATION_OCTET_STREAM : ContentType.create(mimeType); FileEntity body = new FileEntity(file, type); response.setEntity(body); } }