List of usage examples for java.net HttpURLConnection getContentType
public String getContentType()
From source file:org.mapfish.print.PDFUtils.java
private static Image loadImageFromUrl(final RenderingContext context, final URI uri, final boolean alwaysThrowExceptionOnError) throws IOException, DocumentException { if (!uri.isAbsolute()) { //Assumption is that the file is on the local file system return Image.getInstance(uri.toString()); } else if ("file".equalsIgnoreCase(uri.getScheme())) { String path;/*from w ww . j a v a 2 s. c o m*/ if (uri.getHost() != null && uri.getPath() != null) { path = uri.getHost() + uri.getPath(); } else if (uri.getHost() == null && uri.getPath() != null) { path = uri.getPath(); } else { path = uri.toString().substring("file:".length()).replaceAll("/+", "/"); } path = path.replace("/", File.separator); return Image.getInstance(new File(path).toURI().toURL()); } else { final String contentType; final int statusCode; final String statusText; byte[] data = null; try { //read the whole image content in memory, then give that to iText if ((uri.getScheme().equals("http") || uri.getScheme().equals("https")) && context.getConfig().localHostForwardIsFrom(uri.getHost())) { String scheme = uri.getScheme(); final String host = uri.getHost(); if (uri.getScheme().equals("https") && context.getConfig().localHostForwardIsHttps2http()) { scheme = "http"; } URL url = new URL(scheme, "localhost", uri.getPort(), uri.getPath() + "?" + uri.getQuery()); HttpURLConnection connexion = (HttpURLConnection) url.openConnection(); connexion.setRequestProperty("Host", host); for (Map.Entry<String, String> entry : context.getHeaders().entrySet()) { connexion.setRequestProperty(entry.getKey(), entry.getValue()); } InputStream is = null; try { try { is = connexion.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) != -1) { baos.write(buffer, 0, length); } baos.flush(); data = baos.toByteArray(); } catch (IOException e) { LOGGER.warn(e); } statusCode = connexion.getResponseCode(); statusText = connexion.getResponseMessage(); contentType = connexion.getContentType(); } finally { if (is != null) { is.close(); } } } else { GetMethod getMethod = null; try { getMethod = new GetMethod(uri.toString()); for (Map.Entry<String, String> entry : context.getHeaders().entrySet()) { getMethod.setRequestHeader(entry.getKey(), entry.getValue()); } if (LOGGER.isDebugEnabled()) LOGGER.debug("loading image: " + uri); context.getConfig().getHttpClient(uri).executeMethod(getMethod); statusCode = getMethod.getStatusCode(); statusText = getMethod.getStatusText(); Header contentTypeHeader = getMethod.getResponseHeader("Content-Type"); if (contentTypeHeader == null) { contentType = ""; } else { contentType = contentTypeHeader.getValue(); } data = getMethod.getResponseBody(); } finally { if (getMethod != null) { getMethod.releaseConnection(); } } } if (statusCode == 204) { // returns a transparent image if (LOGGER.isDebugEnabled()) LOGGER.debug("creating a transparent image for: " + uri); try { final byte[] maskr = { (byte) 255 }; Image mask = Image.getInstance(1, 1, 1, 1, maskr); mask.makeMask(); data = new byte[1 * 1 * 3]; Image image = Image.getInstance(1, 1, 3, 8, data); image.setImageMask(mask); return image; } catch (DocumentException e) { LOGGER.warn("Couldn't generate a transparent image"); if (alwaysThrowExceptionOnError) { throw e; } Image image = handleImageLoadError(context, e.getMessage()); LOGGER.warn("The status code was not a valid code, a default image is being returned."); return image; } } else if (statusCode < 200 || statusCode >= 300 || contentType.startsWith("text/") || contentType.equals("application/vnd" + ".ogc.se_xml")) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Server returned an error for " + uri + ": " + new String(data)); String errorMessage; if (statusCode < 200 || statusCode >= 300) { errorMessage = "Error (status=" + statusCode + ") while reading the image from " + uri + ": " + statusText; } else { errorMessage = "Didn't receive an image while reading: " + uri; } if (alwaysThrowExceptionOnError) { throw new IOException(errorMessage); } Image image = handleImageLoadError(context, errorMessage); LOGGER.warn("The status code was not a valid code, a default image is being returned."); return image; } else { if (LOGGER.isDebugEnabled()) LOGGER.debug("loaded image: " + uri); return Image.getInstance(data); } } catch (IOException e) { LOGGER.error("Server returned an error for " + uri + ": " + e.getMessage()); if (alwaysThrowExceptionOnError) { throw e; } return handleImageLoadError(context, e.getMessage()); } } }
From source file:org.drools.guvnor.server.jaxrs.CategoryResourceIntegrationTest.java
@Test @RunAsClient/*from w w w.j a va 2 s .c o m*/ @Ignore public void testGetAssetsByCategoryAsJaxb(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/categories/Home%20Mortgage/assets"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); //logger.log(LogLevel, IOUtils.toString(connection.getInputStream())); }
From source file:org.drools.guvnor.server.jaxrs.CategoryResourceIntegrationTest.java
@Test @RunAsClient/*from w w w . ja v a2 s.com*/ @Ignore public void testGetAssetsByCategoryAndPageAsJaxb(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/categories/Home%20Mortgage/assets//page/0"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); //logger.log(LogLevel, IOUtils.toString(connection.getInputStream())); }
From source file:org.drools.guvnor.server.jaxrs.CategoryResourceIntegrationTest.java
@Test @RunAsClient/*from w w w . j a v a2 s .c o m*/ @Ignore public void testGetAssetsByCategoryAsJson(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/categories/Home%20Mortgage/assets"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_JSON, connection.getContentType()); //logger.log(LogLevel, IOUtils.toString(connection.getInputStream())); }
From source file:org.drools.guvnor.server.jaxrs.CategoryResourceIntegrationTest.java
@Test @RunAsClient//from w w w .j ava 2s. c om @Ignore public void testGetAssetsByCategoryAndPageAsJson(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/categories/Home%20Mortgage/assets//page/0"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_JSON, connection.getContentType()); //logger.log(LogLevel, IOUtils.toString(connection.getInputStream())); }
From source file:org.sakaiproject.profile2.conversion.ProfileConverter.java
private void retrieveMainImage(String userUuid, String mainUrl) { InputStream inputStream = null; try {//from w w w .ja v a 2s . c o m URL url = new URL(mainUrl); HttpURLConnection openConnection = (HttpURLConnection) url.openConnection(); openConnection.setReadTimeout(5000); openConnection.setConnectTimeout(5000); openConnection.setInstanceFollowRedirects(true); openConnection.connect(); int responseCode = openConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String mimeType = openConnection.getContentType(); inputStream = openConnection.getInputStream(); // Convert the image. byte[] imageMain = ProfileUtils.scaleImage(inputStream, ProfileConstants.MAX_IMAGE_XY, mimeType); //create resource ID String mainResourceId = sakaiProxy.getProfileImageResourcePath(userUuid, ProfileConstants.PROFILE_IMAGE_MAIN); log.info("Profile2 image converter: mainResourceId: " + mainResourceId); //save, if error, log and return. if (!sakaiProxy.saveFile(mainResourceId, userUuid, DEFAULT_FILE_NAME, mimeType, imageMain)) { log.error("Profile2 image importer: Saving main profile image failed."); } else { ci.setImage(imageMain); ci.setMimeType(mimeType); ci.setFileName(DEFAULT_FILE_NAME); ci.setMainResourceId(mainResourceId); ci.setNeedsSaving(true); } } else { log.warn("Failed to get good response for user " + userUuid + " for " + mainUrl + " got " + responseCode); } } catch (MalformedURLException e) { log.info("Invalid URL for user: " + userUuid + " of: " + mainUrl); } catch (IOException e) { log.warn("Failed to download image for: " + userUuid + " from: " + mainUrl + " error of: " + e.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { log.info("Failed to close input stream for request to: " + mainUrl); } } } }
From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceIntegrationTest.java
@Test @RunAsClient// ww w . ja va2s .c o m public void testGetAssetSource(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1/source"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.TEXT_PLAIN); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.TEXT_PLAIN, connection.getContentType()); String result = IOUtils.toString(connection.getInputStream()); assertTrue(result.contains("declare Album2")); assertTrue(result.contains("genre2: String")); }
From source file:org.ejbca.core.protocol.ocsp.OcspJunitHelper.java
/** * * @param ocspPackage/* w w w . jav a 2s . c o m*/ * @param nonce * @param respCode expected response code, OK = 0, if not 0, response checking will not continue after response code is checked. * @param httpCode, normally 200 for OK or OCSP error. Can be 400 is more than 1 million bytes is sent for example * @return a SingleResp or null if respCode != 0 * @throws IOException * @throws OCSPException * @throws NoSuchProviderException * @throws CertificateException on parsing errors. * @throws OperatorCreationException */ protected SingleResp[] sendOCSPPost(byte[] ocspPackage, String nonce, int respCode, int httpCode) throws IOException, OCSPException, NoSuchProviderException, OperatorCreationException, CertificateException { // POST the OCSP request URL url = new URL(this.sBaseURL + this.urlEnding); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); // POST it con.setRequestProperty("Content-Type", "application/ocsp-request"); OutputStream os = con.getOutputStream(); os.write(ocspPackage); os.close(); assertEquals("Response code", httpCode, con.getResponseCode()); if (con.getResponseCode() != 200) { return null; // if it is an http error code we don't need to test any more } // Some appserver (Weblogic) responds with "application/ocsp-response; charset=UTF-8" assertNotNull("No Content-Type in reply.", con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertEquals("Response status not the expected.", respCode, response.getStatus()); if (respCode != 0) { assertNull("According to RFC 2560, responseBytes are not set on error.", response.getResponseObject()); return null; // it messes up testing of invalid signatures... but is needed for the unsuccessful responses } BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); X509CertificateHolder[] chain = brep.getCerts(); assertNotNull( "No certificate chain returned in response (chain == null), is ocsp.includesignercert=false in ocsp.properties?. It should be set to default value for test to run.", chain); boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0])); assertTrue("Response failed to verify.", verify); // Check nonce (if we sent one) if (nonce != null) { byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue() .getEncoded(); assertNotNull(noncerep); ASN1InputStream ain = new ASN1InputStream(noncerep); ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject()); ain.close(); assertEquals(nonce, new String(oct.getOctets())); } SingleResp[] singleResps = brep.getResponses(); return singleResps; }
From source file:org.drools.guvnor.server.jaxrs.CategoryResourceIntegrationTest.java
@Test @RunAsClient//from w w w . j a v a 2 s .co m @Ignore public void testGetAssetsByCategoryAndPageAsAtom(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/categories/Home%20Mortgage/assets//page/0"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType()); //logger.log(LogLevel, IOUtils.toString(connection.getInputStream())); }
From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceIntegrationTest.java
@Test @RunAsClient//from w w w . java 2s.c o m public void testGetAssetAsJaxB(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); }