Example usage for org.apache.commons.httpclient Header Header

List of usage examples for org.apache.commons.httpclient Header Header

Introduction

In this page you can find the example usage for org.apache.commons.httpclient Header Header.

Prototype

public Header(String paramString1, String paramString2) 

Source Link

Usage

From source file:org.apache.cactus.WebResponse.java

/**
 * @return the cookies returned by the server
 *///from  w  w  w . j  a v  a 2s. c  o m
public Cookie[] getCookies() {
    Cookie[] returnCookies = null;

    // There can be several headers named "Set-Cookie", so loop through
    // all the headers, looking for cookies
    String headerName = this.connection.getHeaderFieldKey(0);
    String headerValue = this.connection.getHeaderField(0);

    Vector cookieVector = new Vector();
    CookieSpec cookieSpec = CookiePolicy.getDefaultSpec();

    for (int i = 1; (headerName != null) || (headerValue != null); i++) {
        LOGGER.debug("Header name  = [" + headerName + "]");
        LOGGER.debug("Header value = [" + headerValue + "]");

        if ((headerName != null) && (headerName.toLowerCase().equals("set-cookie")
                || headerName.toLowerCase().equals("set-cookie2"))) {
            // Parse the cookie definition
            org.apache.commons.httpclient.Cookie[] cookies;
            try {
                cookies = cookieSpec.parse(
                        CookieUtil.getCookieDomain(getWebRequest(), getConnection().getURL().getHost()),
                        CookieUtil.getCookiePort(getWebRequest(), getConnection().getURL().getPort()),
                        CookieUtil.getCookiePath(getWebRequest(), getConnection().getURL().getFile()), false,
                        new Header(headerName, headerValue));
            } catch (HttpException e) {
                throw new ChainedRuntimeException("Error parsing cookies", e);
            }

            // Transform the HttpClient cookies into Cactus cookies and
            // add them to the cookieVector vector
            for (int j = 0; j < cookies.length; j++) {
                Cookie cookie = new Cookie(cookies[j].getDomain(), cookies[j].getName(), cookies[j].getValue());

                cookie.setComment(cookies[j].getComment());
                cookie.setExpiryDate(cookies[j].getExpiryDate());
                cookie.setPath(cookies[j].getPath());
                cookie.setSecure(cookies[j].getSecure());

                cookieVector.addElement(cookie);
            }
        }

        headerName = this.connection.getHeaderFieldKey(i);
        headerValue = this.connection.getHeaderField(i);
    }

    returnCookies = new Cookie[cookieVector.size()];
    cookieVector.copyInto(returnCookies);

    return returnCookies;
}

From source file:org.apache.cocoon.components.language.markup.xsp.SOAPHelper.java

