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

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

Introduction

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

Prototype

public BasicHttpResponse(ProtocolVersion protocolVersion, int i, String str) 

Source Link

Usage

From source file:com.autonomy.aci.client.services.impl.DocumentProcessorTest.java

@Test
public void testProcessor() throws IOException, ProcessorException, AciErrorException {
    // Setup with a error response file...
    final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
    response.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/GetVersion.xml"), -1));

    // Set the AciResponseInputStream...
    final AciResponseInputStream stream = new AciResponseInputStreamImpl(response);

    // Process...
    final Document document = processor.process(stream);
    assertThat("Document is null", document, is(notNullValue()));
}

From source file:org.dataconservancy.ui.services.EZIDServiceImplTest.java

/**
 * Tests exceptional conditions when calling the save method, including bad return code and unexpect return format
 * @throws ClientProtocolException/*from   ww w.j a  va  2 s  .co m*/
 * @throws IOException
 */
@Test
public void testSaveExceptions() throws ClientProtocolException, IOException {
    HttpResponse mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 200, "ok");
    StringEntity entity = new StringEntity("success: namespace:id");
    mockResponse.setEntity(entity);

    HttpClient mockHttpClient = mock(HttpClient.class);
    when(mockHttpClient.execute(any(HttpPost.class)))
            .thenThrow(new ClientProtocolException("Expected exception"));

    ezidService.setHttpClient(mockHttpClient);

    boolean caughtException = false;
    try {
        ezidService.saveID("www.test.com/id/namespace:id");
    } catch (EZIDServiceException e) {
        caughtException = true;
        assertEquals("org.apache.http.client.ClientProtocolException: Expected exception", e.getMessage());
    }

    assertTrue(caughtException);

    mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 404, "not found");
    mockResponse.setEntity(entity);

    mockHttpClient = mock(HttpClient.class);
    when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(mockResponse);

    ezidService.setHttpClient(mockHttpClient);

    caughtException = false;
    try {
        ezidService.saveID("www.test.com/id/namespace:id");
    } catch (EZIDServiceException e) {
        caughtException = true;
        assertTrue(e.getMessage().contains("not found"));
    }

    assertTrue(caughtException);

    mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 200, "ok");
    entity = new StringEntity("namespace:id");
    mockResponse.setEntity(entity);

    mockHttpClient = mock(HttpClient.class);
    when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(mockResponse);

    ezidService.setHttpClient(mockHttpClient);

    caughtException = false;
    try {
        ezidService.saveID("www.test.com/id/namespace:id");
    } catch (EZIDServiceException e) {
        caughtException = true;
        assertEquals("Unexpected response: namespace:id", e.getMessage());
    }

    assertTrue(caughtException);
}

From source file:com.navjagpal.fileshare.WebServer.java

private void handleLoginRequest(DefaultHttpServerConnection serverConnection, HttpRequest request,
        RequestLine requestLine) throws HttpException, IOException {

    BasicHttpEntityEnclosingRequest enclosingRequest = new BasicHttpEntityEnclosingRequest(
            request.getRequestLine());//from   w w w  . ja  va 2s  .  c  o  m
    serverConnection.receiveRequestEntity(enclosingRequest);

    InputStream input = enclosingRequest.getEntity().getContent();
    InputStreamReader reader = new InputStreamReader(input);

    StringBuffer form = new StringBuffer();
    while (reader.ready()) {
        form.append((char) reader.read());
    }
    String password = form.substring(form.indexOf("=") + 1);
    if (password.equals(mSharedPreferences.getString(FileSharingService.PREFS_PASSWORD, ""))) {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 302, "Found");
        response.addHeader("Location", "/");
        response.addHeader("Set-Cookie", "id=" + createCookie());
        response.setEntity(new StringEntity(getHTMLHeader() + "Success!" + getHTMLFooter()));
        serverConnection.sendResponseHeader(response);
        serverConnection.sendResponseEntity(response);
    } else {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 401, "Unauthorized");
        response.setEntity(
                new StringEntity(getHTMLHeader() + "<p>Login failed.</p>" + getLoginForm() + getHTMLFooter()));
        serverConnection.sendResponseHeader(response);
        serverConnection.sendResponseEntity(response);
    }
}

From source file:ut.ee.mh.WebServer.java

