Search in sources :

Example 41 with ServletInputStream

use of javax.servlet.ServletInputStream in project jetty.project by eclipse.

the class HttpTrailersTest method testServletRequestTrailers.

@Test
public void testServletRequestTrailers() throws Exception {
    String trailerName = "Trailer";
    String trailerValue = "value";
    start(new AbstractHandler.ErrorDispatchHandler() {

        @Override
        protected void doNonErrorHandle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            jettyRequest.setHandled(true);
            // Read the content first.
            ServletInputStream input = jettyRequest.getInputStream();
            while (true) {
                int read = input.read();
                if (read < 0)
                    break;
            }
            // Now the trailers can be accessed.
            HttpFields trailers = jettyRequest.getTrailers();
            Assert.assertNotNull(trailers);
            Assert.assertEquals(trailerValue, trailers.get(trailerName));
        }
    });
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        client.setSoTimeout(5000);
        String request = "" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "0\r\n" + trailerName + ": " + trailerValue + "\r\n" + "\r\n";
        OutputStream output = client.getOutputStream();
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        HttpTester.Response response = HttpTester.parseResponse(HttpTester.from(client.getInputStream()));
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    }
}
Also used : OutputStream(java.io.OutputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) HttpFields(org.eclipse.jetty.http.HttpFields) Socket(java.net.Socket) Test(org.junit.Test)

Example 42 with ServletInputStream

use of javax.servlet.ServletInputStream in project solo by b3log.

the class MetaWeblogAPI method metaWeblog.

/**
     * MetaWeblog requests processing.
     *
     * @param request the specified http servlet request
     * @param response the specified http servlet response
     * @param context the specified http request context
     */
