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

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:org.piraso.client.net.HttpPirasoEntryReaderTest.java

@Test
public void testStopSuccess() throws Exception {
    StatusLine line = new BasicStatusLine(new ProtocolVersion("http", 1, 0), HttpStatus.SC_OK, "");
    doReturn(line).when(response).getStatusLine();

    reader.stop();/*from   w ww .  java 2  s .  c o  m*/
}

From source file:org.bedework.util.http.HttpUtil.java

/**
 * @return Status line// w w w  .  j  a v a2s  .  co  m
 */
public static StatusLine getHttpStatus(final String statusLine) throws HttpException {
    final String[] splits = statusLine.split("\\s+");

    if ((splits.length < 2) || (!splits[0].startsWith("HTTP/"))) {
        throw new HttpException("Bad status line: " + statusLine);
    }

    final String[] version = splits[0].substring(5).split(".");

    if (version.length != 2) {
        throw new HttpException("Bad status line: " + statusLine);
    }

    final HttpVersion hv = new HttpVersion(Integer.valueOf(version[0]), Integer.valueOf(version[1]));

    final int status = Integer.valueOf(splits[1]);

    final String reason;

    if (splits.length < 3) {
        reason = null;
    } else {
        reason = splits[2];
    }

    return new BasicStatusLine(hv, status, reason);
}

From source file:com.launchkey.sdk.transport.v1.ApacheHttpClientTransportPingTest.java

@Test
public void testResponseStatusCodeOf401ThrowsExpectedException() throws Exception {
    expectedException.expect(LaunchKeyException.class);
    expectedException.expectMessage("Expected Message");

    when(response.getStatusLine())//from   w  w  w  .j  av  a  2 s  .  co  m
            .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 401, "Expected Message"));
    transport.ping(new PingRequest());
}

From source file:org.sentilo.platform.server.test.parser.OrderParserTest.java

@Test
public void parseEmptySensorWriteResponse() throws Exception {
    final String[] parts = { "prov1", "sensor1" };
    when(resource.getParts()).thenReturn(parts);

    final List<Order> ordersList = Collections.emptyList();
    final SentiloResponse response = SentiloResponse
            .build(new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_0, 200, "")));
    parser.writeResponse(sentiloRequest, response, ordersList);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ((ByteArrayEntity) response.getHttpResponse().getEntity()).writeTo(baos);
    final String expected = "{\"orders\":[]}";
    assertEquals(expected, baos.toString());
}

From source file:com.daidiansha.acarry.control.network.core.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError, IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from w w  w.  java 2s .c o  m
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);

    if (!TextUtils.isEmpty(mUserAgent)) {
        connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent);
    }

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    if (request instanceof MultiPartRequest) {
        setConnectionParametersForMultipartRequest(connection, (MultiPartRequest) request);
    } else {
        setConnectionParametersForRequest(connection, request);
    }

    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    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(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    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:com.gargoylesoftware.htmlunit.HttpWebConnectionTest.java

/**
 * Tests creation of a web response.//w w  w. j a va 2 s  .com
 * @throws Exception if the test fails
 */
@Test
public void makeWebResponse() throws Exception {
    final URL url = new URL("http://htmlunit.sourceforge.net/");
    final String content = "<html><head></head><body></body></html>";
    final DownloadedContent downloadedContent = new DownloadedContent.InMemory(content.getBytes());
    final int httpStatus = HttpStatus.SC_OK;
    final long loadTime = 500L;

    final ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 0);
    final StatusLine statusLine = new BasicStatusLine(protocolVersion, HttpStatus.SC_OK, null);
    final HttpResponse httpResponse = new BasicHttpResponse(statusLine);

    final HttpEntity responseEntity = new StringEntity(content);
    httpResponse.setEntity(responseEntity);

    final HttpWebConnection connection = new HttpWebConnection(getWebClient());
    final Method method = connection.getClass().getDeclaredMethod("makeWebResponse", HttpResponse.class,
            WebRequest.class, DownloadedContent.class, long.class);
    method.setAccessible(true);
    final WebResponse response = (WebResponse) method.invoke(connection, httpResponse, new WebRequest(url),
            downloadedContent, new Long(loadTime));

    assertEquals(httpStatus, response.getStatusCode());
    assertEquals(url, response.getWebRequest().getUrl());
    assertEquals(loadTime, response.getLoadTime());
    assertEquals(content, response.getContentAsString());
    assertEquals(content.getBytes(), IOUtils.toByteArray(response.getContentAsStream()));
    assertEquals(new ByteArrayInputStream(content.getBytes()), response.getContentAsStream());
}

