Example usage for java.net HttpURLConnection getContentType

List of usage examples for java.net HttpURLConnection getContentType

Introduction

In this page you can find the example usage for java.net HttpURLConnection getContentType.

Prototype

public String getContentType() 

Source Link

Document

Returns the value of the content-type header field.

Usage

From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceIntegrationTest.java

@Test
@RunAsClient/* w  ww.  j a  va 2 s .  c o m*/
public void testGetAssetsAsJaxB(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/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, getContent(connection));
}

From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceTest.java

@Test
@RunAsClient/*from   w ww  . j a va 2  s .  c  o m*/
public void testUpdateAssetFromAtomWithStateNotExist(@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_ATOM_XML);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType());
    InputStream in = connection.getInputStream();
    assertNotNull(in);
    Document<Entry> doc = abdera.getParser().parse(in);
    Entry entry = doc.getRoot();

    //Update state
    ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA);
    ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE);
    stateExtension.getExtension(Translator.VALUE).setText("NonExistState");

    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Content-type", MediaType.APPLICATION_ATOM_XML);
    connection.setDoOutput(true);
    entry.writeTo(connection.getOutputStream());
    assertEquals(500, connection.getResponseCode());
    connection.disconnect();
}

From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceIntegrationTest.java

@Test
@RunAsClient//from w  w  w .  j a  v  a2 s .co m
public void testGetAssetsAsJson(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/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, getContent(connection));
}

From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceIntegrationTest.java

@Test
@RunAsClient//from   www.jav a  2 s. c  o m
public void testGetAssetAsJson(@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_JSON);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_JSON, connection.getContentType());
    //logger.log(LogLevel, getContent(connection));
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java

