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.BasicPackageResourceTest.java

@Test
@RunAsClient//from   www .jav a2  s .  c  o  m
public void testGetPackageSource(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/source");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.WILDCARD);
    connection.connect();

    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.TEXT_PLAIN, connection.getContentType());
    String result = IOUtils.toString(connection.getInputStream());

    assertEquals("attachment; filename=restPackage1", connection.getHeaderField("Content-Disposition"));
    assertTrue(result.indexOf("package restPackage1") >= 0);
    assertTrue(result.indexOf("import com.billasurf.Board") >= 0);
    assertTrue(result.indexOf("global com.billasurf.Person customer2") >= 0);
    assertTrue(result.indexOf("function void foo() { System.out.println(version 2); }") >= 0);
    assertTrue(result.indexOf("declare Album2") >= 0);
}

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

@Test
@RunAsClient//from   w  w  w.j av a 2 s .c o m
public void testGetHistoricalPackageSource(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/versions/2/source");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.WILDCARD);
    connection.connect();

    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.TEXT_PLAIN, connection.getContentType());
    String result = IOUtils.toString(connection.getInputStream());
    System.out.println(result);

    assertTrue(result.indexOf("package restPackage1") >= 0);
    assertTrue(result.indexOf("import com.billasurf.Board") >= 0);
    assertTrue(result.indexOf("global com.billasurf.Person customer1") >= 0);
    assertTrue(result.indexOf("function void foo() { System.out.println(version 1); }") >= 0);
    assertTrue(result.indexOf("declare Album1") >= 0);
}

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

@Test
@RunAsClient// w  w w. j a  va 2  s  .co  m
public void testGetHistoricalAssetSource(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1/versions/1/source");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.WILDCARD);
    connection.connect();

    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.TEXT_PLAIN, connection.getContentType());
    String result = IOUtils.toString(connection.getInputStream());
    System.out.println(result);

    assertTrue(result.indexOf("declare Album1") >= 0);
    assertTrue(result.indexOf("genre1: String") >= 0);

    url = new URL(baseURL, "rest/packages/restPackage1/assets/model1/versions/2/source");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.WILDCARD);
    connection.connect();

    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.TEXT_PLAIN, connection.getContentType());
    result = IOUtils.toString(connection.getInputStream());
    System.out.println(result);

    assertTrue(result.indexOf("declare Album2") >= 0);
    assertTrue(result.indexOf("genre2: String") >= 0);
}

From source file:uk.co.jassoft.network.Network.java

public InputStream read(String httpUrl, String method, boolean cache) throws IOException {

    HttpURLConnection conn = null;
    try {/*from w w w. j a  va  2s.c om*/

        URL base, next;
        String location;

        while (true) {
            // inputing the keywords to google search engine
            URL url = new URL(httpUrl);

            //                if(cache) {
            //                    //Proxy instance, proxy ip = 10.0.0.1 with port 8080
            //                    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("cache", 3128));
            //                    // makking connection to the internet
            //                    conn = (HttpURLConnection) url.openConnection(proxy);
            //                }
            //                else {
            conn = (HttpURLConnection) url.openConnection();
            //                }

            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
            conn.setRequestMethod(method);
            conn.setRequestProperty("User-Agent",
                    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)");
            conn.setRequestProperty("Accept-Encoding", "gzip");

            switch (conn.getResponseCode()) {
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
                location = conn.getHeaderField("Location");
                base = new URL(httpUrl);
                next = new URL(base, location); // Deal with relative URLs
                httpUrl = next.toExternalForm();
                continue;
            }

            break;
        }

        if (!conn.getContentType().startsWith("text/") || conn.getContentType().equals("text/xml")) {
            throw new IOException(String.format("Content of story is not Text. Returned content type is [%s]",
                    conn.getContentType()));
        }

        if ("gzip".equals(conn.getContentEncoding())) {
            return new GZIPInputStream(conn.getInputStream());
        }

        // getting the input stream of page html into bufferedreader
        return conn.getInputStream();
    } catch (Exception exception) {
        throw new IOException(exception);
    } finally {
        if (conn != null && conn.getErrorStream() != null) {
            conn.getErrorStream().close();
        }
    }
}

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

