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

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

Introduction

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

Prototype

public FileEntity(File file, ContentType contentType) 

Source Link

Usage

From source file:org.apache.http.contrib.benchmark.HttpBenchmark.java

private void prepare() {
    // prepare http params
    params = getHttpParams(socketTimeout, useHttp1_0);

    host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    // Prepare requests for each thread
    request = new HttpRequest[threads];

    if (postFile != null) {
        FileEntity entity = new FileEntity(postFile, contentType);
        contentLength = entity.getContentLength();
        if (postFile.length() > 100000) {
            entity.setChunked(true);//from  w w  w. java2  s.c o m
        }

        for (int i = 0; i < threads; i++) {
            BasicHttpEntityEnclosingRequest httppost = new BasicHttpEntityEnclosingRequest("POST",
                    url.getPath());
            httppost.setEntity(entity);
            request[i] = httppost;
        }

    } else if (doHeadInsteadOfGet) {
        for (int i = 0; i < threads; i++) {
            request[i] = new BasicHttpRequest("HEAD", url.getPath());
        }

    } else {
        for (int i = 0; i < threads; i++) {
            request[i] = new BasicHttpRequest("GET", url.getPath());
        }
    }

    if (!keepAlive) {
        for (int i = 0; i < threads; i++) {
            request[i].addHeader(new DefaultHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
        }
    }

    if (headers != null) {
        for (int i = 0; i < headers.length; i++) {
            String s = headers[i];
            int pos = s.indexOf(':');
            if (pos != -1) {
                Header header = new DefaultHeader(s.substring(0, pos).trim(), s.substring(pos + 1));
                for (int j = 0; j < threads; j++) {
                    request[j].addHeader(header);
                }
            }
        }
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

/**
 * /*from   w w  w.  j a v a2s. c  o  m*/
 * @param post {@link HttpPost}
 * @return String posted body if computable
 * @throws IOException if sending the data fails due to I/O
 */
protected String sendPostData(HttpPost post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();

    final String contentEncoding = getContentEncodingOrNull();
    final boolean haveContentEncoding = contentEncoding != null;

    // Check if we should do a multipart/form-data or an
    // application/x-www-form-urlencoded post request
    if (getUseMultipartForPost()) {
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        Charset charset = null;
        if (haveContentEncoding) {
            charset = Charset.forName(contentEncoding);
        } else {
            charset = MIME.DEFAULT_CHARSET;
        }

        if (log.isDebugEnabled()) {
            log.debug("Building multipart with:getDoBrowserCompatibleMultipart():"
                    + getDoBrowserCompatibleMultipart() + ", with charset:" + charset + ", haveContentEncoding:"
                    + haveContentEncoding);
        }
        // Write the request to our own stream
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset);
        if (getDoBrowserCompatibleMultipart()) {
            multipartEntityBuilder.setLaxMode();
        } else {
            multipartEntityBuilder.setStrictMode();
        }
        // Create the parts
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringBody stringBody = new StringBody(arg.getValue(), ContentType.create("text/plain", charset));
            FormBodyPart formPart = FormBodyPartBuilder.create(parameterName, stringBody).build();
            multipartEntityBuilder.addPart(formPart);
        }

        // Add any files
        // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
        ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
        for (int i = 0; i < files.length; i++) {
            HTTPFileArg file = files[i];

            File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            fileBodies[i] = new ViewableFileBody(reservedFile, file.getMimeType());
            multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]);
        }

        HttpEntity entity = multipartEntityBuilder.build();
        post.setEntity(entity);

        if (entity.isRepeatable()) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = true;
            }
            entity.writeTo(bos);
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = false;
            }
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                    : contentEncoding));
            bos.close();
        } else {
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
        }

        //            // Set the content type TODO - needed?
        //            String multiPartContentType = multiPart.getContentType().getValue();
        //            post.setHeader(HEADER_CONTENT_TYPE, multiPartContentType);

    } else { // not multipart
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = post.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
                && contentTypeHeader.getValue().length() > 0;
        // If there are no arguments, we can send a file as the body of the request
        // TODO: needs a multiple file upload scenerio
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }

            FileEntity fileRequestEntity = new FileEntity(new File(file.getPath()), (ContentType) null);// TODO is null correct?
            post.setEntity(fileRequestEntity);

            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // In a post request which is not multipart, we only support
            // parameters, no file upload is allowed

            // If a content encoding is specified, we set it as http parameter, so that
            // the post body will be encoded in the specified content encoding
            if (haveContentEncoding) {
                post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, contentEncoding);
            }

            // If none of the arguments have a name specified, we
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // Allow the mimetype of the file to control the content type
                // This is not obvious in GUI if you are not uploading any files,
                // but just sending the content of nameless parameters
                // TODO: needs a multiple file upload scenerio
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                                HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }

                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
                    if (haveContentEncoding) {
                        postBody.append(arg.getEncodedValue(contentEncoding));
                    } else {
                        postBody.append(arg.getEncodedValue());
                    }
                }
                // Let StringEntity perform the encoding
                StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
                post.setEntity(requestEntity);
                postedBody.append(postBody.toString());
            } else {
                // It is a normal post request, with parameter names and values

                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                PropertyIterator args = getArguments().iterator();
                List<NameValuePair> nvps = new ArrayList<>();
                String urlContentEncoding = contentEncoding;
                if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                    // Use the default encoding for urls
                    urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                }
                while (args.hasNext()) {
                    HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
                    // The HTTPClient always urlencodes both name and value,
                    // so if the argument is already encoded, we have to decode
                    // it before adding it to the post request
                    String parameterName = arg.getName();
                    if (arg.isSkippable(parameterName)) {
                        continue;
                    }
                    String parameterValue = arg.getValue();
                    if (!arg.isAlwaysEncoded()) {
                        // The value is already encoded by the user
                        // Must decode the value now, so that when the
                        // httpclient encodes it, we end up with the same value
                        // as the user had entered.
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    nvps.add(new BasicNameValuePair(parameterName, parameterValue));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, urlContentEncoding);
                post.setEntity(entity);
                if (entity.isRepeatable()) {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    post.getEntity().writeTo(bos);
                    bos.flush();
                    // We get the posted bytes using the encoding used to create it
                    if (contentEncoding != null) {
                        postedBody.append(new String(bos.toByteArray(), contentEncoding));
                    } else {
                        postedBody.append(new String(bos.toByteArray(), SampleResult.DEFAULT_HTTP_ENCODING));
                    }
                    bos.close();
                } else {
                    postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
                }
            }
        }
    }
    return postedBody.toString();
}