private void testVerifyHttpGetHeaders(X509Certificate caCertificate, BigInteger serialNumber) throws Exception {
    // An OCSP request, ocspTestCert is already created in earlier tests
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, serialNumber));
    OCSPReq req = gen.build();/*from w  ww .j  a  v a 2 s. c o  m*/
    String reqString = new String(Base64.encode(req.getEncoded(), false));
    URL url = new URL(httpReqPath + '/' + resourceOcsp + '/' + URLEncoder.encode(reqString, "UTF-8"));
    log.debug("OCSP Request: " + url.toExternalForm());
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    assertEquals(
            "Response code did not match. (Make sure you allow encoded slashes in your appserver.. add -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true in Tomcat)",
            200, con.getResponseCode());
    // Some appserver (Weblogic) responds with
    // "application/ocsp-response; charset=UTF-8"
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    assertEquals("Response status not the expected.", OCSPRespBuilder.SUCCESSFUL, response.getStatus());
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    // Just output the headers to stdout so we can visually inspect them if
    // something goes wrong
    Set<String> keys = con.getHeaderFields().keySet();
    for (String field : keys) {
        List<String> values = con.getHeaderFields().get(field);
        for (String value : values) {
            log.info(field + ": " + value);
        }
    }
    String eTag = con.getHeaderField("ETag");
    assertNotNull(
            "RFC 5019 6.2: No 'ETag' HTTP header present as it SHOULD. (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)",
            eTag);
    assertTrue("ETag is messed up.",
            ("\"" + new String(
                    Hex.encode(MessageDigest.getInstance("SHA-1", "BC").digest(response.getEncoded()))) + "\"")
                            .equals(eTag));
    long date = con.getHeaderFieldDate("Date", -1);
    assertTrue("RFC 5019 6.2: No 'Date' HTTP header present as it SHOULD.", date != -1);
    long lastModified = con.getHeaderFieldDate("Last-Modified", -1);
    assertTrue("RFC 5019 6.2: No 'Last-Modified' HTTP header present as it SHOULD.", lastModified != -1);
    // assertTrue("Last-Modified is after response was sent",
    // lastModified<=date); This will not hold on JBoss AS due to the
    // caching of the Date-header
    long expires = con.getExpiration();
    assertTrue("Expires is before response was sent", expires >= date);
    assertTrue("RFC 5019 6.2: No 'Expires' HTTP header present as it SHOULD.", expires != 0);
    String cacheControl = con.getHeaderField("Cache-Control");
    assertNotNull("RFC 5019 6.2: No 'Cache-Control' HTTP header present as it SHOULD.", cacheControl);
    assertTrue("RFC 5019 6.2: No 'public' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("public"));
    assertTrue("RFC 5019 6.2: No 'no-transform' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("no-transform"));
    assertTrue("RFC 5019 6.2: No 'must-revalidate' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("must-revalidate"));
    Matcher matcher = Pattern.compile(".*max-age\\s*=\\s*(\\d+).*").matcher(cacheControl);
    assertTrue("RFC 5019 6.2: No 'max-age' HTTP header Cache-Control present as it SHOULD.", matcher.matches());
    int maxAge = Integer.parseInt(matcher.group(1));
    log.debug("maxAge=" + maxAge + " (expires-lastModified)/1000=" + ((expires - lastModified) / 1000));
    assertTrue(
            "thisUpdate and nextUpdate should not be the same (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)",
            expires != lastModified);
    assertTrue("RFC 5019 6.2: [maxAge] SHOULD be 'later than thisUpdate but earlier than nextUpdate'.",
            maxAge < (expires - lastModified) / 1000);
    // assertTrue("Response cannot be produced after it was sent.",
    // brep.getProducedAt().getTime() <= date); This might not hold on JBoss
    // AS due to the caching of the Date-header
    X509CertificateHolder[] chain = brep.getCerts();
    boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0]));
    assertTrue("Response failed to verify.", verify);
    assertNull("No nonce should be present.", brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce));
    SingleResp[] singleResps = brep.getResponses();
    assertNotNull("SingleResps should not be null.", singleResps);
    assertTrue("Expected a single SingleResp in the repsonse.", singleResps.length == 1);
    assertEquals("Serno in response does not match serno in request.",
            singleResps[0].getCertID().getSerialNumber(), serialNumber);
    assertEquals("Status is not null (null is 'good')", singleResps[0].getCertStatus(), null);
    assertTrue(
            "RFC 5019 6.2: Last-Modified SHOULD 'be the same as the thisUpdate timestamp in the request itself'",
            singleResps[0].getThisUpdate().getTime() == lastModified);
    assertTrue("RFC 5019 6.2: Expires SHOULD 'be the same as the nextUpdate timestamp in the request itself'",
            singleResps[0].getNextUpdate().getTime() == expires);
    assertTrue("Response cannot be produced before it was last modified..",
            brep.getProducedAt().getTime() >= singleResps[0].getThisUpdate().getTime());
}

From source file:com.portfolio.data.attachment.FileServlet.java

void InitAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    String ref = null;/*from w  ww.jav a 2s. com*/
    if (referer != null) {
        int first = referer.indexOf('/', 7);
        int last = referer.lastIndexOf('/');
        ref = referer.substring(first, last);
    }

    response.setContentType(connection.getContentType());
    response.setStatus(connection.getResponseCode());
    response.setContentLength(connection.getContentLength());

    /// Transfer headers
    Map<String, List<String>> headers = connection.getHeaderFields();
    int size = headers.size();
    for (int i = 1; i < size; ++i) {
        String key = connection.getHeaderFieldKey(i);
        String value = connection.getHeaderField(i);
        //         response.setHeader(key, value);
        response.addHeader(key, value);
    }

    /// Deal with correct path with set cookie
    List<String> setValues = headers.get("Set-Cookie");
    if (setValues != null) {
        String setVal = setValues.get(0);
        int pathPlace = setVal.indexOf("Path=");
        if (pathPlace > 0) {
            setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break
            setVal = setVal + ref;

            response.setHeader("Set-Cookie", setVal);
        }
    }
}

From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceIntegrationTest.java

@Test
@RunAsClient/*from  w w w  .java 2  s .  c om*/
public void testGetAssetBinary(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1/binary");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_OCTET_STREAM);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_OCTET_STREAM, connection.getContentType());
    //logger.log(LogLevel, getContent(connection));
}

From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceIntegrationTest.java

