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

@Test
@RunAsClient//from  w w w.j  a  v a2 s. c  o m
public void testGetSourceContentFromBinaryAsset(@ArquillianResource URL baseURL) throws Exception {
    //Query if the asset exist
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image-new");
    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();
    //The asset should not exist
    assertEquals(404, connection.getResponseCode());

    //Create the asset from binary
    url = new URL(baseURL, "rest/packages/restPackage1/assets");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM);
    connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
    connection.setRequestProperty("Slug", "Error-image-new");
    connection.setDoOutput(true);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] data = new byte[1000];
    int count = 0;
    InputStream is = this.getClass().getResourceAsStream("Error-image.gif");
    while ((count = is.read(data, 0, 1000)) != -1) {
        out.write(data, 0, count);
    }
    connection.getOutputStream().write(out.toByteArray());
    out.close();
    assertEquals(200, connection.getResponseCode());

    //Get the asset source. this will return the binary data as a byte array.
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image-new/source");
    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());
    assertNotNull(result);

    //Roll back changes. 
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image-new");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("DELETE");
    connection.connect();
    assertEquals(204, connection.getResponseCode());

    //Verify the package is indeed deleted
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image-new");
    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(404, connection.getResponseCode());
}

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

@Test
@RunAsClient/*from   w  w w  .  jav  a 2  s.  co m*/
public void testCreateAndUpdateAndGetBinaryAsset(@ArquillianResource URL baseURL) throws Exception {
    //Query if the asset exist
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image");
    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);
    byte[] authEncBytes = Base64.encodeBase64("admin:admin".getBytes());
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    //The asset should not exist
    assertEquals(500, connection.getResponseCode());

    //Create the asset from binary
    url = new URL(baseURL, "rest/packages/restPackage1/assets");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM);
    connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
    connection.setRequestProperty("Slug", "Error-image.gif");
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.setDoOutput(true);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] data = new byte[1000];
    int count = 0;
    InputStream is = this.getClass().getResourceAsStream("Error-image.gif");
    while ((count = is.read(data, 0, 1000)) != -1) {
        out.write(data, 0, count);
    }
    connection.getOutputStream().write(out.toByteArray());
    out.close();
    assertEquals(200, connection.getResponseCode());

    //Get the asset meta data and verify
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image");
    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.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    //System.out.println(IOUtils.toString(connection.getInputStream()));
    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();
    assertEquals("Error-image", entry.getTitle());
    ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA);
    ExtensibleElement formatExtension = metadataExtension.getExtension(Translator.FORMAT);
    assertEquals("gif", formatExtension.getSimpleExtension(Translator.VALUE));

    assertTrue(entry.getPublished() != null);

    //Get the asset binary and verify
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image/binary");
    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.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    //System.out.println(IOUtils.toString(connection.getInputStream()));
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_OCTET_STREAM, connection.getContentType());
    in = connection.getInputStream();
    assertNotNull(in);

    //Update asset binary
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image/binary");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setDoOutput(true);
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_XML);
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    ByteArrayOutputStream out2 = new ByteArrayOutputStream();
    byte[] data2 = new byte[1000];
    int count2 = 0;
    InputStream is2 = this.getClass().getResourceAsStream("Error-image-new.gif");
    while ((count2 = is2.read(data2, 0, 1000)) != -1) {
        out2.write(data2, 0, count2);
    }
    connection.getOutputStream().write(out2.toByteArray());
    out2.close();
    assertEquals(204, connection.getResponseCode());

    //Roll back changes. 
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("DELETE");
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    System.out.println(IOUtils.toString(connection.getInputStream()));
    assertEquals(204, connection.getResponseCode());

    //Verify the package is indeed deleted
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image");
    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.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    assertEquals(500, connection.getResponseCode());
}

From source file:com.github.thesmartenergy.sparql.generate.api.Fetch.java

