Example usage for org.apache.http.entity InputStreamEntity InputStreamEntity

List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity

Introduction

In this page you can find the example usage for org.apache.http.entity InputStreamEntity InputStreamEntity.

Prototype

public InputStreamEntity(InputStream inputStream, ContentType contentType) 

Source Link

Usage

From source file:org.acoustid.server.util.ParameterMap.java

public static ParameterMap parseRequest(HttpServletRequest request) throws IOException {
    String contentEncoding = request.getHeader("Content-Encoding");
    if (contentEncoding != null) {
        contentEncoding = contentEncoding.toLowerCase();
    }/*from w w w .j  a  va 2 s.c o  m*/
    String contentType = request.getContentType();
    Map<String, String[]> map;
    if ("gzip".equals(contentEncoding) && "application/x-www-form-urlencoded".equals(contentType)) {
        InputStream inputStream = new GZIPInputStream(request.getInputStream());
        InputStreamEntity entity = new InputStreamEntity(inputStream, -1);
        entity.setContentType(contentType);
        map = new HashMap<String, String[]>();
        for (NameValuePair param : URLEncodedUtils.parse(entity)) {
            String name = param.getName();
            String value = param.getValue();
            String[] values = map.get(name);
            if (values == null) {
                values = new String[] { value };
            } else {
                values = (String[]) ArrayUtils.add(values, value);
            }
            map.put(name, values);
        }
    } else {
        map = request.getParameterMap();
    }
    return new ParameterMap(map);
}

From source file:net.sf.smbt.btc.utils.BTCResourceUtils.java

public void upload(String portID, String command, File file) {
    String query = portID + command;

    boolean verbose = true;
    boolean requestFailed = false;

    HttpResponse response;//from   w ww. ja  v a  2  s .  c om
    HttpEntity entity;
    HttpClient httpclient = new DefaultHttpClient();

    try {
        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
        reqEntity.setContentType("application/xml");
        reqEntity.setChunked(true);

        HttpPost httpput = new HttpPost(query);
        httpput.setEntity(reqEntity);

        if (verbose) {
            System.out.println("-------- open ubibot connection --------");
            System.out.println("executing request: " + httpput.getURI());
        }

        response = httpclient.execute(httpput); // execute this mother
        entity = response.getEntity();

        String ubiResponse = "";
        String statusLine = response.getStatusLine().toString() + "\n";
        String delims = "[ ]+";
        String[] tokens = statusLine.split(delims);

        if (tokens[1].equals("200")) { // success
            System.out.println("\nserver response:");
            System.out.println(statusLine);
            ubiResponse = EntityUtils.toString(entity);
        } else { // bad request
            System.out.println("\nbad request. status code: \n");
            System.out.println(statusLine);
            System.out.println("check the HTTP status codes");
            ubiResponse = EntityUtils.toString(entity) + "\n\n";
            Header[] respHeader;
            respHeader = response.getAllHeaders();
            for (int i = 0; i < respHeader.length; i++) {
                ubiResponse += respHeader[i].toString() + "\n";
            }
            if (verbose)
                System.out.print(ubiResponse);
            requestFailed = true;
            // "***failed request***";
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
        if (verbose) {
            System.out.println("----------- connection closed ----------\n");
        }
    }
}

From source file:net.facework.core.http.ModAssetServer.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    AbstractHttpEntity body = null;/*w ww  .  j a v a 2s .  co m*/

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    final String url = URLDecoder.decode(request.getRequestLine().getUri());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length);
    }

    final String location = "www" + (url.equals("/") ? "/index.htm" : url);
    response.setStatusCode(HttpStatus.SC_OK);

    try {
        Log.i(TAG, "Requested: \"" + url + "\"");

        // Compares the Last-Modified date header (if present) with the If-Modified-Since date
        if (request.containsHeader("If-Modified-Since")) {
            try {
                Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue());
                if (date.compareTo(mServer.mLastModified) <= 0) {
                    // The file has not been modified
                    response.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
                    return;
                }
            } catch (DateParseException e) {
                e.printStackTrace();
            }
        }

        // We determine if the asset is compressed
        try {
            AssetFileDescriptor afd = mAssetManager.openFd(location);

            // The asset is not compressed
            FileInputStream fis = new FileInputStream(afd.getFileDescriptor());
            fis.skip(afd.getStartOffset());
            body = new InputStreamEntity(fis, afd.getDeclaredLength());

            Log.d(TAG, "Serving uncompressed file " + "www" + url);

        } catch (FileNotFoundException e) {

            // The asset may be compressed
            // AAPT compresses assets so first we need to uncompress them to determine their length
            InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000);
            byte[] tmp = new byte[4096];
            int length = 0;
            while ((length = stream.read(tmp)) != -1)
                buffer.write(tmp, 0, length);
            body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size());
            stream.close();

            Log.d(TAG, "Serving compressed file " + "www" + url);

        }

        body.setContentType(getMimeMediaType(url) + "; charset=UTF-8");
        response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified));

    } catch (IOException e) {
        // File does not exist
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        body = new EntityTemplate(new ContentProducer() {
            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("<html><body><h1>");
                writer.write("File ");
                writer.write("www" + url);
                writer.write(" not found");
                writer.write("</h1></body></html>");
                writer.flush();
            }
        });
        Log.d(TAG, "File " + "www" + url + " not found");
        body.setContentType("text/html; charset=UTF-8");
    }

    response.setEntity(body);

}