private void handleLocationRequest(DefaultHttpServerConnection serverConnection, HttpRequest request,
        RequestLine requestLine) throws HttpException, IOException {

    BasicHttpEntityEnclosingRequest enclosingRequest = new BasicHttpEntityEnclosingRequest(
            request.getRequestLine());//from  w  ww  .  j  a v a 2  s .  c o m
    serverConnection.receiveRequestEntity(enclosingRequest);

    InputStream input = enclosingRequest.getEntity().getContent();
    InputStreamReader reader = new InputStreamReader(input);

    StringBuffer form = new StringBuffer();
    while (reader.ready()) {
        form.append((char) reader.read());
    }
    String password = form.substring(form.indexOf("=") + 1);

    if (password.equals(mSharedPreferences.getString(FileSharingService.PREFS_PASSWORD, ""))) {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 302, "Found");
        response.addHeader("Location", "/");
        response.addHeader("Set-Cookie", "id=" + createCookie());
        response.setEntity(new StringEntity(getHTMLHeader() + "Success!" + getHTMLFooter()));
        serverConnection.sendResponseHeader(response);
        serverConnection.sendResponseEntity(response);
    } else {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 401, "Unauthorized");
        response.setEntity(
                new StringEntity(getHTMLHeader() + "<p>Login failed.</p>" + getLoginForm() + getHTMLFooter()));
        serverConnection.sendResponseHeader(response);
        serverConnection.sendResponseEntity(response);
    }
}

From source file:org.esigate.DriverTest.java

public void testSpecialCharacterInErrorPage() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    HttpEntity httpEntity = new StringEntity("", "UTF-8");
    response.setEntity(httpEntity);//  w  w w  .j  a  v a 2s  .c  o m
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    assertEquals("", HttpResponseUtils.toString(driverResponse));
}

From source file:name.persistent.behaviours.DomainSupport.java

@type("message/x-response")
@iri("http://persistent.name/rdf/2010/purl#entity-graph")
public HttpResponse entityGraph(@type("application/rdf+xml") ReadableByteChannel in) {
    HttpResponse resp = new BasicHttpResponse(HTTP11, 200, "OK");
    purlSetEntityHeaders(resp);// www.j  a  v a  2  s . c  o  m
    String type = "application/rdf+xml";
    resp.setEntity(new ReadableHttpEntityChannel(type, -1, in));
    return resp;
}

From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java