public XScriptObject invoke() throws ProcessingException {
    HttpConnection conn = null;/*  w  w w . j  a va  2 s.c  o m*/

    try {
        if (action == null || action.length() == 0) {
            action = "\"\"";
        }

        String host = url.getHost();
        int port = url.getPort();

        if (System.getProperty("http.proxyHost") != null) {
            String proxyHost = System.getProperty("http.proxyHost");
            int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
            conn = new HttpConnection(proxyHost, proxyPort, host, port);
        } else {
            conn = new HttpConnection(host, port);
        }

        PostMethod method = new PostMethod(url.getFile());
        String request;

        try {
            // Write the SOAP request body
            if (xscriptObject instanceof XScriptObjectInlineXML) {
                // Skip overhead
                request = ((XScriptObjectInlineXML) xscriptObject).getContent();
            } else {
                StringBuffer bodyBuffer = new StringBuffer();
                InputSource saxSource = xscriptObject.getInputSource();

                Reader r = null;
                // Byte stream or character stream?
                if (saxSource.getByteStream() != null) {
                    r = new InputStreamReader(saxSource.getByteStream());
                } else {
                    r = saxSource.getCharacterStream();
                }

                try {
                    char[] buffer = new char[1024];
                    int len;
                    while ((len = r.read(buffer)) > 0)
                        bodyBuffer.append(buffer, 0, len);
                } finally {
                    if (r != null) {
                        r.close();
                    }
                }

                request = bodyBuffer.toString();
            }

        } catch (Exception ex) {
            throw new ProcessingException("Error assembling request", ex);
        }

        method.setRequestHeader(new Header("Content-type", "text/xml; charset=\"utf-8\""));
        method.setRequestHeader(new Header("SOAPAction", action));
        method.setRequestBody(request);

        if (authorization != null && !authorization.equals("")) {
            method.setRequestHeader(
                    new Header("Authorization", "Basic " + SourceUtil.encodeBASE64(authorization)));
        }

        method.execute(new HttpState(), conn);

        String ret = method.getResponseBodyAsString();
        int startOfXML = ret.indexOf("<?xml");
        if (startOfXML == -1) { // No xml?!
            throw new ProcessingException("Invalid response - no xml");
        }

        return new XScriptObjectInlineXML(xscriptManager, ret.substring(startOfXML));
    } catch (Exception ex) {
        throw new ProcessingException("Error invoking remote service: " + ex, ex);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception ex) {
        }
    }
}

From source file:org.apache.cocoon.components.language.markup.xsp.XSPSOAPHelper.java

public XScriptObject invoke() throws ProcessingException {
    HttpConnection conn = null;/* w  w w.j a v  a2s  .  c  o  m*/

    try {
        if (this.action == null || this.action.length() == 0) {
            this.action = "\"\"";
        }

        String host = this.url.getHost();
        int port = this.url.getPort();
        Protocol protocol = Protocol.getProtocol(this.url.getProtocol());

        if (System.getProperty("http.proxyHost") != null) {
            String proxyHost = System.getProperty("http.proxyHost");
            int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
            conn = new HttpConnection(proxyHost, proxyPort, host, null, port, protocol);
        } else {
            conn = new HttpConnection(host, port, protocol);
        }
        conn.setSoTimeout(1000 * timeoutSeconds);

        PostMethod method = new PostMethod(this.url.getFile());
        String request;

        try {
            // Write the SOAP request body
            if (this.xscriptObject instanceof XScriptObjectInlineXML) {
                // Skip overhead
                request = ((XScriptObjectInlineXML) this.xscriptObject).getContent();
            } else {
                StringBuffer bodyBuffer = new StringBuffer();
                InputSource saxSource = this.xscriptObject.getInputSource();

                Reader r = null;
                // Byte stream or character stream?
                if (saxSource.getByteStream() != null) {
                    r = new InputStreamReader(saxSource.getByteStream());
                } else {
                    r = saxSource.getCharacterStream();
                }

                try {
                    char[] buffer = new char[1024];
                    int len;
                    while ((len = r.read(buffer)) > 0) {
                        bodyBuffer.append(buffer, 0, len);
                    }
                } finally {
                    if (r != null) {
                        r.close();
                    }
                }

                request = bodyBuffer.toString();
            }

        } catch (Exception ex) {
            throw new ProcessingException("Error assembling request", ex);
        }

        method.setRequestHeader(new Header("Content-type", "text/xml; charset=utf-8"));
        method.setRequestHeader(new Header("SOAPAction", this.action));
        method.setRequestBody(request);

        if (this.authorization != null && !this.authorization.equals("")) {
            method.setRequestHeader(
                    new Header("Authorization", "Basic " + SourceUtil.encodeBASE64(this.authorization)));
        }

        method.execute(new HttpState(), conn);

        String contentType = method.getResponseHeader("Content-type").toString();
        // Check if charset given, if not, use defaultResponseEncoding
        // (cannot just use getResponseCharSet() as it fills in
        // "ISO-8859-1" if the charset is not specified)
        String charset = contentType.indexOf("charset=") == -1 ? this.defaultResponseEncoding
                : method.getResponseCharSet();
        String ret = new String(method.getResponseBody(), charset);

        return new XScriptObjectInlineXML(this.xscriptManager, ret);
    } catch (ProcessingException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ProcessingException("Error invoking remote service: " + ex, ex);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception ex) {
        }
    }
}