@Test
@RunAsClient//w ww.j  av  a2s .c o  m
@Ignore
public void testGetPackageBinary(@ArquillianResource URL baseURL) throws Exception {
    /* Tests package compilation in addition to byte retrieval */
    URL url = new URL(baseURL, "rest/packages/restPackage1/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());
    System.out.println(IOUtils.toString(connection.getInputStream()));
}

From source file:noThreads.ParseLevel2.java

/**
 * @param theUrl/* w ww.  j  a  va  2 s .  c o  m*/
 * @param conAttempts
 * @return
 * @throws IOException
 */
public boolean validUrl(String theUrl, int conAttempts) throws IOException {
    long total_time = 0, endTime = 0;
    long startTime = System.currentTimeMillis();
    URL link = new URL(theUrl);
    int CONNECT_TIMEOUT = 5000, READ_TIMEOUT = 2000;

    HttpURLConnection huc = (HttpURLConnection) link.openConnection();
    huc.setRequestProperty("User-Agent", userAgent);
    huc.setConnectTimeout(CONNECT_TIMEOUT);
    huc.setReadTimeout(READ_TIMEOUT);
    try {
        huc.connect();

    } catch (java.net.ConnectException e) {
        print(e.getMessage() + "\n");
        if (e.getMessage().equalsIgnoreCase("Connection timed out")) {
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        } else {
            return false;
        }

    } catch (java.net.SocketTimeoutException e) {
        print(e.getMessage() + "\n");
        if (e.getMessage().equalsIgnoreCase("connect timed out")) {
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        } else {
            return false;
        }

    } catch (IOException e) {
        print(e.getMessage() + "\n");
        return false;
    }
    UrlValidator urlValidator = new UrlValidator();
    if (urlValidator.isValid(theUrl) == true) {
        print("valid url form");
        if (huc.getContentType() != null) {
            print("Content: " + huc.getContentType());
            if (huc.getContentType().equals("text/html") || huc.getContentType().equals("unknown/unknown")) {
                if (getResposeCode(theUrl, 0) >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
                    print("Server Response Code: " + getResposeCode(theUrl, 0));
                    return false;
                }
            }
            print(huc.getContentType());
            endTime = System.currentTimeMillis();
            total_time = total_time + (endTime - startTime);
            print("Total elapsed time is :" + total_time + "\n");
            return true;
        } else {//edw erxetai an den prolavei na diavasei h an einai null to content
            endTime = System.currentTimeMillis();
            total_time = total_time + (endTime - startTime);
            print("Total elapsed time is :" + total_time + "\n");
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        }
    } else {
        endTime = System.currentTimeMillis();
        total_time = total_time + (endTime - startTime);
        print("Total elapsed time is :" + total_time + "\n");
        return false;
    }
}

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

@Test
@RunAsClient//from w  ww  .  j a va  2  s . c  o m
public void testGetPackageForXML(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1");
    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());
    //System.out.println(IOUtils.toString(connection.getInputStream()));
    Package p = unmarshalPackageXML(connection.getInputStream());
    assertEquals("restPackage1", p.getTitle());
    assertEquals("this is package restPackage1", p.getDescription());
    assertEquals("version3", p.getCheckInComment());
    assertEquals(3, p.getVersion());
    assertEquals(new URL(baseURL, "rest/packages/restPackage1/source").toExternalForm(),
            p.getSourceLink().toString());
    assertEquals(new URL(baseURL, "rest/packages/restPackage1/binary").toExternalForm(),
            p.getBinaryLink().toString());
    PackageMetadata pm = p.getMetadata();
    assertEquals("admin", pm.getLastContributor());
    assertNotNull(pm.getCreated());
    assertNotNull(pm.getUuid());
    assertNotNull(pm.getLastModified());
    Set<URI> assetsURI = p.getAssets();

    assertEquals(7, assetsURI.size());
    assertTrue(assetsURI.contains(new URL(baseURL, "rest/packages/restPackage1/assets/drools").toURI()));
    assertTrue(assetsURI.contains(new URL(baseURL, "rest/packages/restPackage1/assets/func").toURI()));
    assertTrue(assetsURI.contains(new URL(baseURL, "rest/packages/restPackage1/assets/myDSL").toURI()));
    assertTrue(assetsURI.contains(new URL(baseURL, "rest/packages/restPackage1/assets/rule1").toURI()));
    assertTrue(assetsURI.contains(new URL(baseURL, "rest/packages/restPackage1/assets/rule2").toURI()));
    assertTrue(assetsURI.contains(new URL(baseURL, "rest/packages/restPackage1/assets/rule4").toURI()));
    assertTrue(assetsURI.contains(new URL(baseURL, "rest/packages/restPackage1/assets/model1").toURI()));
}

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