From source file:com.wifi.brainbreaker.mydemo.http.ModAssetServer.java

public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    AbstractHttpEntity body = null;//w ww .  jav a  2 s. c om

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    final String url = URLDecoder.decode(request.getRequestLine().getUri());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length);
    }

    final String location = "www" + (url.equals("/") ? "/index.htm" : url);
    response.setStatusCode(HttpStatus.SC_OK);

    try {
        Log.i(TAG, "Requested: \"" + url + "\"");

        // Compares the Last-Modified date header (if present) with the If-Modified-Since date
        if (request.containsHeader("If-Modified-Since")) {
            try {
                Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue());
                if (date.compareTo(mServer.mLastModified) <= 0) {
                    // The file has not been modified
                    response.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
                    return;
                }
            } catch (DateParseException e) {
                e.printStackTrace();
            }
        }

        // We determine if the asset is compressed
        try {
            AssetFileDescriptor afd = mAssetManager.openFd(location);

            // The asset is not compressed
            FileInputStream fis = new FileInputStream(afd.getFileDescriptor());
            fis.skip(afd.getStartOffset());
            body = new InputStreamEntity(fis, afd.getDeclaredLength());

            Log.d(TAG, "Serving uncompressed file " + "www" + url);

        } catch (FileNotFoundException e) {

            // The asset may be compressed
            // AAPT compresses assets so first we need to uncompress them to determine their length
            InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000);
            byte[] tmp = new byte[4096];
            int length = 0;
            while ((length = stream.read(tmp)) != -1)
                buffer.write(tmp, 0, length);
            body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size());
            stream.close();

            Log.d(TAG, "Serving compressed file " + "www" + url);

        }

        body.setContentType(getMimeMediaType(url) + "; charset=UTF-8");
        response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified));

    } catch (IOException e) {
        // File does not exist
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        body = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("<html><body><h1>");
                writer.write("File ");
                writer.write("www" + url);
                writer.write(" not found");
                writer.write("</h1></body></html>");
                writer.flush();
            }
        });
        Log.d(TAG, "File " + "www" + url + " not found");
        body.setContentType("text/html; charset=UTF-8");
    }

    response.setEntity(body);

}

From source file:com.intel.cosbench.client.amplistor.AmpliClient.java