@Test
@RunAsClient/*from   w  w w  .ja v a2 s  .  co  m*/
public void testUpdateAssetFromAtomWithStateNotExist(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL + "rest/packages/restPackage1/assets/model6");
    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());
    InputStream in = connection.getInputStream();
    assertNotNull(in);
    Document<Entry> doc = abdera.getParser().parse(in);
    Entry entry = doc.getRoot();

    //Update state
    ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA);
    ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE);
    stateExtension.<Element>getExtension(Translator.VALUE).setText("NonExistState");

    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Content-type", MediaType.APPLICATION_ATOM_XML);
    connection.setDoOutput(true);
    entry.writeTo(connection.getOutputStream());
    assertEquals(500, connection.getResponseCode());
    connection.disconnect();
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java

private void testNextUpdateThisUpdate(X509Certificate caCertificate, BigInteger serialNumber) throws Exception {
    // And an OCSP request
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, serialNumber));
    OCSPReq req = gen.build();/*from  w w w .j a  va  2 s . c  om*/
    // POST the request and receive a singleResponse
    URL url = new URL(httpReqPath + '/' + resourceOcsp);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/ocsp-request");
    OutputStream os = con.getOutputStream();
    os.write(req.getEncoded());
    os.close();
    assertEquals("Response code", 200, con.getResponseCode());
    // Some appserver (Weblogic) responds with
    // "application/ocsp-response; charset=UTF-8"
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    assertEquals("Response status not the expected.", 0, response.getStatus());
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    X509CertificateHolder[] chain = brep.getCerts();
    boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0]));
    assertTrue("Response failed to verify.", verify);
    SingleResp[] singleResps = brep.getResponses();
    assertEquals("No of SingResps should be 1.", 1, singleResps.length);
    CertificateID certId = singleResps[0].getCertID();
    assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), serialNumber);
    assertNull("Status is not null.", singleResps[0].getCertStatus());
    Date thisUpdate = singleResps[0].getThisUpdate();
    Date nextUpdate = singleResps[0].getNextUpdate();
    Date producedAt = brep.getProducedAt();
    assertNotNull("thisUpdate was not set.", thisUpdate);
    assertNotNull("nextUpdate was not set. (This test requires ocsp.untilNextUpdate to be configured.)",
            nextUpdate);
    assertNotNull("producedAt was not set.", producedAt);
    assertTrue("nextUpdate cannot be before thisUpdate.", !nextUpdate.before(thisUpdate));
    assertTrue("producedAt cannot be before thisUpdate.", !producedAt.before(thisUpdate));
}

From source file:org.drools.guvnor.server.jaxrs.AssetPackageResourceIntegrationTest.java

@Test
@RunAsClient// ww  w . ja va2 s .  co  m
public void testGetAssetAsAtom(@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_ATOM_XML);
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType());
    //System.out.println(getContent(connection));

    InputStream in = connection.getInputStream();
    assertNotNull(in);
    Document<Entry> doc = abdera.getParser().parse(in);
    Entry entry = doc.getRoot();
    assertEquals(baseURL.getPath() + "rest/packages/restPackage1/assets/model1", entry.getBaseUri().getPath());
    assertEquals("model1", entry.getTitle());
    assertNotNull(entry.getPublished());
    assertNotNull(entry.getAuthor().getName());
    assertEquals("desc for model1", entry.getSummary());
    //assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE.getType(), entry.getContentMimeType().getPrimaryType());
    assertEquals(baseURL.getPath() + "rest/packages/restPackage1/assets/model1/binary",
            entry.getContentSrc().getPath());

    ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA);
    ExtensibleElement archivedExtension = metadataExtension.getExtension(Translator.ARCHIVED);
    assertEquals("false", archivedExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE);
    assertEquals("Draft", stateExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement formatExtension = metadataExtension.getExtension(Translator.FORMAT);
    assertEquals("model.drl", formatExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement uuidExtension = metadataExtension.getExtension(Translator.UUID);
    assertNotNull(uuidExtension.getSimpleExtension(Translator.VALUE));
    ExtensibleElement categoryExtension = metadataExtension.getExtension(Translator.CATEGORIES);
    assertEquals("AssetPackageResourceTestCategory", categoryExtension.getSimpleExtension(Translator.VALUE));
}