@GET
public Response doFetch(@Context Request r, @Context HttpServletRequest request,
        @DefaultValue("http://localhost:8080/sparql-generate/example/example1") @QueryParam("uri") String uri,
        @DefaultValue("*/*") @QueryParam("useaccept") String useaccept,
        @DefaultValue("") @QueryParam("accept") String accept) throws IOException {

    HttpURLConnection con;
    String message = null;/* ww  w.  ja  v a  2  s.  com*/
    URL obj;
    try {
        obj = new URL(uri);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", useaccept);
        con.setInstanceFollowRedirects(true);
        System.out.println("GET to " + uri + " returned " + con.getResponseCode());
        InputStream in = con.getInputStream();
        message = IOUtils.toString(in);
    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("Error while trying to access message at URI <" + uri + ">: " + e.getMessage()).build();
    }

    Map<String, List<String>> headers = con.getHeaderFields();
    if (!headers.containsKey("Link")) {
        return Response.status(Response.Status.BAD_REQUEST).entity(
                "Error while processing message at URI <" + uri + ">: there should be a Link header field")
                .build();
    }
    String var = null;
    URL qobj = null;
    for (String linkstr : headers.get("Link")) {
        Link link = Link.valueOf(linkstr);
        if (link.getRels().contains("https://w3id.org/sparql-generate/voc#spargl-query")
                || link.getRels().contains("spargl-query")) {
            Map<String, String> params = link.getParams();
            // check the context
            // check syntax for variable ?
            var = params.getOrDefault("var", "message");
            // ok for relative and absolute URIs ?
            try {
                qobj = obj.toURI().resolve(link.getUri()).toURL();
                System.out.println("found link " + qobj + " and var " + var);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            break;
        }
        // what if multiple suitable links ? 
    }

    if (var == null || qobj == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Error while processing message at URI <"
                + uri
                + ">: did not find a suitable link with relation spargl-query, or https://w3id.org/sparql-generate/voc#spargl-query")
                .build();
    }

    HttpURLConnection qcon;
    String query;
    try {
        qcon = (HttpURLConnection) qobj.openConnection();
        qcon.setRequestMethod("GET");
        qcon.setRequestProperty("Accept", "application/sparql-generate");
        qcon.setInstanceFollowRedirects(true);
        System.out.println("GET to " + qobj + " returned " + qcon.getResponseCode());
        InputStream in = qcon.getInputStream();
        query = IOUtils.toString(in);
    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("Error while trying to access query at URI <" + qobj + ">: " + e.getMessage()).build();
    }

    System.out.println("got query " + query);

    // parse the SPARQL-Generate query and create plan
    PlanFactory factory = new PlanFactory();

    Syntax syntax = SPARQLGenerate.SYNTAX;
    SPARQLGenerateQuery q = (SPARQLGenerateQuery) QueryFactory.create(query, syntax);
    if (q.getBaseURI() == null) {
        q.setBaseURI("http://example.org/");
    }
    RootPlan plan = factory.create(q);

    // create the initial model
    Model model = ModelFactory.createDefaultModel();

    // if content encoding is not text-based, then use base64 encoding
    // use con.getContentEncoding() for this

    String dturi = "http://www.w3.org/2001/XMLSchema#string";
    String ct = con.getContentType();
    if (ct != null) {
        dturi = "urn:iana:mime:" + ct;
    }

    QuerySolutionMap initialBinding = new QuerySolutionMap();
    TypeMapper typeMapper = TypeMapper.getInstance();
    RDFDatatype dt = typeMapper.getSafeTypeByName(dturi);
    Node arqLiteral = NodeFactory.createLiteral(message, dt);
    RDFNode jenaLiteral = model.asRDFNode(arqLiteral);
    initialBinding.add(var, jenaLiteral);

    // execute the plan
    plan.exec(initialBinding, model);

    System.out.println(accept);
    if (!accept.equals("text/turtle") && !accept.equals("application/rdf+xml")) {
        List<Variant> vs = Variant
                .mediaTypes(new MediaType("application", "rdf+xml"), new MediaType("text", "turtle")).build();
        Variant v = r.selectVariant(vs);
        accept = v.getMediaType().toString();
    }

    System.out.println(accept);
    StringWriter sw = new StringWriter();
    Response.ResponseBuilder res;
    if (accept.equals("application/rdf+xml")) {
        model.write(sw, "RDF/XML", "http://example.org/");
        res = Response.ok(sw.toString(), "application/rdf+xml");
        res.header("Content-Disposition", "filename= message.rdf;");
        return res.build();
    } else {
        model.write(sw, "TTL", "http://example.org/");
        res = Response.ok(sw.toString(), "text/turtle");
        res.header("Content-Disposition", "filename= message.ttl;");
        return res.build();
    }
}