public String StoreStreamedObject(InputStream stream, long length, String ampliNamespace, String ampliFilename)
        throws IOException, HttpException, AmpliException {
    HttpPut method = null;//from  ww w .  ja v a 2s  .  c o  m
    HttpResponse response = null;
    try {
        String storageUrl = "http://" + this.host + ":" + this.port + nsRoot;
        method = HttpClientUtil.makeHttpPut(storageUrl + "/" + HttpClientUtil.encodeURL(ampliNamespace) + "/"
                + HttpClientUtil.encodeURL(ampliFilename));

        InputStreamEntity entity = new InputStreamEntity(stream, length);

        if (length < 0)
            entity.setChunked(true);
        else {
            entity.setChunked(false);
        }

        method.setEntity(entity);

        response = client.execute(method);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return response.getFirstHeader("ETag").getValue();
        }

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return response.getFirstHeader("ETag").getValue();
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED) {
            throw new AmpliException("Etag missmatch", response.getAllHeaders(), response.getStatusLine());
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_LENGTH_REQUIRED) {
            throw new AmpliException("Length miss-match", response.getAllHeaders(), response.getStatusLine());
        } else {
            throw new AmpliException(
                    System.currentTimeMillis() + ": [" + Thread.currentThread().getName() + "]: "
                            + ampliNamespace + "/" + ampliFilename + ": " + response.getStatusLine(),
                    response.getAllHeaders(), response.getStatusLine());
        }
    } finally {
        if (response != null)
            EntityUtils.consume(response.getEntity());
    }
}

From source file:de.kp.ames.http.HttpClient.java

public Response doPost(String url, InputStream stream, String mimetype) throws Exception {

    /*/*from   ww  w .jav  a  2 s  .c o m*/
     * Create HttpPost
     */
    URI uri = createUri(url);
    HttpPost httpPost = new HttpPost(uri);

    /*
     * Set header
     */
    httpPost.setHeader(CONTENT_TYPE_LABEL, mimetype);

    long length = getLengthFromInputStream(stream);

    HttpEntity entity = new InputStreamEntity(stream, length);
    httpPost.setEntity(entity);

    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity httpEntity = new BufferedHttpEntity(response.getEntity());

    return new Response(httpEntity.getContent(), response.getStatusLine().getStatusCode());

}

From source file:bookkeepr.jettyhandlers.WebHandler.java