From source file:org.dasein.cloud.aws.storage.S3Method.java

S3Response invoke(@Nullable String bucket, @Nullable String object, @Nullable String temporaryEndpoint)
        throws S3Exception, CloudException, InternalException {
    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug("----------------------------------------------------------------------------------");
    }/*from  w w  w  .  j av a2 s . co m*/
    HttpClient client = null;
    boolean leaveOpen = false;
    try {
        StringBuilder url = new StringBuilder();
        HttpRequestBase method;
        int status;

        // Sanitise the parameters as they may have spaces and who knows what else
        if (bucket != null) {
            bucket = AWSCloud.encode(bucket, false);
        }
        if (object != null && !"?location".equalsIgnoreCase(object) && !"?acl".equalsIgnoreCase(object)
                && !"?tagging".equalsIgnoreCase(object)) {
            object = AWSCloud.encode(object, false);
        }
        if (temporaryEndpoint != null) {
            temporaryEndpoint = AWSCloud.encode(temporaryEndpoint, false);
        }
        if (provider.getEC2Provider().isAWS()) {
            url.append("https://");
            String regionId = provider.getContext().getRegionId();

            if (temporaryEndpoint == null) {
                boolean validDomainName = isValidDomainName(bucket);

                if (bucket != null && validDomainName) {
                    url.append(bucket);
                    if (regionId != null && !regionId.isEmpty() && !"us-east-1".equals(regionId)) {
                        url.append(".s3-");
                        url.append(regionId);
                        url.append(".amazonaws.com/");
                    } else {
                        url.append(".s3.amazonaws.com/");
                    }
                } else {
                    if (regionId != null && !regionId.isEmpty() && !"us-east-1".equals(regionId)) {
                        url.append("s3-");
                        url.append(regionId);
                        url.append(".amazonaws.com/");
                    } else {
                        url.append("s3.amazonaws.com/");
                    }
                }
                if (bucket != null && !validDomainName) {
                    url.append(bucket);
                    url.append("/");
                }
            } else {
                url.append(temporaryEndpoint);
                url.append("/");
            }
        } else if (provider.getEC2Provider().isStorage()
                && "google".equalsIgnoreCase(provider.getProviderName())) {
            url.append("https://");
            if (temporaryEndpoint == null) {
                if (bucket != null) {
                    url.append(bucket);
                    url.append(".");
                }
                url.append("commondatastorage.googleapis.com/");
            } else {
                url.append(temporaryEndpoint);
                url.append("/");
            }
        } else {
            int idx = 0;

            if (!provider.getContext().getEndpoint().startsWith("http")) {
                url.append("https://");
            } else {
                idx = provider.getContext().getEndpoint().indexOf("https://");
                if (idx == -1) {
                    idx = "http://".length();
                    url.append("http://");
                } else {
                    idx = "https://".length();
                    url.append("https://");
                }
            }
            String service = "";
            if (provider.getEC2Provider().isEucalyptus()) {
                service = "Walrus/";
            }

            if (temporaryEndpoint == null) {
                url.append(provider.getContext().getEndpoint().substring(idx));
                if (!provider.getContext().getEndpoint().endsWith("/")) {
                    url.append("/").append(service);
                } else {
                    url.append(service);
                }
            } else {
                url.append(temporaryEndpoint);
                url.append("/");
                url.append(service);
            }
            if (bucket != null) {
                url.append(bucket);
                url.append("/");
            }
        }
        if (object != null) {
            url.append(object);
        } else if (parameters != null) {
            boolean first = true;

            if (object != null && object.indexOf('?') != -1) {
                first = false;
            }
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                String key = entry.getKey();
                String val = entry.getValue();

                if (first) {
                    url.append("?");
                    first = false;
                } else {
                    url.append("&");
                }
                if (val != null) {
                    url.append(AWSCloud.encode(key, false));
                    url.append("=");
                    url.append(AWSCloud.encode(val, false));
                } else {
                    url.append(AWSCloud.encode(key, false));
                }
            }
        }

        if (provider.getEC2Provider().isStorage() && provider.getProviderName().equalsIgnoreCase("Google")) {
            headers.put(AWSCloud.P_GOOG_DATE, getDate());
        } else {
            headers.put(AWSCloud.P_AWS_DATE, provider.getV4HeaderDate(null));
        }
        if (contentType == null && body != null) {
            contentType = "application/xml";
            headers.put("Content-Type", contentType);
        } else if (contentType != null) {
            headers.put("Content-Type", contentType);
        }

        method = action.getMethod(url.toString());
        String host = method.getURI().getHost();
        headers.put("host", host);

        if (action.equals(S3Action.PUT_BUCKET_TAG))
            try {
                headers.put("Content-MD5", toBase64(computeMD5Hash(body)));
            } catch (NoSuchAlgorithmException e) {
                logger.error(e);
            } catch (IOException e) {
                logger.error(e);
            }

        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                method.addHeader(entry.getKey(), entry.getValue());
            }
        }

        if (body != null) {
            ((HttpEntityEnclosingRequestBase) method).setEntity(new StringEntity(body, APPLICATION_XML));
        } else if (uploadFile != null) {
            ((HttpEntityEnclosingRequestBase) method).setEntity(new FileEntity(uploadFile, contentType));
        }
        try {
            String hash = null;
            if (method instanceof HttpEntityEnclosingRequestBase) {
                try {
                    hash = provider.getRequestBodyHash(
                            EntityUtils.toString(((HttpEntityEnclosingRequestBase) method).getEntity()));
                } catch (IOException e) {
                    throw new InternalException(e);
                }
            } else {
                hash = provider.getRequestBodyHash("");
            }

            String signature;
            if (provider.getEC2Provider().isAWS()) {
                // Sign v4 for AWS
                signature = provider.getV4Authorization(new String(provider.getAccessKey()[0]),
                        new String(provider.getAccessKey()[1]), method.getMethod(), url.toString(), SERVICE_ID,
                        headers, hash);
                if (hash != null) {
                    method.addHeader(AWSCloud.P_AWS_CONTENT_SHA256, hash);
                }
            } else {
                // Eucalyptus et al use v2
                signature = provider.signS3(new String(provider.getAccessKey()[0], "utf-8"),
                        provider.getAccessKey()[1], method.getMethod(), null, contentType, headers, bucket,
                        object);
            }
            method.addHeader(AWSCloud.P_CFAUTH, signature);
        } catch (UnsupportedEncodingException e) {
            logger.error(e);
        }

        if (wire.isDebugEnabled()) {
            wire.debug("[" + url.toString() + "]");
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                try {
                    wire.debug(EntityUtils.toString(((HttpEntityEnclosingRequestBase) method).getEntity()));
                } catch (IOException ignore) {
                }

                wire.debug("");
            } else if (uploadFile != null) {
                wire.debug("-- file upload --");
                wire.debug("");
            }
        }

        attempts++;
        client = provider.getClient(body == null && uploadFile == null);

        S3Response response = new S3Response();
        HttpResponse httpResponse;

        try {
            APITrace.trace(provider, action.toString());
            httpResponse = client.execute(method);
            if (wire.isDebugEnabled()) {
                wire.debug(httpResponse.getStatusLine().toString());
                for (Header header : httpResponse.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
            status = httpResponse.getStatusLine().getStatusCode();
        } catch (IOException e) {
            logger.error(url + ": " + e.getMessage());
            throw new InternalException(e);
        }
        response.headers = httpResponse.getAllHeaders();

        HttpEntity entity = httpResponse.getEntity();
        InputStream input = null;

        if (entity != null) {
            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
        }
        try {
            if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED
                    || status == HttpStatus.SC_ACCEPTED) {
                Header clen = httpResponse.getFirstHeader("Content-Length");
                long len = -1L;

                if (clen != null) {
                    len = Long.parseLong(clen.getValue());
                }
                if (len != 0L) {
                    try {
                        Header ct = httpResponse.getFirstHeader("Content-Type");

                        if ((ct != null && (ct.getValue().startsWith("application/xml")
                                || ct.getValue().startsWith("text/xml")))
                                || (action.equals(S3Action.GET_BUCKET_TAG) && input != null)) {
                            try {
                                response.document = parseResponse(input);
                                return response;
                            } finally {
                                input.close();
                            }
                        } else if (ct != null && ct.getValue().startsWith("application/octet-stream")
                                && len < 1) {
                            return null;
                        } else {
                            response.contentLength = len;
                            if (ct != null) {
                                response.contentType = ct.getValue();
                            }
                            response.input = input;
                            response.method = method;
                            leaveOpen = true;
                            return response;
                        }
                    } catch (IOException e) {
                        logger.error(e);
                        throw new CloudException(e);
                    }
                } else {
                    return response;
                }
            } else if (status == HttpStatus.SC_NO_CONTENT) {
                return response;
            }
            if (status == HttpStatus.SC_FORBIDDEN) {
                throw new S3Exception(status, "", "AccessForbidden",
                        "Access was denied : " + (url != null ? url.toString() : ""));
            } else if (status == HttpStatus.SC_NOT_FOUND) {
                throw new S3Exception(status, null, null, "Object not found.");
            } else {
                if (status == HttpStatus.SC_SERVICE_UNAVAILABLE
                        || status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                    if (attempts >= 5) {
                        String msg;

                        if (status == HttpStatus.SC_SERVICE_UNAVAILABLE) {
                            msg = "Cloud service is currently unavailable.";
                        } else {
                            msg = "The cloud service encountered a server error while processing your request.";
                        }
                        logger.error(msg);
                        throw new CloudException(msg);
                    } else {
                        leaveOpen = true;
                        if (input != null) {
                            try {
                                input.close();
                            } catch (IOException ignore) {
                            }
                        }
                        try {
                            Thread.sleep(5000L);
                        } catch (InterruptedException ignore) {
                        }
                        return invoke(bucket, object);
                    }
                }
                try {
                    Document doc;

                    try {
                        logger.warn("Received error code: " + status);
                        doc = parseResponse(input);
                    } finally {
                        if (input != null) {
                            input.close();
                        }
                    }
                    if (doc != null) {
                        String endpoint = null, code = null, message = null, requestId = null;
                        NodeList blocks = doc.getElementsByTagName("Error");

                        if (blocks.getLength() > 0) {
                            Node error = blocks.item(0);
                            NodeList attrs;

                            attrs = error.getChildNodes();
                            for (int i = 0; i < attrs.getLength(); i++) {
                                Node attr = attrs.item(i);

                                if (attr.getNodeName().equals("Code") && attr.hasChildNodes()) {
                                    code = attr.getFirstChild().getNodeValue().trim();
                                } else if (attr.getNodeName().equals("Message") && attr.hasChildNodes()) {
                                    message = attr.getFirstChild().getNodeValue().trim();
                                } else if (attr.getNodeName().equals("RequestId") && attr.hasChildNodes()) {
                                    requestId = attr.getFirstChild().getNodeValue().trim();
                                } else if (attr.getNodeName().equals("Endpoint") && attr.hasChildNodes()) {
                                    endpoint = attr.getFirstChild().getNodeValue().trim();
                                }
                            }

                        }
                        if (endpoint != null && code.equals("TemporaryRedirect")) {
                            if (temporaryEndpoint != null) {
                                throw new CloudException("Too deep redirect to " + endpoint);
                            } else {
                                return invoke(bucket, object, endpoint);
                            }
                        } else {
                            if (message == null) {
                                throw new CloudException("Unable to identify error condition: " + status + "/"
                                        + requestId + "/" + code);
                            }
                            throw new S3Exception(status, requestId, code, message);
                        }
                    } else {
                        throw new CloudException("Unable to parse error.");
                    }
                } catch (IOException e) {
                    if (status == HttpStatus.SC_FORBIDDEN) {
                        throw new S3Exception(status, "", "AccessForbidden",
                                "Access was denied without explanation.");
                    }
                    throw new CloudException(e);
                } catch (RuntimeException e) {
                    throw new CloudException(e);
                } catch (Error e) {
                    throw new CloudException(e);
                }
            }
        } finally {
            if (!leaveOpen) {
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
    } finally {
        if (!leaveOpen && client != null) {
            client.getConnectionManager().shutdown();
        }
        if (wire.isDebugEnabled()) {
            wire.debug("----------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

public void putWithFile(@Nonnull String strMethod, @Nonnull String resource, Map<String, String> queries,
        File file, Map<String, String> headerMap, boolean authorization)
        throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "("
                + getStorageAccount() + "," + resource + ")");
    }/*from   w  ww .ja v  a 2s  . c  o m*/
    String endpoint = getStorageEnpoint();

    if (wire.isDebugEnabled()) {
        wire.debug(strMethod + "--------------------------------------------------------> " + endpoint
                + getStorageAccount() + resource);
        wire.debug("");
    }

    long begin = System.currentTimeMillis();
    try {

        HttpClient client = getClient();

        String contentLength = null;

        if (file != null) {
            contentLength = String.valueOf(file.length());
        } else {
            contentLength = "0";
        }

        HttpRequestBase method = getMethod(strMethod, buildUrl(resource, queries), queries, headerMap,
                authorization);

        if (wire.isDebugEnabled()) {
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (file != null) {
                wire.debug(file);
                wire.debug("");
            }
        }

        // If it is post or put
        if (method instanceof HttpEntityEnclosingRequestBase) {

            HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) method;

            if (file != null) {
                entityEnclosingMethod.setEntity(new FileEntity(file, ContentType.APPLICATION_OCTET_STREAM));
            }
        }

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (logger.isTraceEnabled()) {
                e.printStackTrace();
            }

            long end = System.currentTimeMillis();
            logger.debug("Totoal time -> " + (end - begin));
            throw new CloudException(e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("post(): HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }

        if ((status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED
                && status.getStatusCode() != HttpServletResponse.SC_OK)
                && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) {
            logger.error(
                    strMethod + "(): Expected OK for " + strMethod + "request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();
            String result;

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                result = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(result);
            }
            wire.debug("");
            AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result);
            logger.error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] "
                    + items.details);
            throw new AzureException(items);
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> ");
        }
    }
}