From source file:groovyx.net.http.HttpURLClient.java

/**
 * Perform a request.  Parameters are:/* w w w.j  ava2s.  c  om*/
 * <dl>
 *   <dt>url</dt><dd>the entire request URL</dd>
 *   <dt>path</dt><dd>the path portion of the request URL, if a default
 *     URL is set on this instance.</dd>
 *   <dt>query</dt><dd>URL query parameters for this request.</dd>
 *   <dt>timeout</dt><dd>see {@link HttpURLConnection#setReadTimeout(int)}</dd>
 *   <dt>method</dt><dd>This defaults to GET, or POST if a <code>body</code>
 *   parameter is also specified.</dd>
 *   <dt>contentType</dt><dd>Explicitly specify how to parse the response.
 *     If this value is ContentType.ANY, the response <code>Content-Type</code>
 *     header is used to determine how to parse the response.</dd>
 *   <dt>requestContentType</dt><dd>used in a PUT or POST request to
 *     transform the request body and set the proper
 *     <code>Content-Type</code> header.  This defaults to the
 *     <code>contentType</code> if unset.</dd>
 *   <dt>auth</dt><dd>Basic authorization; pass the value as a list in the
 *   form [user, pass]</dd>
 *   <dt>headers</dt><dd>additional request headers, as a map</dd>
 *   <dt>body</dt><dd>request content body, for a PUT or POST request.
 *     This will be encoded using the requestContentType</dd>
 * </dl>
 * @param args named parameters
 * @return the parsed response
 * @throws URISyntaxException
 * @throws MalformedURLException
 * @throws IOException
 */
public HttpResponseDecorator request(Map<String, ?> args)
        throws URISyntaxException, MalformedURLException, IOException {

    // copy so we don't modify the original collection when removing items:
    args = new HashMap<String, Object>(args);

    Object arg = args.remove("url");
    if (arg == null && this.defaultURL == null)
        throw new IllegalStateException("Either the 'defaultURL' property"
                + " must be set or a 'url' parameter must be passed to the " + "request method.");
    URIBuilder url = arg != null ? new URIBuilder(arg.toString()) : defaultURL.clone();

    arg = null;
    arg = args.remove("path");
    if (arg != null)
        url.setPath(arg.toString());
    arg = null;
    arg = args.remove("query");
    if (arg != null) {
        if (!(arg instanceof Map<?, ?>))
            throw new IllegalArgumentException("'query' must be a map");
        url.setQuery((Map<?, ?>) arg);
    }

    HttpURLConnection conn = (HttpURLConnection) url.toURL().openConnection();
    conn.setInstanceFollowRedirects(this.followRedirects);

    arg = null;
    arg = args.remove("timeout");
    if (arg != null)
        conn.setConnectTimeout(Integer.parseInt(arg.toString()));

    arg = null;
    arg = args.remove("method");
    if (arg != null)
        conn.setRequestMethod(arg.toString());

    arg = null;
    arg = args.remove("contentType");
    Object contentType = arg != null ? arg : this.contentType;
    if (contentType instanceof ContentType)
        conn.addRequestProperty("Accept", ((ContentType) contentType).getAcceptHeader());

    arg = null;
    arg = args.remove("requestContentType");
    String requestContentType = arg != null ? arg.toString()
            : this.requestContentType != null ? this.requestContentType.toString()
                    : contentType != null ? contentType.toString() : null;

    // must add default headers before setting auth:
    for (String key : defaultHeaders.keySet())
        conn.addRequestProperty(key, defaultHeaders.get(key));

    arg = null;
    arg = args.remove("auth");
    if (arg != null) {
        if (oauth != null)
            log.warn("You are trying to use both OAuth and basic authentication!");
        try {
            List<?> vals = (List<?>) arg;
            conn.addRequestProperty("Authorization",
                    getBasicAuthHeader(vals.get(0).toString(), vals.get(1).toString()));
        } catch (Exception ex) {
            throw new IllegalArgumentException("Auth argument must be a list in the form [user,pass]");
        }
    }

    arg = null;
    arg = args.remove("headers");
    if (arg != null) {
        if (!(arg instanceof Map<?, ?>))
            throw new IllegalArgumentException("'headers' must be a map");
        Map<?, ?> headers = (Map<?, ?>) arg;
        for (Object key : headers.keySet())
            conn.addRequestProperty(key.toString(), headers.get(key).toString());
    }

    arg = null;
    arg = args.remove("body");
    if (arg != null) { // if there is a request POST or PUT body
        conn.setDoOutput(true);
        final HttpEntity body = (HttpEntity) encoderRegistry.getAt(requestContentType).call(arg);
        // TODO configurable request charset

        //TODO don't override if there is a 'content-type' in the headers list
        conn.addRequestProperty("Content-Type", requestContentType);
        try {
            // OAuth Sign if necessary.
            if (oauth != null)
                conn = oauth.sign(conn, body);
            // send request data
            DefaultGroovyMethods.leftShift(conn.getOutputStream(), body.getContent());
        } finally {
            conn.getOutputStream().close();
        }
    }
    // sign the request if we're using OAuth
    else if (oauth != null)
        conn = oauth.sign(conn, null);

    if (args.size() > 0) {
        String illegalArgs = "";
        for (String k : args.keySet())
            illegalArgs += k + ",";
        throw new IllegalArgumentException("Unknown named parameters: " + illegalArgs);
    }

    String method = conn.getRequestMethod();
    log.debug(method + " " + url);

    HttpResponse response = new HttpURLResponseAdapter(conn);
    if (ContentType.ANY.equals(contentType))
        contentType = conn.getContentType();

    Object result = this.getparsedResult(method, contentType, response);

    log.debug(response.getStatusLine());
    HttpResponseDecorator decoratedResponse = new HttpResponseDecorator(response, result);

    if (log.isTraceEnabled()) {
        for (Header h : decoratedResponse.getHeaders())
            log.trace(" << " + h.getName() + " : " + h.getValue());
    }

    if (conn.getResponseCode() > 399)
        throw new HttpResponseException(decoratedResponse);

    return decoratedResponse;
}

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

@Test
@RunAsClient/*from   w  ww .j a va 2s . co m*/
public void testCreateAndUpdateAndGetBinaryAsset(@ArquillianResource URL baseURL) throws Exception {
    //Query if the asset exist
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image");
    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);
    byte[] authEncBytes = Base64.encodeBase64("admin:admin".getBytes());
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    //The asset should not exist
    assertEquals(404, connection.getResponseCode());

    //Create the asset from binary
    url = new URL(baseURL, "rest/packages/restPackage1/assets");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM);
    connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
    connection.setRequestProperty("Slug", "Error-image.gif");
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.setDoOutput(true);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] data = new byte[1000];
    int count = 0;
    InputStream is = this.getClass().getResourceAsStream("Error-image.gif");
    while ((count = is.read(data, 0, 1000)) != -1) {
        out.write(data, 0, count);
    }
    connection.getOutputStream().write(out.toByteArray());
    out.close();
    assertEquals(200, connection.getResponseCode());

    //Get the asset meta data and verify
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image");
    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.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    //System.out.println(IOUtils.toString(connection.getInputStream()));
    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();
    assertEquals("Error-image", entry.getTitle());
    ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA);
    ExtensibleElement formatExtension = metadataExtension.getExtension(Translator.FORMAT);
    assertEquals("gif", formatExtension.getSimpleExtension(Translator.VALUE));

    assertTrue(entry.getPublished() != null);

    //Get the asset binary and verify
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image/binary");
    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.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    //System.out.println(IOUtils.toString(connection.getInputStream()));
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_OCTET_STREAM, connection.getContentType());
    in = connection.getInputStream();
    assertNotNull(in);

    //Update asset binary
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image/binary");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setDoOutput(true);
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_XML);
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM);
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    ByteArrayOutputStream out2 = new ByteArrayOutputStream();
    byte[] data2 = new byte[1000];
    int count2 = 0;
    InputStream is2 = this.getClass().getResourceAsStream("Error-image-new.gif");
    while ((count2 = is2.read(data2, 0, 1000)) != -1) {
        out2.write(data2, 0, count2);
    }
    connection.getOutputStream().write(out2.toByteArray());
    out2.close();
    assertEquals(204, connection.getResponseCode());

    //Roll back changes. 
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("DELETE");
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    assertEquals(204, connection.getResponseCode());

    //Verify the package is indeed deleted
    url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image");
    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.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    assertEquals(404, connection.getResponseCode());
}