@RequestProcessing(value = "/apis/metaweblog", method = HTTPRequestMethod.POST)
public void metaWeblog(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) {
    final TextXMLRenderer renderer = new TextXMLRenderer();
    context.setRenderer(renderer);
    String responseContent = null;
    try {
        final ServletInputStream inputStream = request.getInputStream();
        final String xml = IOUtils.toString(inputStream, "UTF-8");
        final JSONObject requestJSONObject = XML.toJSONObject(xml);
        final JSONObject methodCall = requestJSONObject.getJSONObject(METHOD_CALL);
        final String methodName = methodCall.getString(METHOD_NAME);
        LOGGER.log(Level.INFO, "MetaWeblog[methodName={0}]", methodName);
        final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");
        if (METHOD_DELETE_POST.equals(methodName)) {
            // Removes the first argument "appkey"
            params.remove(0);
        }
        final String userEmail = params.getJSONObject(INDEX_USER_EMAIL).getJSONObject("value").getString("string");
        final JSONObject user = userQueryService.getUserByEmail(userEmail);
        if (null == user) {
            throw new Exception("No user[email=" + userEmail + "]");
        }
        final String userPwd = params.getJSONObject(INDEX_USER_PWD).getJSONObject("value").getString("string");
        if (!user.getString(User.USER_PASSWORD).equals(MD5.hash(userPwd))) {
            throw new Exception("Wrong password");
        }
        if (METHOD_GET_USERS_BLOGS.equals(methodName)) {
            responseContent = getUsersBlogs();
        } else if (METHOD_GET_CATEGORIES.equals(methodName)) {
            responseContent = getCategories();
        } else if (METHOD_GET_RECENT_POSTS.equals(methodName)) {
            final int numOfPosts = params.getJSONObject(INDEX_NUM_OF_POSTS).getJSONObject("value").getInt("int");
            responseContent = getRecentPosts(numOfPosts);
        } else if (METHOD_NEW_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            addArticle(article);
            final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<params><param><value><string>").append(article.getString(Keys.OBJECT_ID)).append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_GET_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value").getString("string");
            responseContent = getPost(postId);
        } else if (METHOD_EDIT_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value").getString("string");
            article.put(Keys.OBJECT_ID, postId);
            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            final JSONObject updateArticleRequest = new JSONObject();
            updateArticleRequest.put(Article.ARTICLE, article);
            articleMgmtService.updateArticle(updateArticleRequest);
            final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<params><param><value><string>").append(postId).append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_DELETE_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value").getString("string");
            articleMgmtService.removeArticle(postId);
            final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<params><param><value><boolean>").append(true).append("</boolean></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else {
            throw new UnsupportedOperationException("Unsupported method[name=" + methodName + "]");
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<fault><value><struct>").append("<member><name>faultCode</name><value><int>500</int></value></member>").append("<member><name>faultString</name><value><string>").append(e.getMessage()).append("</string></value></member></struct></value></fault></methodResponse>");
        responseContent = stringBuilder.toString();
    }
    renderer.setContent(responseContent);
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) JSONObject(org.json.JSONObject) TextXMLRenderer(org.b3log.latke.servlet.renderer.TextXMLRenderer) JSONArray(org.json.JSONArray) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) ParseException(java.text.ParseException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 43 with ServletInputStream

use of javax.servlet.ServletInputStream in project jetty.project by eclipse.

the class RequestTest method testContent.

@Test
public void testContent() throws Exception {
    final AtomicInteger length = new AtomicInteger();
    _handler._checker = new RequestTester() {

        @Override
        public boolean check(HttpServletRequest request, HttpServletResponse response) throws IOException {
            int len = request.getContentLength();
            ServletInputStream in = request.getInputStream();
            for (int i = 0; i < len; i++) {
                int b = in.read();
                if (b < 0)
                    return false;
            }
            if (in.read() > 0)
                return false;
            length.set(len);
            return true;
        }
    };
    String content = "";
    for (int l = 0; l < 1024; l++) {
        String request = "POST / HTTP/1.1\r\n" + "Host: whatever\r\n" + "Content-Type: multipart/form-data-test\r\n" + "Content-Length: " + l + "\r\n" + "Connection: close\r\n" + "\r\n" + content;
        Log.getRootLogger().debug("test l={}", l);
        String response = _connector.getResponse(request);
        Log.getRootLogger().debug(response);
        assertThat(response, Matchers.containsString(" 200 OK"));
        assertEquals(l, length.get());
        content += "x";
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletInputStream(javax.servlet.ServletInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) LocalEndPoint(org.eclipse.jetty.server.LocalConnector.LocalEndPoint) Test(org.junit.Test)

Example 44 with ServletInputStream

use of javax.servlet.ServletInputStream in project dropwizard by dropwizard.

the class TaskServletTest method passesPostBodyAlongToPostBodyTasks.

@Test
public void passesPostBodyAlongToPostBodyTasks() throws Exception {
    String body = "{\"json\": true}";
    final PrintWriter output = mock(PrintWriter.class);
    final ServletInputStream bodyStream = new TestServletInputStream(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
    when(request.getMethod()).thenReturn("POST");
    when(request.getPathInfo()).thenReturn("/print-json");
    when(request.getParameterNames()).thenReturn(Collections.enumeration(ImmutableList.of()));
    when(request.getInputStream()).thenReturn(bodyStream);
    when(response.getWriter()).thenReturn(output);
    servlet.service(request, response);
    verify(printJSON).execute(ImmutableMultimap.of(), body, output);
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 45 with ServletInputStream

use of javax.servlet.ServletInputStream in project dropwizard by dropwizard.

the class TaskServletTest method runsATaskWhenFound.

@Test
public void runsATaskWhenFound() throws Exception {
    final PrintWriter output = mock(PrintWriter.class);
    final ServletInputStream bodyStream = new TestServletInputStream(new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8)));
    when(request.getMethod()).thenReturn("POST");
    when(request.getPathInfo()).thenReturn("/gc");
    when(request.getParameterNames()).thenReturn(Collections.enumeration(ImmutableList.of()));
    when(response.getWriter()).thenReturn(output);
    when(request.getInputStream()).thenReturn(bodyStream);
    servlet.service(request, response);
    verify(gc).execute(ImmutableMultimap.of(), output);
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Aggregations

ServletInputStream (javax.servlet.ServletInputStream)79 IOException (java.io.IOException)51 HttpServletRequest (javax.servlet.http.HttpServletRequest)43 Test (org.junit.Test)43 ServletException (javax.servlet.ServletException)41 HttpServletResponse (javax.servlet.http.HttpServletResponse)40 CountDownLatch (java.util.concurrent.CountDownLatch)26 HttpServlet (javax.servlet.http.HttpServlet)20 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)20 InterruptedIOException (java.io.InterruptedIOException)18 AsyncContext (javax.servlet.AsyncContext)17 ReadListener (javax.servlet.ReadListener)17 ServletOutputStream (javax.servlet.ServletOutputStream)16 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)16 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)15 Request (org.eclipse.jetty.server.Request)14 Response (org.eclipse.jetty.client.api.Response)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 PrintWriter (java.io.PrintWriter)8 Matchers.containsString (org.hamcrest.Matchers.containsString)8