From source file:com.launchkey.sdk.transport.v1.ApacheHttpClientTransportPollTest.java

@Test
public void testResponseStatusCodeOf100ThrowsExpectedException() throws Exception {
    expectedException.expect(CommunicationErrorException.class);
    expectedException.expectMessage("Expected Message");

    when(response.getStatusLine())//  ww  w  .  ja  v  a  2s  .  com
            .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 100, "Expected Message"));
    transport.poll(new PollRequest(null, 0L, null, null));
}

From source file:com.launchkey.sdk.transport.v1.ApacheHttpClientTransportUsersTest.java

@Test
public void testResponseStatusCodeOf100ThrowsExpectedException() throws Exception {
    expectedException.expect(CommunicationErrorException.class);
    expectedException.expectMessage("Expected Message");

    when(response.getStatusLine())/*from  www  .j  ava 2s.  c  om*/
            .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 100, "Expected Message"));
    transport.users(new UsersRequest(null, 0L, null));
}

From source file:edu.chalmers.dat076.moviefinder.service.TraktHandlerTest.java

@Test
public void testGetEpisodeByTitleAndEpisode() throws IOException {
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpResponse response = factory/*from  w  w w. j a v a  2 s .  co  m*/
            .newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null), null);
    response.setEntity(new StringEntity(episodeHIMYM, "UTF-8"));
    Mockito.when(defaultHttpClient.execute(getRequest("http://api.trakt.tv/show/episode/summary.json/"
            + Constants.TRAKT_API_KEY + "/how-i-met-your-mother/" + 3 + "/" + 6))).thenReturn(response);
    TraktEpisodeResponse r = instance.getBySeasonEpisode("how i met your mother", 3, 6);

    assertEquals(r.getEpisode().getSeason(), 3);
    assertEquals(r.getEpisode().getNumber(), 6);
}

From source file:org.npr.android.test.HttpServer.java

private void processRequest(DataSource dataSource, Socket client) throws IllegalStateException, IOException {
    if (dataSource == null) {
        Log.e(TAG, "Invalid (null) resource.");
        client.close();/*from   w w  w .  j  a  v  a 2s . c om*/
        return;
    }

    Log.d(TAG, "setting response headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"));
    httpString.append("\n");

    httpString.append("Content-Type: ").append(dataSource.getContentType());
    httpString.append("\n");

    // Some content (e.g. streams) does not define a length
    long length = dataSource.getContentLength();
    if (length >= 0) {
        httpString.append("Content-Length: ").append(length);
        httpString.append("\n");
    }

    httpString.append("\n");
    Log.d(TAG, "headers done");

    InputStream data = null;
    try {
        data = dataSource.createInputStream();
        byte[] buffer = httpString.toString().getBytes();
        int readBytes;
        Log.d(TAG, "writing to client");
        client.getOutputStream().write(buffer, 0, buffer.length);

        // Start sending content.
        byte[] buff = new byte[1024 * 50];
        while (isRunning) {
            readBytes = data.read(buff, 0, buff.length);
            if (readBytes == -1) {
                if (simulateStream) {
                    data.close();
                    data = dataSource.createInputStream();
                    readBytes = data.read(buff, 0, buff.length);
                    if (readBytes == -1) {
                        throw new IOException("Error re-opening data source for looping.");
                    }
                } else {
                    break;
                }
            }
            client.getOutputStream().write(buff, 0, readBytes);
        }
    } catch (SocketException e) {
        // Ignore when the client breaks connection
        Log.w(TAG, "Ignoring " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "Error getting content stream.", e);
    } catch (Exception e) {
        Log.e(TAG, "Error streaming file content.", e);
    } finally {
        if (data != null) {
            data.close();
        }
        client.close();
    }
}