From source file:com.cr_wd.android.network.HttpClient.java

/**
 * Performs a HTTP GET/POST Request/*w  ww  .  j av a 2 s .c  om*/
 * 
 * @return id of the request
 */
protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params,
        final HttpHandler handler) {
    if (headers == null) {
        headers = new HttpHeaders();
    }
    if (params == null) {
        params = new HttpParams();
    }

    handler.client = this;

    final int requestId = incrementRequestId();

    class HandlerRunnable extends Handler implements Runnable {

        private final Method method;
        private String url;
        private final HttpHeaders headers;
        private final HttpParams params;
        private final HttpHandler handler;
        private HttpResponse response;

        private boolean canceled = false;
        private int retries = 0;

        protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers,
                final HttpParams params, final HttpHandler handler) {
            this.method = method;
            this.url = url;
            this.headers = headers;
            this.params = params;
            this.handler = handler;
        }

        @Override
        public void run() {
            execute();
        }

        private void execute() {
            response = new HttpResponse(requestId, method, url);

            HttpURLConnection conn = null;
            try {
                /* append query string for GET requests */
                if (method == Method.GET) {
                    if (!params.urlParams.isEmpty()) {
                        url += ('?' + params.getParamString());
                    }
                }

                /* setup headers for POST requests */
                if (method == Method.POST) {
                    headers.addHeader("Accept-Charset", requestOptions.encoding);
                    if (params.hasMultipartParams()) {
                        final SimpleMultipart multipart = params.getMultipart();
                        headers.addHeader("Content-Type", multipart.getContentType());
                    } else {
                        headers.addHeader("Content-Type",
                                "application/x-www-form-urlencoded;charset=" + requestOptions.encoding);
                    }
                }

                if (canceled) {
                    postCancel();
                    return;
                }

                /* open and configure the connection */
                conn = (HttpURLConnection) new URL(url).openConnection();

                postStart();

                if (method == Method.GET) {
                    conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                } else if (method == Method.POST) {
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                }
                conn.setAllowUserInteraction(false);
                conn.setReadTimeout(requestOptions.readTimeout);
                conn.setConnectTimeout(requestOptions.connectTimeout);

                /* add headers to the connection */
                for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) {
                    for (final String value : entry.getValue()) {
                        conn.addRequestProperty(entry.getKey(), value);
                    }
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.requestProperties = conn.getRequestProperties();

                /* do post */
                if (method == Method.POST) {
                    InputStream is;

                    if (params.hasMultipartParams()) {
                        is = params.getMultipart().getContent();
                    } else {
                        is = new ByteArrayInputStream(params.getParamString().getBytes());
                    }

                    final OutputStream os = conn.getOutputStream();

                    writeStream(os, is);
                } else {
                    conn.connect();
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.contentEncoding = conn.getContentEncoding();
                response.contentLength = conn.getContentLength();
                response.contentType = conn.getContentType();
                response.date = conn.getDate();
                response.expiration = conn.getExpiration();
                response.headerFields = conn.getHeaderFields();
                response.ifModifiedSince = conn.getIfModifiedSince();
                response.lastModified = conn.getLastModified();
                response.responseCode = conn.getResponseCode();
                response.responseMessage = conn.getResponseMessage();

                /* do get */
                if (conn.getResponseCode() < 400) {
                    response.responseBody = readStream(conn.getInputStream());
                    postSuccess();
                } else {
                    response.responseBody = readStream(conn.getErrorStream());
                    response.throwable = new Exception(response.responseMessage);
                    postError();
                }

            } catch (final Exception e) {
                if (retries < requestOptions.maxRetries) {
                    retries++;
                    postRetry();
                    execute();
                } else {
                    response.responseBody = e.getMessage();
                    response.throwable = e;
                    postError();
                }
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }

        private String readStream(final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            final ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                baf.append(buffer, 0, read);
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }

            return new String(baf.toByteArray());
        }

        private void writeStream(final OutputStream os, final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                os.write(buffer, 0, read);
            }

            if (!canceled) {
                os.flush();
            }

            try {
                os.close();
            } catch (final IOException e) {
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }
        }

        @Override
        public void handleMessage(final Message msg) {
            if (msg.what == HttpHandler.MESSAGE_CANCEL) {
                canceled = true;
            }
        }

        private void postSuccess() {
            postMessage(HttpHandler.MESSAGE_SUCCESS);
        }

        private void postError() {
            postMessage(HttpHandler.MESSAGE_ERROR);
        }

        private void postCancel() {
            postMessage(HttpHandler.MESSAGE_CANCEL);
        }

        private void postStart() {
            postMessage(HttpHandler.MESSAGE_START);
        }

        private void postRetry() {
            postMessage(HttpHandler.MESSAGE_RETRY);
        }

        private void postMessage(final int what) {
            final Message msg = handler.obtainMessage();
            msg.what = what;
            msg.arg1 = requestId;
            msg.obj = response;
            handler.sendMessage(msg);
        }
    }
    ;
    /* Create a new HandlerRunnable and start it */
    final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler);
    requests.put(requestId, new WeakReference<Handler>(hr));
    new Thread(hr).start();

    /* Return with the request id */
    return requestId;
}