From source file:org.envirocar.app.dao.remote.BaseRemoteDAO.java

protected HttpResponse executePayloadRequest(HttpEntityEnclosingRequestBase request, FileWithMetadata content)
        throws NotConnectedException, UnauthorizedException, ResourceConflictException {
    FileEntity entity = new FileEntity(content.getFile(), "application/json");

    if (content.isGzipped()) {
        entity.setContentEncoding("gzip");
    }/* ww w.  j a  v  a  2  s . c  o  m*/

    request.setEntity(entity);

    return executePayloadRequest(request);
}

From source file:org.exoplatform.utils.ExoDocumentUtils.java

public static boolean putFileToServerFromLocal(String url, File fileManager, String fileType) {
    try {//from ww w.  j  a v a 2 s.co m
        url = url.replaceAll(" ", "%20");

        HttpPut put = new HttpPut(url);
        FileEntity fileEntity = new FileEntity(fileManager, fileType);
        put.setEntity(fileEntity);
        fileEntity.setContentType(fileType);
        HttpResponse response = ExoConnectionUtils.httpClient.execute(put);
        int status = response.getStatusLine().getStatusCode();
        if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
            return true;
        } else {
            return false;
        }
    } catch (IOException e) {
        if (Log.LOGD)
            Log.d(ExoDocumentUtils.class.getSimpleName(), e.getMessage(), Log.getStackTraceString(e));
        return false;
    } finally {
        fileManager.delete();
    }

}