From source file:org.apache.hadoop.fs.swift.http.SwiftRestClient.java

/**
 * Makes HTTP GET request to Swift/*  ww  w  .jav a2  s . c o  m*/
 *
 * @param path   path to object
 * @param offset offset from file beginning
 * @param length file length
 * @return The input stream -which must be closed afterwards.
 */
public InputStream getDataAsInputStream(SwiftObjectPath path, long offset, long length) throws IOException {
    if (offset < 0) {
        throw new SwiftBadRequestException("Invalid offset: " + offset + ".");
    }
    if (length <= 0) {
        throw new SwiftBadRequestException("Invalid length: " + length + ".");
    }

    final String range = String.format(SWIFT_RANGE_HEADER_FORMAT_PATTERN, offset, offset + length - 1);
    if (LOG.isDebugEnabled()) {
        LOG.debug("getDataAsInputStream(" + offset + "," + length + ")");
    }

    return getDataAsInputStream(path, new Header(HEADER_RANGE, range), SwiftRestClient.NEWEST);
}

From source file:org.apache.hadoop.fs.swift.snative.SwiftNativeFileSystemStore.java

/**
 * Tell the Swift server to expect a multi-part upload by submitting
 * a 0-byte file with the X-Object-Manifest header
 *
 * @param path path of final final/*from www  .j a v a2 s  .  co  m*/
 * @throws IOException
 */
public void createManifestForPartUpload(Path path) throws IOException {
    String pathString = toObjectPath(path).toString();
    if (!pathString.endsWith("/")) {
        pathString = pathString.concat("/");
    }
    if (pathString.startsWith("/")) {
        pathString = pathString.substring(1);
    }

    swiftRestClient.upload(toObjectPath(path), new ByteArrayInputStream(new byte[0]), 0,
            new Header(SwiftProtocolConstants.X_OBJECT_MANIFEST, pathString));
}

From source file:org.apache.hadoop.hbase.rest.client.TestRemoteTable.java

/**
 * Test a some methods of class Response.
 *//*from ww  w .  j  ava  2 s  .  co m*/
@Test
public void testResponse() {
    Response response = new Response(200);
    assertEquals(200, response.getCode());
    Header[] headers = new Header[2];
    headers[0] = new Header("header1", "value1");
    headers[1] = new Header("header2", "value2");
    response = new Response(200, headers);
    assertEquals("value1", response.getHeader("header1"));
    assertFalse(response.hasBody());
    response.setCode(404);
    assertEquals(404, response.getCode());
    headers = new Header[2];
    headers[0] = new Header("header1", "value1.1");
    headers[1] = new Header("header2", "value2");
    response.setHeaders(headers);
    assertEquals("value1.1", response.getHeader("header1"));
    response.setBody(Bytes.toBytes("body"));
    assertTrue(response.hasBody());
}

From source file:org.apache.hadoop.hbase.rest.TestGzipFilter.java