@Test
@RunAsClient//from   ww  w. jav a2  s  . c  o m
public void testUpdateAndGetAssetSource(@ArquillianResource URL baseURL) throws Exception {
    /*
     *  Get the content of rule4
     */
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/rule4/source");
    HttpURLConnection connection1 = (HttpURLConnection) url.openConnection();
    connection1.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection1.setRequestMethod("GET");
    connection1.setRequestProperty("Accept", MediaType.TEXT_PLAIN);
    connection1.connect();
    assertEquals(200, connection1.getResponseCode());
    assertEquals(MediaType.TEXT_PLAIN, connection1.getContentType());
    String newContent = "rule 'nheron' when Goo1() then end";
    /*
     * update the content
     */
    URL url2 = new URL(baseURL, "rest/packages/restPackage1/assets/rule4/source");
    HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection();
    connection2.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection2.setDoOutput(true);
    connection2.setRequestMethod("PUT");
    connection2.setRequestProperty("Accept", MediaType.APPLICATION_XML);
    OutputStreamWriter out = new OutputStreamWriter(connection2.getOutputStream());
    out.write(newContent);
    out.close();
    connection2.getInputStream();
    assertEquals(204, connection2.getResponseCode());
    /*
     * get the content again and verify it was modified
     */
    URL url3 = new URL(baseURL, "rest/packages/restPackage1/assets/rule4/source");
    HttpURLConnection connection3 = (HttpURLConnection) url3.openConnection();
    connection3.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection3.setRequestMethod("GET");
    connection3.setRequestProperty("Accept", MediaType.TEXT_PLAIN);
    connection3.connect();

    assertEquals(200, connection3.getResponseCode());
    assertEquals(MediaType.TEXT_PLAIN, connection3.getContentType());
    String result = IOUtils.toString(connection3.getInputStream());
    assertEquals(result, newContent);
}

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

/**
 * Test of getPackagesAsFeed method, of class PackageService.
 *///from  ww  w .  ja  v a 2 s  .  c  om
@Test
@RunAsClient
public void testGetPackagesForAtom(@ArquillianResource URL baseURL) throws MalformedURLException, IOException {
    URL url = new URL(baseURL, "rest/packages");
    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(IOUtils.toString(connection.getInputStream()));

    InputStream in = connection.getInputStream();
    assertNotNull(in);
    Document<Feed> doc = abdera.getParser().parse(in);
    Feed feed = doc.getRoot();
    assertEquals(baseURL.getPath() + "rest/packages", feed.getBaseUri().getPath());
    assertEquals("Packages", feed.getTitle());

    List<Entry> entries = feed.getEntries();
    assertEquals(2, entries.size());
    Iterator<Entry> it = entries.iterator();
    boolean foundPackageEntry = false;
    while (it.hasNext()) {
        Entry entry = it.next();
        if ("restPackage1".equals(entry.getTitle())) {
            foundPackageEntry = true;
            List<Link> links = entry.getLinks();
            assertEquals(1, links.size());
            assertEquals(baseURL.getPath() + "rest/packages/restPackage1", links.get(0).getHref().getPath());
        }
    }
    assertTrue(foundPackageEntry);
}

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

@Test
@RunAsClient/*from  w ww .j  a va2  s .c om*/
public void testGetHistoricalPackageForAtom(@ArquillianResource URL baseURL)
        throws MalformedURLException, IOException {
    URL url = new URL(baseURL, "rest/packages/restPackage1/versions/2");
    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(IOUtils.toString(connection.getInputStream()));

    InputStream in = connection.getInputStream();
    assertNotNull(in);
    Document<Entry> doc = abdera.getParser().parse(in);
    Entry entry = doc.getRoot();
    assertEquals(baseURL.getPath() + "rest/packages/restPackage1/versions/2", entry.getBaseUri().getPath());
    assertEquals("restPackage1", entry.getTitle());
    assertEquals("this is package restPackage1", entry.getSummary());
    //assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE.getType(), entry.getContentMimeType().getPrimaryType());
    assertEquals(baseURL.getPath() + "rest/packages/restPackage1/versions/2/binary",
            entry.getContentSrc().getPath());

    List<Link> links = entry.getLinks();
    assertEquals(7, links.size());
    Map<String, Link> linksMap = new HashMap<String, Link>();
    for (Link link : links) {
        linksMap.put(link.getTitle(), link);
    }

    assertEquals(baseURL.getPath() + "rest/packages/restPackage1/versions/2/assets/drools",
            linksMap.get("drools").getHref().getPath());
    assertEquals(baseURL.getPath() + "rest/packages/restPackage1/versions/2/assets/func",
            linksMap.get("func").getHref().getPath());
    assertEquals(baseURL.getPath() + "rest/packages/restPackage1/versions/2/assets/myDSL",
            linksMap.get("myDSL").getHref().getPath());
    assertEquals(baseURL.getPath() + "rest/packages/restPackage1/versions/2/assets/rule1",
            linksMap.get("rule1").getHref().getPath());
    assertEquals(baseURL.getPath() + "rest/packages/restPackage1/versions/2/assets/rule2",
            linksMap.get("rule2").getHref().getPath());
    assertEquals(baseURL.getPath() + "rest/packages/restPackage1/versions/2/assets/model1",
            linksMap.get("model1").getHref().getPath());
}