Search in sources :

Example 11 with ByteArrayBody

use of org.apache.http.entity.mime.content.ByteArrayBody in project scheduling by ow2-proactive.

the class LoginWithCredentialsCommand method login.

@Override
protected String login(ApplicationContext currentContext) throws CLIException {
    File credentials = new File(pathname);
    if (!credentials.exists()) {
        throw new CLIException(REASON_INVALID_ARGUMENTS, String.format("File does not exist: %s", credentials.getAbsolutePath()));
    }
    if (warn) {
        writeLine(currentContext, "Using the default credentials file: %s", credentials.getAbsolutePath());
    }
    HttpPost request = new HttpPost(currentContext.getResourceUrl("login"));
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("credential", new ByteArrayBody(FileUtility.byteArray(credentials), APPLICATION_OCTET_STREAM.getMimeType()));
    request.setEntity(entity);
    HttpResponseWrapper response = execute(request, currentContext);
    if (statusCode(OK) == statusCode(response)) {
        return StringUtility.responseAsString(response).trim();
    } else {
        handleError("An error occurred while logging: ", response, currentContext);
        throw new CLIException(REASON_OTHER, "An error occurred while logging.");
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpResponseWrapper(org.ow2.proactive_grid_cloud_portal.cli.utils.HttpResponseWrapper) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) ByteArrayBody(org.apache.http.entity.mime.content.ByteArrayBody) CLIException(org.ow2.proactive_grid_cloud_portal.cli.CLIException) File(java.io.File)

Example 12 with ByteArrayBody

use of org.apache.http.entity.mime.content.ByteArrayBody in project selenium_java by sergueik.

the class RestClient method request.

private JSON request(HttpEntityEnclosingRequestBase req, Issue.NewAttachment... attachments) throws RestException, IOException {
    if (attachments != null) {
        req.setHeader("X-Atlassian-Token", "nocheck");
        MultipartEntity ent = new MultipartEntity();
        for (Issue.NewAttachment attachment : attachments) {
            String filename = attachment.getFilename();
            Object content = attachment.getContent();
            if (content instanceof byte[]) {
                ent.addPart("file", new ByteArrayBody((byte[]) content, filename));
            } else if (content instanceof InputStream) {
                ent.addPart("file", new InputStreamBody((InputStream) content, filename));
            } else if (content instanceof File) {
                ent.addPart("file", new FileBody((File) content, filename));
            } else if (content == null) {
                throw new IllegalArgumentException("Missing content for the file " + filename);
            } else {
                throw new IllegalArgumentException("Expected file type byte[], java.io.InputStream or java.io.File but provided " + content.getClass().getName() + " for the file " + filename);
            }
        }
        req.setEntity(ent);
    }
    return request(req);
}
Also used : FileBody(org.apache.http.entity.mime.content.FileBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) InputStream(java.io.InputStream) ByteArrayBody(org.apache.http.entity.mime.content.ByteArrayBody) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) JSONObject(net.sf.json.JSONObject) File(java.io.File)

Example 13 with ByteArrayBody

use of org.apache.http.entity.mime.content.ByteArrayBody in project new-cloud by xie-summer.

the class HttpUtils method uploadFile.

/**
 * @param url
 * @param params
 * @param uploadMap
 * @param fileNameMap
 * @param encode
 * @return
 */
public static HttpResult uploadFile(String url, Map<String, String> params, Map<String, byte[]> uploadMap, Map<String, String> fileNameMap, String encode, int timeout) {
    /**
     * DefaultHttpClient client = new DefaultHttpClient();
     * client.getParams().setIntParameter("http.socket.timeout",
     * LONG_TIMEOUT); client.getParams().setBooleanParameter(
     * "http.protocol.expect-continue", false);
     * client.getParams().setIntParameter("http.connection.timeout",
     * CONNECTION_TIMEOUT);
     */
    CookieStore cookieStore = getCookieStore(null);
    CloseableHttpClient client = getHttpClient(CONNECTION_TIMEOUT, timeout, cookieStore);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(Charset.forName(encode));
    HttpPost request = new HttpPost(url);
    // MultipartEntity reqEntity = new MultipartEntity();
    for (String input : uploadMap.keySet()) {
        ByteArrayBody isb = new ByteArrayBody(uploadMap.get(input), fileNameMap.get(input));
        multipartEntityBuilder.addPart(input, isb);
    }
    try {
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                multipartEntityBuilder.addTextBody(key, params.get(key), ContentType.create("text/plain", Charset.forName(encode)));
            }
        }
        request.setEntity(multipartEntityBuilder.build());
        List<Cookie> reqcookie = cookieStore.getCookies();
        CloseableHttpResponse response = client.execute(request);
        try {
            String result = "";
            HttpEntity entity = getEntity(response);
            if (entity != null) {
                result = EntityUtils.toString(entity, encode);
            }
            if (isSuccess(response)) {
                HttpResult ret = HttpResult.getSuccessReturn(result);
                addHeader(ret, response);
                List<Cookie> cookies = cookieStore.getCookies();
                addCookie(ret, cookies, reqcookie);
                return ret;
            } else {
                int statusCode = response.getStatusLine().getStatusCode();
                String msg = "httpStatus:" + statusCode + response.getStatusLine().getReasonPhrase() + ", Header: ";
                Header[] headers = response.getAllHeaders();
                for (Header header : headers) {
                    msg += header.getName() + ":" + header.getValue();
                }
                request.abort();
                DB_LOGGER.error("ERROR HttpUtils:" + msg + request.getURI());
                return HttpResult.getFailure("httpStatus:" + response.getStatusLine().getStatusCode(), statusCode, result);
            }
        } finally {
            response.close();
        }
    } catch (HttpHostConnectException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_HTTP_HOST_CONNECT_EXCEPTION);
    } catch (ConnectTimeoutException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_CONNECT_TIMEOUT_EXCEPTION);
    } catch (SocketTimeoutException e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_SOCKET_TIMEOUT_EXCEPTION);
    } catch (Exception e) {
        request.abort();
        DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 100));
        return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), EXCEPTION_HTTP_STATUSCODE);
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ByteArrayBody(org.apache.http.entity.mime.content.ByteArrayBody) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) SocketTimeoutException(java.net.SocketTimeoutException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Aggregations

ByteArrayBody (org.apache.http.entity.mime.content.ByteArrayBody)13 HttpPost (org.apache.http.client.methods.HttpPost)11 HttpEntity (org.apache.http.HttpEntity)6 MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)5 StringBody (org.apache.http.entity.mime.content.StringBody)4 Test (org.junit.Test)4 HttpResponse (org.apache.http.HttpResponse)3 MultipartEntity (org.apache.http.entity.mime.MultipartEntity)3 TypeToken (com.google.gson.reflect.TypeToken)2 File (java.io.File)2 IOException (java.io.IOException)2 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)2 FileBody (org.apache.http.entity.mime.content.FileBody)2 ModelPublishException (org.eclipse.vorto.repository.api.upload.ModelPublishException)2 CabinetException (cz.metacentrum.perun.cabinet.bl.CabinetException)1 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)1 SecurityConstraint (io.undertow.servlet.api.SecurityConstraint)1 TestHttpClient (io.undertow.testutils.TestHttpClient)1