From source file:org.jdesktop.wonderland.modules.officeconverter.client.OfficeContentImporter.java

private File convertFile(File inputFile) throws IOException {
    try {// www. j a va  2  s  . c o  m
        HttpClient httpClient = new DefaultHttpClient();
        String serverURL = loginInfo.getServerURL();
        HttpPost post = new HttpPost(serverURL + "/office-converter/converter/service");
        //LOGGER.warning("URI: " + post.getURI());
        post.addHeader("Accept", "application/pdf");

        String extension = FilenameUtils.getExtension(inputFile.getName());
        //LOGGER.warning("Extension: " + extension);
        DocumentFormat format = new DefaultDocumentFormatRegistry().getFormatByFileExtension(extension);
        //LOGGER.warning("Format: " + format.getMimeType());

        HttpEntity postEntity = new FileEntity(inputFile, format.getMimeType());
        post.setEntity(postEntity);

        HttpResponse response = httpClient.execute(post);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            LOGGER.warning("Status Code: " + statusLine.getStatusCode());
            LOGGER.warning("Status: " + statusLine.getReasonPhrase());
            throw new IOException(statusLine.getReasonPhrase());
        }

        File outputFile = new File(inputFile.getName() + ".pdf");
        outputFile.deleteOnExit();
        LOGGER.warning("Output filename: " + outputFile.getName());
        FileOutputStream outputStream = new FileOutputStream(outputFile);

        HttpEntity responseEntity = response.getEntity();
        responseEntity.writeTo(outputStream);
        outputStream.close();
        return outputFile;
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "failed to convert file", e);
        throw new IOException("Failed to convert file", e);
    }
}