public void handle(String path, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException {
    if (path.equals("/")) {
        response.sendRedirect("/web/");
    }/*from   w  w  w. j  a v  a 2s . c o  m*/

    HttpClient httpclient = null;
    if (path.startsWith("/web/xmlify")) {
        ((Request) request).setHandled(true);
        if (request.getMethod().equals("POST")) {
            try {
                String remotePath = path.substring(11);

                BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
                XMLAble xmlable = null;
                try {
                    xmlable = httpForm2XmlAble(reader.readLine());
                } catch (BookKeeprException ex) {
                    response.sendError(400,
                            "Server could not form xml from the form data you submitted. " + ex.getMessage());
                    return;
                }
                if (xmlable == null) {
                    response.sendError(500,
                            "Server could not form xml from the form data you submitted. The server created a null value!");
                    return;

                }
                //                    XMLWriter.write(System.out, xmlable);
                //                    if(true)return;

                HttpPost httppost = new HttpPost(bookkeepr.getConfig().getExternalUrl() + remotePath);
                httppost.getParams().setBooleanParameter("http.protocol.strict-transfer-encoding", false);

                ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
                XMLWriter.write(out, xmlable);
                ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
                httppost.setEntity(new InputStreamEntity(in, -1));
                Logger.getLogger(WebHandler.class.getName()).log(Level.INFO,
                        "Xmlifier posting to " + bookkeepr.getConfig().getExternalUrl() + remotePath);

                httpclient = bookkeepr.checkoutHttpClient();
                HttpResponse httpresp = httpclient.execute(httppost);
                for (Header head : httpresp.getAllHeaders()) {
                    if (head.getName().equalsIgnoreCase("transfer-encoding")) {
                        continue;
                    }
                    response.setHeader(head.getName(), head.getValue());
                }
                response.setStatus(httpresp.getStatusLine().getStatusCode());

                httpresp.getEntity().writeTo(response.getOutputStream());

            } catch (HttpException ex) {
                Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING,
                        "HttpException " + ex.getMessage(), ex);
                response.sendError(500, ex.getMessage());

            } catch (URISyntaxException ex) {
                Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
                response.sendError(400, "Invalid target URI");
            } finally {
                if (httpclient != null) {
                    bookkeepr.returnHttpClient(httpclient);
                }
            }

        }
        return;
    }

    if (request.getMethod().equals("GET")) {
        if (path.startsWith("/web")) {
            ((Request) request).setHandled(true);

            if (badchar.matcher(path).matches()) {
                response.sendError(400, "User Error");
                return;
            }
            String localpath = path.substring(4);
            Logger.getLogger(WebHandler.class.getName()).log(Level.FINE,
                    "Transmitting " + localroot + localpath);
            File targetFile = new File(localroot + localpath);
            if (targetFile.isDirectory()) {
                if (path.endsWith("/")) {
                    targetFile = new File(localroot + localpath + "index.html");
                } else {
                    response.sendRedirect(path + "/");
                    return;
                }
            }
            if (targetFile.exists()) {
                if (targetFile.getName().endsWith(".html") || targetFile.getName().endsWith(".xsl")) {
                    BufferedReader in = new BufferedReader(new FileReader(targetFile));
                    PrintStream out = null;
                    String hdr = request.getHeader("Accept-Encoding");
                    if (hdr != null && hdr.contains("gzip")) {
                        // if the host supports gzip encoding, gzip the output for quick transfer speed.
                        out = new PrintStream(new GZIPOutputStream(response.getOutputStream()));
                        response.setHeader("Content-Encoding", "gzip");
                    } else {
                        out = new PrintStream(response.getOutputStream());
                    }
                    String line = in.readLine();
                    while (line != null) {
                        if (line.trim().startsWith("%%%")) {
                            BufferedReader wrapper = new BufferedReader(
                                    new FileReader(localroot + "/wrap/" + line.trim().substring(3) + ".html"));
                            String line2 = wrapper.readLine();
                            while (line2 != null) {
                                out.println(line2);
                                line2 = wrapper.readLine();
                            }
                            wrapper.close();
                        } else if (line.trim().startsWith("***chooser")) {
                            String[] elems = line.trim().split("\\s");
                            try {
                                int type = TypeIdManager
                                        .getTypeFromClass(Class.forName("bookkeepr.xmlable." + elems[1]));
                                List<IdAble> items = this.bookkeepr.getMasterDatabaseManager()
                                        .getAllOfType(type);
                                out.printf("<select name='%sId'>\n", elems[1]);
                                for (IdAble item : items) {
                                    out.printf("<option value='%x'>%s</option>", item.getId(), item.toString());
                                }
                                out.println("</select>");

                            } catch (Exception e) {
                                Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING,
                                        "Could not make a type ID for " + line.trim());
                            }
                        } else {

                            out.println(line);
                        }
                        line = in.readLine();
                    }
                    in.close();
                    out.close();
                } else {
                    outputToInput(new FileInputStream(targetFile), response.getOutputStream());
                }

            } else {
                response.sendError(HttpStatus.SC_NOT_FOUND);
            }
        }
    }
}

From source file:com.aliyun.android.oss.task.PutObjectTask.java

public void setUploadFile(File uploadFile) {
    this.uploadFile = uploadFile;
    if (entity == null) {
        InputStream inputStream = null;
        try {/*w w  w  .  ja v a2 s.c o m*/
            inputStream = new FileInputStream(uploadFile);
            entity = new InputStreamEntity(inputStream, uploadFile.length());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:org.datagator.api.client.backend.DataGatorService.java

public CloseableHttpResponse patch(String endpoint, InputStream data, ContentType ctype)
        throws URISyntaxException, IOException {
    HttpPatch request = new HttpPatch(buildServiceURI(endpoint));
    if (data != null) {
        HttpEntity entity = new InputStreamEntity(data, ctype);
        request.setEntity(entity);/*from   w w w  . j a va2 s  . c o m*/
    }
    return http.execute(request, context);
}

From source file:org.fashiontec.bodyapps.sync.SyncPic.java

/**
 * Multipart post for images.//from  www .j a  va  2 s .  com
 * @param url
 * @param path
 * @return
 */
public HttpResponse post(String url, String path) {
    HttpResponse response = null;
    try {
        File file = new File(path);
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        InputStreamEntity entity = new InputStreamEntity(new FileInputStream(file.getPath()), file.length());
        entity.setContentType("image/jpeg");
        entity.setChunked(true);
        post.setEntity(entity);

        response = client.execute(post);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}