Example usage for org.apache.http.message BasicHeader BasicHeader

List of usage examples for org.apache.http.message BasicHeader BasicHeader

Introduction

In this page you can find the example usage for org.apache.http.message BasicHeader BasicHeader.

Prototype

public BasicHeader(String str, String str2) 

Source Link

Usage

From source file:co.forsaken.api.json.JsonWebCall.java

public String executeRet(Object arg) {
    if (_log)/*from ww  w  .j  a v a2s . c om*/
        System.out.println("Requested: [" + _url + "]");
    try {
        canConnect();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
    HttpClient httpClient = new DefaultHttpClient(_connectionManager);
    InputStream in = null;
    String res = null;
    try {
        Gson gson = new Gson();
        HttpPost request = new HttpPost(_url);
        if (arg != null) {
            StringEntity params = new StringEntity(gson.toJson(arg));
            params.setContentType(new BasicHeader("Content-Type", "application/json"));
            request.setEntity(params);
        }
        HttpResponse response = httpClient.execute(request);
        if (response != null) {
            in = response.getEntity().getContent();
            res = convertStreamToString(in);
        }
    } catch (Exception ex) {
        System.out.println("JSONWebCall.execute() Error: \n" + ex.getMessage());
        System.out.println("Result: \n" + res);
        StackTraceElement[] arrOfSTE;
        int max = (arrOfSTE = ex.getStackTrace()).length;
        for (int i = 0; i < max; i++) {
            StackTraceElement trace = arrOfSTE[i];
            System.out.println(trace);
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    if (_log)
        System.out.println("Returned: [" + _url + "] [" + res + "]");
    return res;
}

From source file:io.pivotal.strepsirrhini.chaoslemur.infrastructure.StandardDirectorUtils.java

private static RestTemplate createRestTemplate(String host, String username, String password,
        Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {

    String directorUaaBearerToken = getBoshDirectorUaaToken(host, username, password);

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
            .build();/*from  w  ww . j  a v  a2  s .  c om*/

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    Header auth = new BasicHeader("Authorization", String.format("Bearer %s", directorUaaBearerToken));
    Header accept = new BasicHeader("Accept", "*/*");
    List<Header> headers = new ArrayList<Header>();
    headers.add(auth);
    headers.add(accept);

    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().setDefaultHeaders(headers)
            .setSSLSocketFactory(connectionFactory).build();

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);

    return restTemplate;
}

From source file:org.soyatec.windowsazure.blob.internal.BlobConstraints.java

public IBlobConstraints isDestinationModifiedSince(Timestamp time) {
    constraints.add(new BasicHeader(HeaderNames.IfModifiedSince, formatTime(time)));
    return this;
}

From source file:org.vietspider.content.export.CSVExportDataDialog.java

public void export(String domainId, File file, String[] dataHeaders) {
    String plugin = "cvs.export.data.plugin";
    if (stop)/*from   w  w w .  java  2  s .co  m*/
        return;
    ClientConnector2 connector = ClientConnector2.currentInstance();
    HttpData httpData = null;
    try {
        PluginClientHandler handler = new PluginClientHandler();
        String pageValue = handler.send(plugin, "compute.export", domainId);
        int totalPage = -1;
        try {
            totalPage = Integer.parseInt(pageValue);
        } catch (Exception e) {
            return;
        }

        if (totalPage < 1)
            return;
        int page = 1;

        StringBuilder buildHeader = new StringBuilder();
        for (int i = 0; i < dataHeaders.length; i++) {
            if (buildHeader.length() > 0)
                buildHeader.append(',');
            buildHeader.append(dataHeaders[i]);
        }
        if (!file.exists() || file.length() < 1) {
            RWData.getInstance().save(file, buildHeader.toString().getBytes(Application.CHARSET));
        }

        CSVModel model = new CSVModel();
        model.setDomainId(domainId);
        model.setHeaders(dataHeaders);

        File licenseFile = LicenseVerifier.loadLicenseFile();
        boolean license = LicenseVerifier.verify("export", licenseFile);
        if (!license && totalPage > 10)
            totalPage = 10;

        while (page <= totalPage) {
            Header[] headers = new Header[] { new BasicHeader("action", "export"),
                    new BasicHeader("plugin.name", plugin)
                    //                new BasicHeader("page", String.valueOf(page))
            };
            model.setPage(page);
            String xml = Object2XML.getInstance().toXMLDocument(model).getTextValue();
            byte[] bytes = xml.getBytes(Application.CHARSET);

            httpData = connector.loadResponse(URLPath.DATA_PLUGIN_HANDLER, bytes, headers);
            InputStream inputStream = httpData.getStream();

            try {
                if (file.length() > 0)
                    RWData.getInstance().append(file, "\n".getBytes());
                RWData.getInstance().save(file, inputStream, true);
                inputStream.close();
            } finally {
                connector.release(httpData);
                inputStream.close();
            }
            page++;
        }
    } catch (Exception e) {
        ClientLog.getInstance().setException(null, e);
    } finally {
        connector.release(httpData);
    }
}

From source file:org.androidannotations.rest.spring.test.RequestTestBuilder.java

private void prepareFakeResponse() {
    Set<String> cookiesNames = responseCookies.keySet();
    Header[] headers = new Header[1 + responseCookies.size()];
    headers[0] = new BasicHeader("content-type", "application/json");

    int i = 1;// w w  w .  j a v  a2  s  .c o m
    for (String cookieName : cookiesNames) {
        headers[i++] = new BasicHeader("Set-Cookie", cookieName + "=" + responseCookies.get(cookieName));
    }

    String responseBody = responseContent != null ? responseContent.replaceAll("'", "\"") : "";

    Robolectric.addPendingHttpResponse(HttpStatus.OK.value(), responseBody, headers);
}

From source file:org.envirocar.app.network.RestClient.java

private static void put(String url, AsyncHttpResponseHandler handler, String contents, String user,
        String token) throws UnsupportedEncodingException {
    client.addHeader("Content-Type", "application/json");
    setHeaders(user, token);/*w  ww  . ja v  a 2s .  c o m*/

    StringEntity se = new StringEntity(contents);
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

    client.put(null, url, se, "application/json", handler);
}

From source file:net.oneandone.shared.artifactory.DownloadResponseHandlerTest.java

/**
 * Test of checkHeaderNotNull method, of class DownloadResponseHandler.
 *//*from  w ww. j  a v  a  2  s  .  c  om*/
@Test
public void testCheckHeaderNotNull() {
    final String headerName = "DOES_NOT_MATTER";
    when(mockedResponse.getFirstHeader(headerName)).thenReturn(new BasicHeader(headerName, "foo"));
    final Header result = sut.checkHeaderNotNull(mockedResponse, headerName);
    assertEquals("foo", result.getValue());
}

From source file:com.vincestyling.netroid.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }/*from   w  ww.ja v  a 2s.  c  o m*/
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }

    setConnectionParametersForRequest(connection, request);

    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }

    StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }

    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }

    return response;
}