/**
 * Opens a URL. It can be a simple URL or one which requires basic
 * authentication./*from w w w .ja v  a2s  . c  o m*/
 * <p/>
 * Tries to access the given URL. If http response is either
 * {@code HttpStatus.SC_UNAUTHORIZED} or
 * {@code HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED}, asks for
 * login/password and tries to authenticate into proxy server and/or URL.
 * <p/>
 * This implementation relies on the Apache Http Client due to its
 * capabilities of proxy/http authentication. <br/>
 * Proxy configuration is determined by {@link ProxySelectorRoutePlanner} using the JVM proxy
 * settings by default.
 * <p/>
 * For more information see: <br/>
 * - {@code http://hc.apache.org/httpcomponents-client-ga/} <br/>
 * - {@code http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/conn/ProxySelectorRoutePlanner.html}
 * <p/>
 * There's a very simple realm cache implementation.
 * Login/Password for each realm are stored in a static {@link Map}.
 * Before asking the user the method verifies if the information is already
 * available in the memory cache.
 *
 * @param url                   the URL string to be opened.
 * @param needsMarkResetSupport Indicates the caller <em>must</em> have an input stream that
 *                              supports the mark/reset operations (as indicated by {@link InputStream#markSupported()}.
 *                              Implementation detail: If the original stream does not, it will be fetched and wrapped
 *                              into a {@link ByteArrayInputStream}. This can only work sanely if the resource is a
 *                              small file that can fit in memory. It also means the caller has no chance of showing
 *                              a meaningful download progress. If unsure, callers should set this to false.
 * @param monitor               {@link ITaskMonitor} to output status.
 * @param headers               An optional array of HTTP headers to use in the GET request.
 * @return Returns a {@link Pair} with {@code first} holding an {@link InputStream}
 * and {@code second} holding an {@link HttpResponse}.
 * The returned pair is never null and contains
 * at least a code; for http requests that provide them the response
 * also contains locale, headers and an status line.
 * The input stream can be null, especially in case of error.
 * The caller must only accept the stream if the response code is 200 or similar.
 * @throws IOException             Exception thrown when there are problems retrieving
 *                                 the URL or its content.
 * @throws CanceledByUserException Exception thrown if the user cancels the
 *                                 authentication dialog.
 */
@NonNull
static Pair<InputStream, HttpResponse> openUrl(@NonNull String url, boolean needsMarkResetSupport,
        @NonNull ITaskMonitor monitor, @Nullable Header[] headers) throws IOException, CanceledByUserException {

    Exception fallbackOnJavaUrlConnect = null;
    Pair<InputStream, HttpResponse> result = null;

    try {
        result = openWithHttpClient(url, monitor, headers);

    } catch (UnknownHostException e) {
        // Host in unknown. No need to even retry with the Url object,
        // if it's broken, it's broken. It's already an IOException but
        // it could use a better message.
        throw new IOException("Unknown Host " + e.getMessage(), e);

    } catch (ClientProtocolException e) {
        // We get this when HttpClient fails to accept the current protocol,
        // e.g. when processing file:// URLs.
        fallbackOnJavaUrlConnect = e;

    } catch (IOException e) {
        throw e;

    } catch (CanceledByUserException e) {
        // HTTP Basic Auth or NTLM login was canceled by user.
        throw e;

    } catch (Exception e) {
        if (DEBUG) {
            System.out.printf("[HttpClient Error] %s : %s\n", url, e.toString());
        }

        fallbackOnJavaUrlConnect = e;
    }

    if (fallbackOnJavaUrlConnect != null) {
        // If the protocol is not supported by HttpClient (e.g. file:///),
        // revert to the standard java.net.Url.open.

        try {
            result = openWithUrl(url, headers);
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            if (DEBUG && !fallbackOnJavaUrlConnect.equals(e)) {
                System.out.printf("[Url Error] %s : %s\n", url, e.toString());
            }
        }
    }

    // If the caller requires an InputStream that supports mark/reset, let's
    // make sure we have such a stream.
    if (result != null && needsMarkResetSupport) {
        InputStream is = result.getFirst();
        if (is != null) {
            if (!is.markSupported()) {
                try {
                    // Consume the whole input stream and offer a byte array stream instead.
                    // This can only work sanely if the resource is a small file that can
                    // fit in memory. It also means the caller has no chance of showing
                    // a meaningful download progress.
                    InputStream is2 = toByteArrayInputStream(is);
                    if (is2 != null) {
                        result = Pair.of(is2, result.getSecond());
                        try {
                            is.close();
                        } catch (Exception ignore) {
                        }
                    }
                } catch (Exception e3) {
                    // Ignore. If this can't work, caller will fail later.
                }
            }
        }
    }

    if (result == null) {
        // Make up an error code if we don't have one already.
        HttpResponse outResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), //$NON-NLS-1$
                HttpStatus.SC_METHOD_FAILURE, ""); //$NON-NLS-1$;  // 420=Method Failure
        result = Pair.of(null, outResponse);
    }

    return result;
}

From source file:org.esigate.DriverTest.java

public void testGzipErrorPage() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    response.addHeader("Content-encoding", "gzip");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    byte[] uncompressedBytes = "".getBytes("UTF-8");
    gzos.write(uncompressedBytes, 0, uncompressedBytes.length);
    gzos.close();//w ww  . jav a  2s.com
    byte[] compressedBytes = baos.toByteArray();
    ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes);
    httpEntity.setContentType("Text/html;Charset=UTF-8");
    httpEntity.setContentEncoding("gzip");
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    assertEquals("", HttpResponseUtils.toString(driverResponse));
}

From source file:com.cellbots.httpserver.HttpCommandServer.java