From source file:easyshop.downloadhelper.HttpPageGetter.java

public HttpPage getDHttpPage(PageRef url, String charSet) {
    count++;//from  w w w .  ja v a  2 s.co  m
    log.debug("getURL(" + count + ")");

    if (url.getUrlStr() == null) {
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new OriHttpPage(-1, null, null, null, conRes, null);
    }
    URL requestedURL = null;
    try {
        requestedURL = new URL(url.getUrlStr());
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        log.error("wrong urlstr" + url.getUrlStr());
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new OriHttpPage(-1, null, null, null, conRes, null);
    }
    ;
    //        System.out.println(""+requestedURL.toExternalForm());
    URL referer = null;
    try {
        log.debug("Creating HTTP connection to " + requestedURL);
        HttpURLConnection conn = (HttpURLConnection) requestedURL.openConnection();
        if (referer != null) {
            log.debug("Setting Referer header to " + referer);
            conn.setRequestProperty("Referer", referer.toExternalForm());
        }

        if (userAgent != null) {
            log.debug("Setting User-Agent to " + userAgent);
            conn.setRequestProperty("User-Agent", userAgent);
        }

        //            DateFormat dateFormat=DateFormat.getDateInstance();
        //            conn.setRequestProperty("If-Modlfied-Since",dateFormat.parse("2005-08-15 20:18:30").toGMTString());
        conn.setUseCaches(false);

        //            conn.setRequestProperty("connection","keep-alive");
        for (Iterator it = conn.getRequestProperties().keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();
            if (key == null) {
                break;
            }
            String value = conn.getHeaderField(key);
            //                System.out.println("Request header " + key + ": " + value);
        }
        log.debug("Opening URL");
        long startTime = System.currentTimeMillis();
        conn.connect();

        String resp = conn.getResponseMessage();
        log.debug("Remote server response: " + resp);

        int code = conn.getResponseCode();

        if (code != 200) {
            log.error("Could not get connection for code=" + code);
            System.err.println("Could not get connection for code=" + code);
            ConnResponse conRes = new ConnResponse(null, null, 0, 0, code);
            return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
        }

        //            if (conn.getContentLength()<=0||conn.getContentLength()>10000000){
        //               log.error("Content length==0");
        //               System.err.println("Content length==0");
        //               ConnResponse conRes=new ConnResponse(null,null,null,0,0,-100);
        //               return new URLObject(-1,requestedURL, null,null,conRes);
        //            }

        String respStr = conn.getHeaderField(0);
        long serverDate = conn.getDate();
        //            log.info("Server response: " + respStr);

        for (int i = 1; i < conn.getHeaderFields().size(); i++) {
            String key = conn.getHeaderFieldKey(i);
            if (key == null) {
                break;
            }
            String value = conn.getHeaderField(key);
            //                System.out.println("Received header " + key + ": " + value);
            //               log.debug("Received header " + key + ": " + value);
        }

        //            log.debug("Getting buffered input stream from remote connection");
        log.debug("start download(" + count + ")");
        BufferedInputStream remoteBIS = new BufferedInputStream(conn.getInputStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream(10240);
        byte[] buf = new byte[1024];
        int bytesRead = 0;
        while (bytesRead >= 0) {
            baos.write(buf, 0, bytesRead);
            bytesRead = remoteBIS.read(buf);
        }
        //            baos.write(remoteBIS.read(new byte[conn.getContentLength()]));
        //            remoteBIS.close();
        byte[] content = baos.toByteArray();
        long timeTaken = System.currentTimeMillis() - startTime;
        if (timeTaken < 100)
            timeTaken = 500;

        int bytesPerSec = (int) ((double) content.length / ((double) timeTaken / 1000.0));
        //            log.info("Downloaded " + content.length + " bytes, " + bytesPerSec + " bytes/sec");
        if (content.length < conn.getContentLength()) {
            log.warn("Didn't download full content for URL: " + url);
            //                failureCount++;
            ConnResponse conRes = new ConnResponse(conn.getContentType(), null, content.length, serverDate,
                    code);
            return new HttpPage(requestedURL.toExternalForm(), null, conRes, conn.getContentType());
        }

        log.debug("download(" + count + ")");

        ConnResponse conRes = new ConnResponse(conn.getContentType(), null, conn.getContentLength(), serverDate,
                code);
        String c = charSet;
        if (c == null)
            c = conRes.getCharSet();
        HttpPage obj = new HttpPage(requestedURL.toExternalForm(), content, conRes, c);
        return obj;
    } catch (IOException ioe) {
        log.warn("Caught IO Exception: " + ioe.getMessage(), ioe);
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
    } catch (Exception e) {
        log.warn("Caught Exception: " + e.getMessage(), e);
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
    }
}

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

@Test
@RunAsClient/*ww w.j  av a 2  s .c o m*/
public void testGetHistoricalAssetBinary(@ArquillianResource URL baseURL) throws Exception {
    //Query if the asset exist
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary");
    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);
    byte[] authEncBytes = Base64.encodeBase64("admin:admin".getBytes());
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    //The asset should not exist
    assertEquals(500, connection.getResponseCode());

    //Create the asset from binary
    url = new URL(baseURL, "rest/packages/restPackage1/assets");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM);
    connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML);
    connection.setRequestProperty("Slug", "testGetHistoricalAssetBinary.gif");
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.setDoOutput(true);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] data = new byte[1000];
    int count = 0;
    InputStream is = this.getClass().getResourceAsStream("Error-image.gif");
    while ((count = is.read(data, 0, 1000)) != -1) {
        out.write(data, 0, count);
    }
    connection.getOutputStream().write(out.toByteArray());
    out.close();
    assertEquals(200, connection.getResponseCode());

    //Update asset binary
    url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary/binary");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setDoOutput(true);
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_XML);
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    ByteArrayOutputStream out2 = new ByteArrayOutputStream();
    byte[] data2 = new byte[1000];
    int count2 = 0;
    InputStream is2 = this.getClass().getResourceAsStream("Error-image-new.gif");
    while ((count2 = is2.read(data2, 0, 1000)) != -1) {
        out2.write(data2, 0, count2);
    }
    connection.getOutputStream().write(out2.toByteArray());
    out2.close();
    assertEquals(204, connection.getResponseCode());

    //Get the asset binary version 1 and verify
    url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary/versions/1/binary");
    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.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_OCTET_STREAM, connection.getContentType());
    InputStream in = connection.getInputStream();
    assertNotNull(in);

    //Get the asset binary version 2 and verify
    url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary/versions/2/binary");
    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.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    assertEquals(200, connection.getResponseCode());
    assertEquals(MediaType.APPLICATION_OCTET_STREAM, connection.getContentType());
    in = connection.getInputStream();
    assertNotNull(in);

    //Roll back changes. 
    url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization",
            "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("DELETE");
    connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    System.out.println(IOUtils.toString(connection.getInputStream()));
    assertEquals(204, connection.getResponseCode());

    //Verify the package is indeed deleted
    url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary");
    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.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
    connection.connect();
    assertEquals(500, connection.getResponseCode());
}