From source file:org.apache.maven.wagon.providers.http.HttpMethodConfiguration.java

public Header[] asRequestHeaders() {
    if (headers == null) {
        return new Header[0];
    }/*from   w  ww .  ja va  2s  .  c om*/

    Header[] result = new Header[headers.size()];

    int index = 0;
    for (Map.Entry entry : headers.entrySet()) {
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();

        Header header = new BasicHeader(key, value);
        result[index++] = header;
    }

    return result;
}

From source file:org.apache.axis2.transport.http.HTTPWorker.java

public void service(final AxisHttpRequest request, final AxisHttpResponse response,
        final MessageContext msgContext) throws HttpException, IOException {
    ConfigurationContext configurationContext = msgContext.getConfigurationContext();
    final String servicePath = configurationContext.getServiceContextPath();
    final String contextPath = (servicePath.startsWith("/") ? servicePath : "/" + servicePath) + "/";

    String uri = request.getRequestURI();
    String method = request.getMethod();
    String soapAction = HttpUtils.getSoapAction(request);
    InvocationResponse pi;/*from  w  ww  . ja  v  a 2s  .co  m*/

    if (method.equals(HTTPConstants.HEADER_GET)) {
        if (uri.equals("/favicon.ico")) {
            response.setStatus(HttpStatus.SC_MOVED_PERMANENTLY);
            response.addHeader(new BasicHeader("Location", "http://ws.apache.org/favicon.ico"));
            return;
        }
        if (!uri.startsWith(contextPath)) {
            response.setStatus(HttpStatus.SC_MOVED_PERMANENTLY);
            response.addHeader(new BasicHeader("Location", contextPath));
            return;
        }
        if (uri.endsWith("axis2/services/")) {
            String s = HTTPTransportReceiver.getServicesHTML(configurationContext);
            response.setStatus(HttpStatus.SC_OK);
            response.setContentType("text/html");
            OutputStream out = response.getOutputStream();
            out.write(EncodingUtils.getBytes(s, HTTP.ISO_8859_1));
            return;
        }
        if (uri.indexOf("?") < 0) {
            if (!uri.endsWith(contextPath)) {
                if (uri.endsWith(".xsd") || uri.endsWith(".wsdl")) {
                    HashMap services = configurationContext.getAxisConfiguration().getServices();
                    String file = uri.substring(uri.lastIndexOf("/") + 1, uri.length());
                    if ((services != null) && !services.isEmpty()) {
                        Iterator i = services.values().iterator();
                        while (i.hasNext()) {
                            AxisService service = (AxisService) i.next();
                            InputStream stream = service.getClassLoader()
                                    .getResourceAsStream("META-INF/" + file);
                            if (stream != null) {
                                OutputStream out = response.getOutputStream();
                                response.setContentType("text/xml");
                                ListingAgent.copy(stream, out);
                                out.flush();
                                out.close();
                                return;
                            }
                        }
                    }
                }
            }
        }
        if (uri.endsWith("?wsdl2")) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.length() - 6);
            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    service.printWSDL2(response.getOutputStream(), getHost(request));
                } else {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                }
                return;
            }
        }
        if (uri.endsWith("?wsdl")) {
            /**
             * service name can be hierarchical (axis2/services/foo/1.0.0/Version?wsdl) or
             * normal (axis2/services/Version?wsdl).
             */
            String[] temp = uri.split(configurationContext.getServiceContextPath() + "/");
            String serviceName = temp[1].substring(0, temp[1].length() - 5);

            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    service.printWSDL(response.getOutputStream(), getHost(request));
                } else {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                }
                return;
            }
        }
        if (uri.endsWith("?xsd")) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.length() - 4);
            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    service.printSchema(response.getOutputStream());
                } else {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                }
                return;
            }
        }
        //cater for named xsds - check for the xsd name
        if (uri.indexOf("?xsd=") > 0) {
            // fix for imported schemas
            String[] uriParts = uri.split("[?]xsd=");
            String serviceName = uri.substring(uriParts[0].lastIndexOf("/") + 1, uriParts[0].length());
            String schemaName = uri.substring(uri.lastIndexOf("=") + 1);

            HashMap services = configurationContext.getAxisConfiguration().getServices();
            AxisService service = (AxisService) services.get(serviceName);
            if (service != null) {
                boolean canExposeServiceMetadata = canExposeServiceMetadata(service);
                if (!canExposeServiceMetadata) {
                    response.setStatus(HttpStatus.SC_FORBIDDEN);
                    return;
                }
                //run the population logic just to be sure
                service.populateSchemaMappings();
                //write out the correct schema
                Map schemaTable = service.getSchemaMappingTable();
                XmlSchema schema = (XmlSchema) schemaTable.get(schemaName);
                if (schema == null) {
                    int dotIndex = schemaName.indexOf('.');
                    if (dotIndex > 0) {
                        String schemaKey = schemaName.substring(0, dotIndex);
                        schema = (XmlSchema) schemaTable.get(schemaKey);
                    }
                }
                //schema found - write it to the stream
                if (schema != null) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.setContentType("text/xml");
                    schema.write(response.getOutputStream());
                    return;
                } else {
                    InputStream instream = service.getClassLoader()
                            .getResourceAsStream(DeploymentConstants.META_INF + "/" + schemaName);

                    if (instream != null) {
                        response.setStatus(HttpStatus.SC_OK);
                        response.setContentType("text/xml");
                        OutputStream outstream = response.getOutputStream();
                        boolean checkLength = true;
                        int length = Integer.MAX_VALUE;
                        int nextValue = instream.read();
                        if (checkLength)
                            length--;
                        while (-1 != nextValue && length >= 0) {
                            outstream.write(nextValue);
                            nextValue = instream.read();
                            if (checkLength)
                                length--;
                        }
                        outstream.flush();
                        return;
                    } else {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        int ret = service.printXSD(baos, schemaName);
                        if (ret > 0) {
                            baos.flush();
                            instream = new ByteArrayInputStream(baos.toByteArray());
                            response.setStatus(HttpStatus.SC_OK);
                            response.setContentType("text/xml");
                            OutputStream outstream = response.getOutputStream();
                            boolean checkLength = true;
                            int length = Integer.MAX_VALUE;
                            int nextValue = instream.read();
                            if (checkLength)
                                length--;
                            while (-1 != nextValue && length >= 0) {
                                outstream.write(nextValue);
                                nextValue = instream.read();
                                if (checkLength)
                                    length--;
                            }
                            outstream.flush();
                            return;
                        }
                        // no schema available by that name  - send 404
                        response.sendError(HttpStatus.SC_NOT_FOUND, "Schema Not Found!");
                        return;
                    }
                }
            }
        }
        if (uri.indexOf("?wsdl2=") > 0) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("?wsdl2="));
            if (processInternalWSDL(uri, configurationContext, serviceName, response, getHost(request)))
                return;
        }
        if (uri.indexOf("?wsdl=") > 0) {
            String serviceName = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("?wsdl="));
            if (processInternalWSDL(uri, configurationContext, serviceName, response, getHost(request)))
                return;
        }

        String contentType = null;
        Header[] headers = request.getHeaders(HTTPConstants.HEADER_CONTENT_TYPE);
        if (headers != null && headers.length > 0) {
            contentType = headers[0].getValue();
            int index = contentType.indexOf(';');
            if (index > 0) {
                contentType = contentType.substring(0, index);
            }
        }

        // deal with GET request
        pi = RESTUtil.processURLRequest(msgContext, response.getOutputStream(), contentType);

    } else if (method.equals(HTTPConstants.HEADER_POST)) {
        // deal with POST request

        String contentType = request.getContentType();

        if (HTTPTransportUtils.isRESTRequest(contentType)) {
            pi = RESTUtil.processXMLRequest(msgContext, request.getInputStream(), response.getOutputStream(),
                    contentType);
        } else {
            String ip = (String) msgContext.getProperty(MessageContext.TRANSPORT_ADDR);
            if (ip != null) {
                uri = ip + uri;
            }
            pi = HTTPTransportUtils.processHTTPPostRequest(msgContext, request.getInputStream(),
                    response.getOutputStream(), contentType, soapAction, uri);
        }

    } else if (method.equals(HTTPConstants.HEADER_PUT)) {

        String contentType = request.getContentType();
        msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);

        pi = RESTUtil.processXMLRequest(msgContext, request.getInputStream(), response.getOutputStream(),
                contentType);

    } else if (method.equals(HTTPConstants.HEADER_DELETE)) {

        pi = RESTUtil.processURLRequest(msgContext, response.getOutputStream(), null);

    } else {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    Boolean holdResponse = (Boolean) msgContext.getProperty(RequestResponseTransport.HOLD_RESPONSE);
    if (pi.equals(InvocationResponse.SUSPEND) || (holdResponse != null && Boolean.TRUE.equals(holdResponse))) {
        try {
            ((RequestResponseTransport) msgContext.getProperty(RequestResponseTransport.TRANSPORT_CONTROL))
                    .awaitResponse();
        } catch (InterruptedException e) {
            throw new IOException("We were interrupted, so this may not function correctly:" + e.getMessage());
        }
    }

    // Finalize response
    RequestResponseTransport requestResponseTransportControl = (RequestResponseTransport) msgContext
            .getProperty(RequestResponseTransport.TRANSPORT_CONTROL);

    if (TransportUtils.isResponseWritten(msgContext)
            || ((requestResponseTransportControl != null) && requestResponseTransportControl.getStatus()
                    .equals(RequestResponseTransport.RequestResponseTransportStatus.SIGNALLED))) {
        // The response is written or signalled.  The current status is used (probably SC_OK).
    } else {
        // The response may be ack'd, mark the status as accepted.
        response.setStatus(HttpStatus.SC_ACCEPTED);
    }
}