public void handle(final HttpServerConnection conn, final HttpContext context)
        throws HttpException, IOException {
    HttpRequest request = conn.receiveRequestHeader();
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");

    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") && !method.equals("PUT")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }//from w ww  .j a  v a  2  s.  c  o m

    // Get the requested target. This is the string after the domain name in
    // the URL. If the full URL was http://mydomain.com/test.html, target
    // will be /test.html.
    String target = request.getRequestLine().getUri();
    //Log.w(TAG, "*** Request target: " + target);

    // Gets the requested resource name. For example, if the full URL was
    // http://mydomain.com/test.html?x=1&y=2, resource name will be
    // test.html
    final String resName = getResourceNameFromTarget(target);
    UrlParams params = new UrlParams(target);
    //Log.w(TAG, "*** Request LINE: " + request.getRequestLine().toString());
    //Log.w(TAG, "*** Request resource: " + resName);
    if (method.equals("POST") || method.equals("PUT")) {
        byte[] entityContent = null;
        // Gets the content if the request has an entity.
        if (request instanceof HttpEntityEnclosingRequest) {
            conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            if (entity != null) {
                entityContent = EntityUtils.toByteArray(entity);
            }
        }
        response.setStatusCode(HttpStatus.SC_OK);
        if (serverListener != null) {
            serverListener.onRequest(resName, params.keys, params.values, entityContent);
        }
    } else if (dataMap.containsKey(resName)) { // The requested resource is
                                               // a byte array
        response.setStatusCode(HttpStatus.SC_OK);
        response.setHeader("Content-Type", dataMap.get(resName).contentType);
        response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource));
    } else { // Resource is a file recognized by the app
        String fileName = resourceMap.containsKey(resName) ? resourceMap.get(resName).resource : resName;
        String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType
                : "text/html";
        Log.d(TAG, "*** mapped resource: " + fileName);
        Log.d(TAG, "*** checking for file: " + rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName);
        response.setStatusCode(HttpStatus.SC_OK);
        final File file = new File(rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName);
        if (file.exists() && !file.isDirectory()) {
            response.setStatusCode(HttpStatus.SC_OK);
            FileEntity body = new FileEntity(file, URLConnection.guessContentTypeFromName(fileName));
            response.setHeader("Content-Type", URLConnection.guessContentTypeFromName(fileName));
            response.setEntity(body);
        } else if (file.isDirectory()) {
            response.setStatusCode(HttpStatus.SC_OK);
            EntityTemplate body = new EntityTemplate(new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                    ArrayList<String> fileList = getDirListing(file);
                    String resp = "{ \"list\": [";
                    for (String fl : fileList) {
                        resp += "\"" + fl + "\",";
                    }
                    resp = resp.substring(0, resp.length() - 1);
                    resp += "]}";
                    writer.write(resp);
                    writer.flush();
                }
            });
            body.setContentType(contentType);
            response.setEntity(body);
        } else if (resourceMap.containsKey(resName)) {
            EntityTemplate body = new EntityTemplate(new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                    writer.write(resourceMap.get(resName).resource);
                    writer.flush();
                }
            });
            body.setContentType(contentType);
            response.setEntity(body);
        } else {
            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            response.setEntity(new StringEntity("Not Found"));
        }
    }
    conn.sendResponseHeader(response);
    conn.sendResponseEntity(response);
    conn.flush();
    conn.shutdown();
}

From source file:de.ii.xtraplatform.ogc.csw.client.CSWAdapter.java

private HttpResponse requestGET(CSWOperation operation) throws ParserConfigurationException {
    URI url = findUrl(operation.getOperation(), CSW.METHOD.GET);

    HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient;

    URIBuilder uri = new URIBuilder(url);

    Map<String, String> params = operation.toKvp(nsStore, version);

    for (Map.Entry<String, String> param : params.entrySet()) {
        uri.addParameter(param.getKey(), param.getValue());
    }/*from   w w  w .ja  v  a2s .c  o m*/
    //LOGGER.debug(FrameworkMessages.GET_REQUEST_OPERATION_URL, operation.toString(), uri.toString());

    boolean retried = false;
    HttpGet httpGet;
    HttpResponse response;

    try {

        // replace the + with %20
        String uristring = uri.build().toString();
        uristring = uristring.replaceAll("\\+", "%20");
        httpGet = new HttpGet(uristring);

        // TODO: temporary basic auth hack
        if (useBasicAuth) {
            String basic_auth = new String(Base64.encodeBase64((user + ":" + password).getBytes()));
            httpGet.addHeader("Authorization", "Basic " + basic_auth);
        }

        response = httpClient.execute(httpGet, new BasicHttpContext());

        // check http status
        checkResponseStatus(response.getStatusLine().getStatusCode(), uri);

    } catch (SocketTimeoutException ex) {
        if (ignoreTimeouts) {
            //LOGGER.warn(FrameworkMessages.GET_REQUEST_TIMED_OUT_AFTER_MS_URL_REQUEST, HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri.toString());
        }
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "");
        response.setEntity(new StringEntity("", ContentType.TEXT_XML));
    } catch (IOException ex) {
        try {
            if (!isDefaultUrl(uri.build(), CSW.METHOD.GET)) {

                //LOGGER.info(FrameworkMessages.REMOVING_URL, uri.toString());
                this.urls.remove(operation.getOperation().toString());

                //LOGGER.info(FrameworkMessages.RETRY_WITH_DEFAULT_URL, this.urls.get("default"));
                return requestGET(operation);
            }
        } catch (URISyntaxException ex0) {
        }
        //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString());
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (URISyntaxException ex) {
        //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString());
        throw new ReadError("Failed requesting URL: '{}'", uri);
    }
    //LOGGER.debug(FrameworkMessages.WFS_REQUEST_SUBMITTED);
    return response;
}