From source file:i5.las2peer.services.mobsos.SurveyService.java

/**
 * Parses incoming content to a questionnaire JSON representation including checks for completeness, illegal fields and values.
 *///from w  ww  .j av a  2s.  com
private JSONObject parseQuestionnaire(String content) throws IllegalArgumentException {

    JSONObject o;
    try {
        o = (JSONObject) JSONValue.parseWithException(content);
    } catch (ParseException e1) {
        throw new IllegalArgumentException("Questionnaire data *" + content + "* is not valid JSON!");
    }

    // check result for unknown illegal fields. If so, parsing fails.
    String[] fields = { "id", "owner", "organization", "logo", "name", "description", "lang" };
    for (Object key : o.keySet()) {
        if (!Arrays.asList(fields).contains(key)) {

            throw new IllegalArgumentException("Illegal questionnaire field '" + key + "' detected!");

        } else {
            if (key.equals("name") && !(o.get(key) instanceof String)) {
                throw new IllegalArgumentException(
                        "Illegal value for questionnaire field 'name'. Should be a string.");
            } else if (key.equals("description") && !(o.get(key) instanceof String)) {
                throw new IllegalArgumentException(
                        "Illegal value for questionnaire field 'description'. Should be a string.");
            } else if (key.equals("organization") && !(o.get(key) instanceof String)) {
                throw new IllegalArgumentException(
                        "Illegal value for questionnaire field 'organization'. Should be a string.");
            } else if (key.equals("logo")) {
                try {
                    URL u = new URL((String) o.get(key));
                    HttpURLConnection con = (HttpURLConnection) u.openConnection();
                    if (404 == con.getResponseCode()) {
                        throw new IllegalArgumentException(
                                "Illegal value for questionnaire field 'logo'. Should be a valid URL to an image resource.");
                    }
                    if (!con.getContentType().matches("image/.*")) {
                        throw new IllegalArgumentException(
                                "Illegal value for questionnaire field 'logo'. Should be a valid URL to an image resource.");
                    }
                } catch (MalformedURLException e) {
                    throw new IllegalArgumentException(
                            "Illegal value for questionnaire field 'logo'. Should be a valid URL to an image resource.");
                } catch (IOException e) {
                    throw new IllegalArgumentException(
                            "Illegal value for questionnaire field 'logo'. Should be a valid URL to an image resource.");
                }
            } else if (key.equals("lang")) {

                String lang = (String) o.get(key);

                Pattern p = Pattern.compile("[a-z]+-[A-Z]+");
                Matcher m = p.matcher(lang);

                // do not iterate over all locales found, but only use first option with highest preference.

                Locale l = null;

                if (m.find()) {
                    String[] tokens = m.group().split("-");
                    l = new Locale(tokens[0], tokens[1]);
                    //l = new Locale("zz","ZZ");
                    //System.out.println("Locale: " + l.getDisplayCountry() + " " + l.getDisplayLanguage());
                } else {
                    throw new IllegalArgumentException(
                            "Illegal value for questionnaire field 'lang'. Should be a valid locale such as en-US or de-DE");
                }
            }
        }
    }

    // check if all necessary fields are specified.
    if (o.get("name") == null || o.get("organization") == null || o.get("logo") == null
            || o.get("description") == null || o.get("lang") == null) {
        throw new IllegalArgumentException(
                "Questionnaire data incomplete! All fields name, organization, logo, description, and lang must be defined!");
    }

    return o;
}