From source file:org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient.java

private ArtifactoryUploadResponse uploadFile(DeployDetails details, String uploadUrl) throws IOException {
    ArtifactoryUploadResponse response = tryChecksumDeploy(details, uploadUrl);
    if (response != null) {
        // Checksum deploy was performed:
        return response;
    }/*  w ww  .  j  av a 2 s .  c om*/

    HttpPut httpPut = createHttpPutMethod(details, uploadUrl);
    // add the 100 continue directive
    httpPut.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);

    FileEntity fileEntity = new FileEntity(details.getFile(), "binary/octet-stream");

    response = httpClient.upload(httpPut, fileEntity);
    int statusCode = response.getStatusLine().getStatusCode();

    //Accept both 200, and 201 for backwards-compatibility reasons
    if ((statusCode != HttpStatus.SC_CREATED) && (statusCode != HttpStatus.SC_OK)) {
        throw new IOException("Failed to deploy file. Status code: " + statusCode + getMessage(response));
    }

    return response;
}

From source file:org.rhq.maven.plugins.UploadMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skipUpload) {
        getLog().info("Skipped execution");
        return;/*from ww w.  j a  v a 2s .c o m*/
    }
    File agentPluginArchive = getAgentPluginArchiveFile(buildDirectory, finalName);
    if (!agentPluginArchive.exists() && agentPluginArchive.isFile()) {
        throw new MojoExecutionException("Agent plugin archive does not exist: " + agentPluginArchive);
    }

    // Prepare HttpClient
    ClientConnectionManager httpConnectionManager = new BasicClientConnectionManager();
    DefaultHttpClient httpClient = new DefaultHttpClient(httpConnectionManager);
    HttpParams httpParams = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, socketConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, socketReadTimeout);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port),
            new UsernamePasswordCredentials(username, password));

    HttpPost uploadContentRequest = null;
    HttpPut moveContentToPluginsDirRequest = null;
    HttpPost pluginScanRequest = null;
    HttpPost pluginDeployRequest = null;
    HttpGet pluginDeployCheckCompleteRequest = null;
    try {

        // Upload plugin content
        URI uploadContentUri = buildUploadContentUri();
        uploadContentRequest = new HttpPost(uploadContentUri);
        uploadContentRequest.setEntity(new FileEntity(agentPluginArchive, APPLICATION_OCTET_STREAM));
        uploadContentRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
        HttpResponse uploadContentResponse = httpClient.execute(uploadContentRequest);

        if (uploadContentResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            handleProblem(uploadContentResponse.getStatusLine().toString());
            return;
        }

        getLog().info("Uploaded " + agentPluginArchive);
        // Read the content handle value in JSON response
        JSONObject uploadContentResponseJsonObject = new JSONObject(
                EntityUtils.toString(uploadContentResponse.getEntity()));
        String contentHandle = (String) uploadContentResponseJsonObject.get("value");
        uploadContentRequest.abort();

        if (!startScan && !updatePluginsOnAllAgents) {

            // Request uploaded content to be moved to the plugins directory but do not trigger a plugin scan
            URI moveContentToPluginsDirUri = buildMoveContentToPluginsDirUri(contentHandle);
            moveContentToPluginsDirRequest = new HttpPut(moveContentToPluginsDirUri);
            moveContentToPluginsDirRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
            HttpResponse moveContentToPluginsDirResponse = httpClient.execute(moveContentToPluginsDirRequest);

            if (moveContentToPluginsDirResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                handleProblem(moveContentToPluginsDirResponse.getStatusLine().toString());
                return;
            }

            moveContentToPluginsDirRequest.abort();
            getLog().info("Moved uploaded content to plugins directory");
            return;
        }

        // Request uploaded content to be moved to the plugins directory and trigger a plugin scan
        URI pluginScanUri = buildPluginScanUri(contentHandle);
        pluginScanRequest = new HttpPost(pluginScanUri);
        pluginScanRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
        getLog().info("Moving uploaded content to plugins directory and requesting a plugin scan");
        HttpResponse pluginScanResponse = httpClient.execute(pluginScanRequest);

        if (pluginScanResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED //
                && pluginScanResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            handleProblem(pluginScanResponse.getStatusLine().toString());
            return;
        }

        pluginScanRequest.abort();
        getLog().info("Plugin scan complete");

        if (updatePluginsOnAllAgents) {

            URI pluginDeployUri = buildPluginDeployUri();
            pluginDeployRequest = new HttpPost(pluginDeployUri);
            pluginDeployRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
            getLog().info("Requesting agents to update their plugins");
            HttpResponse pluginDeployResponse = httpClient.execute(pluginDeployRequest);

            if (pluginDeployResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                handleProblem(pluginDeployResponse.getStatusLine().toString());
                return;
            }

            getLog().info("Plugins update requests sent");
            // Read the agent plugins update handle value in JSON response
            JSONObject pluginDeployResponseJsonObject = new JSONObject(
                    EntityUtils.toString(pluginDeployResponse.getEntity()));
            String pluginsUpdateHandle = (String) pluginDeployResponseJsonObject.get("value");
            pluginDeployRequest.abort();

            if (waitForPluginsUpdateOnAllAgents) {

                getLog().info("Waiting for plugins update requests to complete");

                long start = System.currentTimeMillis();
                for (;;) {

                    URI pluginDeployCheckCompleteUri = buildPluginDeployCheckCompleteUri(pluginsUpdateHandle);
                    pluginDeployCheckCompleteRequest = new HttpGet(pluginDeployCheckCompleteUri);
                    pluginDeployCheckCompleteRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
                    HttpResponse pluginDeployCheckCompleteResponse = httpClient
                            .execute(pluginDeployCheckCompleteRequest);

                    if (pluginDeployCheckCompleteResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                        handleProblem(pluginDeployCheckCompleteResponse.getStatusLine().toString());
                        return;
                    }

                    // Read the agent plugins update handle value in JSON response
                    JSONObject pluginDeployCheckCompleteResponseJsonObject = new JSONObject(
                            EntityUtils.toString(pluginDeployCheckCompleteResponse.getEntity()));
                    Boolean pluginDeployCheckCompleteHandle = (Boolean) pluginDeployCheckCompleteResponseJsonObject
                            .get("value");
                    pluginDeployCheckCompleteRequest.abort();

                    if (pluginDeployCheckCompleteHandle == TRUE) {
                        getLog().info("All agents updated their plugins");
                        return;
                    }

                    if (SECONDS.toMillis(
                            maxWaitForPluginsUpdateOnAllAgents) < (System.currentTimeMillis() - start)) {
                        handleProblem("Not all agents updated their plugins but wait limit has been reached ("
                                + maxWaitForPluginsUpdateOnAllAgents + " ms)");
                        return;
                    }

                    Thread.sleep(SECONDS.toMillis(5));
                    getLog().info("Checking plugins update requests status again");
                }
            }
        }
    } catch (IOException e) {
        handleException(e);
    } catch (JSONException e) {
        handleException(e);
    } catch (URISyntaxException e) {
        handleException(e);
    } catch (InterruptedException e) {
        handleException(e);
    } finally {
        abortQuietly(uploadContentRequest);
        abortQuietly(moveContentToPluginsDirRequest);
        abortQuietly(pluginScanRequest);
        abortQuietly(pluginDeployRequest);
        abortQuietly(pluginDeployCheckCompleteRequest);
        httpConnectionManager.shutdown();
    }
}