@Test
public void testGzipFilter() throws Exception {
    String path = "/" + TABLE + "/" + ROW_1 + "/" + COLUMN_1;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    GZIPOutputStream os = new GZIPOutputStream(bos);
    os.write(VALUE_1);//from ww  w .ja v a  2 s  .  co  m
    os.close();
    byte[] value_1_gzip = bos.toByteArray();

    // input side filter

    Header[] headers = new Header[2];
    headers[0] = new Header("Content-Type", Constants.MIMETYPE_BINARY);
    headers[1] = new Header("Content-Encoding", "gzip");
    Response response = client.put(path, headers, value_1_gzip);
    assertEquals(response.getCode(), 200);

    HTable table = new HTable(TEST_UTIL.getConfiguration(), TABLE);
    Get get = new Get(Bytes.toBytes(ROW_1));
    get.addColumn(Bytes.toBytes(CFA), Bytes.toBytes("1"));
    Result result = table.get(get);
    byte[] value = result.getValue(Bytes.toBytes(CFA), Bytes.toBytes("1"));
    assertNotNull(value);
    assertTrue(Bytes.equals(value, VALUE_1));

    // output side filter

    headers[0] = new Header("Accept", Constants.MIMETYPE_BINARY);
    headers[1] = new Header("Accept-Encoding", "gzip");
    response = client.get(path, headers);
    assertEquals(response.getCode(), 200);
    ByteArrayInputStream bis = new ByteArrayInputStream(response.getBody());
    GZIPInputStream is = new GZIPInputStream(bis);
    value = new byte[VALUE_1.length];
    is.read(value, 0, VALUE_1.length);
    assertTrue(Bytes.equals(value, VALUE_1));
    is.close();
    table.close();

    testScannerResultCodes();
}

From source file:org.apache.hadoop.hbase.rest.TestGzipFilter.java

@Test
public void testErrorNotGzipped() throws Exception {
    Header[] headers = new Header[2];
    headers[0] = new Header("Accept", Constants.MIMETYPE_BINARY);
    headers[1] = new Header("Accept-Encoding", "gzip");
    Response response = client.get("/" + TABLE + "/" + ROW_1 + "/" + COLUMN_2, headers);
    assertEquals(response.getCode(), 404);
    String contentEncoding = response.getHeader("Content-Encoding");
    assertTrue(contentEncoding == null || !contentEncoding.contains("gzip"));
    response = client.get("/" + TABLE, headers);
    assertEquals(response.getCode(), 405);
    contentEncoding = response.getHeader("Content-Encoding");
    assertTrue(contentEncoding == null || !contentEncoding.contains("gzip"));
}

From source file:org.apache.hadoop.hbase.rest.TestGzipFilter.java

void testScannerResultCodes() throws Exception {
    Header[] headers = new Header[3];
    headers[0] = new Header("Content-Type", Constants.MIMETYPE_XML);
    headers[1] = new Header("Accept", Constants.MIMETYPE_JSON);
    headers[2] = new Header("Accept-Encoding", "gzip");
    Response response = client.post("/" + TABLE + "/scanner", headers, "<Scanner/>".getBytes());
    assertEquals(response.getCode(), 201);
    String scannerUrl = response.getLocation();
    assertNotNull(scannerUrl);/*from  w  w w .j  av a2 s  .c o  m*/
    response = client.get(scannerUrl);
    assertEquals(response.getCode(), 200);
    response = client.get(scannerUrl);
    assertEquals(response.getCode(), 204);
}

From source file:org.apache.hadoop.hbase.rest.TestMultiRowResource.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    conf = TEST_UTIL.getConfiguration();
    conf.setBoolean(RESTServer.REST_CSRF_ENABLED_KEY, csrfEnabled);
    extraHdr = new Header(RESTServer.REST_CSRF_CUSTOM_HEADER_DEFAULT, "");
    TEST_UTIL.startMiniCluster();/*from w  w  w . j av a 2  s .  com*/
    REST_TEST_UTIL.startServletContainer(conf);
    context = JAXBContext.newInstance(CellModel.class, CellSetModel.class, RowModel.class);
    marshaller = context.createMarshaller();
    unmarshaller = context.createUnmarshaller();
    client = new Client(new Cluster().add("localhost", REST_TEST_UTIL.getServletPort()));
    Admin admin = TEST_UTIL.getHBaseAdmin();
    if (admin.tableExists(TABLE)) {
        return;
    }
    HTableDescriptor htd = new HTableDescriptor(TABLE);
    htd.addFamily(new HColumnDescriptor(CFA));
    htd.addFamily(new HColumnDescriptor(CFB));
    admin.createTable(htd);
}