From source file:ste.web.http.handlers.FileHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

    checkHttpMethod(request);//w ww  .  j a  v a2s .  c  o  m

    String target = request.getRequestLine().getUri();

    for (String exclude : excludePatterns) {
        if (target.matches(exclude)) {
            notFound(target, response);

            return;
        }
    }
    if (StringUtils.isNotBlank(webContext) && target.startsWith(webContext)) {
        target = target.substring(webContext.length());
    }

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
    }

    URI uri = null;
    try {
        uri = new URI(target);
    } catch (URISyntaxException x) {
        throw new HttpException("malformed URL '" + target + "'");
    }
    final File file = new File(this.docRoot, uri.getPath());
    if (!file.exists()) {
        notFound(target, response);
    } else if (!file.canRead() || file.isDirectory()) {
        response.setStatusCode(HttpStatus.SC_FORBIDDEN);
        StringEntity entity = new StringEntity("<html><body><h1>Access denied</h1></body></html>",
                ContentType.TEXT_HTML);
        response.setEntity(entity);
    } else {
        response.setStatusCode(HttpStatus.SC_OK);

        String mimeType = MimeUtils.getInstance().getMimeType(file);
        ContentType type = MimeUtils.MIME_UNKNOWN.equals(mimeType) ? ContentType.APPLICATION_OCTET_STREAM
                : ContentType.create(mimeType);
        FileEntity body = new FileEntity(file, type);
        response.setEntity(body);
    }
}