Example usage for javax.servlet.http HttpServletRequest getMethod

List of usage examples for javax.servlet.http HttpServletRequest getMethod

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getMethod.

Prototype

public String getMethod();

Source Link

Document

Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.

Usage

From source file:org.deegree.securityproxy.authentication.wass.AddParameterAnonymousAuthenticationFilter.java

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain, Authentication authResult) throws IOException, ServletException {
    LOG.debug("Authentication was successful, request will be modified if required!");
    String method = request.getMethod();
    if (isGetRequestedAndSupported(method))
        addParameter(request, authResult);
    else if (isPostRequestedAndSupported(method)) {
        modifyPostBody(request, authResult);
    }/*from w w  w .ja  va2 s.c om*/
    chain.doFilter(request, response);
}

From source file:org.ngrinder.infra.servlet.ResourceLocationConfigurableJnlpDownloadServlet.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*  w ww  . j  ava 2  s . c om*/
        // Forward the the request to existing JNLPDownloadServlet.
        LOGGER.debug("JNLP file is downloading : {}", request.getPathInfo());
        if ("GET".equals(request.getMethod())) {
            doGet(request, response);
        } else if ("HEAD".equals(request.getMethod())) {
            doHead(request, response);
        } else {
            doGet(request, response);
        }
    } catch (Exception e) {
        NoOp.noOp();
    }

}

From source file:guru.nidi.ramlproxy.core.MockServlet.java

private void handleMeta(HttpServletRequest req, HttpServletResponse res, File targetDir, String name)
        throws IOException {
    final int dotPos = name.lastIndexOf('.');
    if (dotPos > 0) {
        name = name.substring(0, dotPos);
    }/*from   w  w w .j  ava2  s.c om*/
    final File metaFile = findFile(targetDir, "META-" + name, req.getMethod());
    if (metaFile != null) {
        try {
            final ReponseMetaData meta = new ReponseMetaData(mapper.readValue(metaFile, Map.class));
            meta.apply(res);
        } catch (Exception e) {
            log.warn("Problem applying meta data for '" + targetDir + "/" + name + "': " + e);
        }
    }
}

From source file:com.bluexml.xforms.chiba.XFormsFilter.java

@Override
public void doFilter(ServletRequest srvRequest, ServletResponse srvResponse, FilterChain filterChain)
        throws IOException, ServletException {

    //ensure correct Request encoding
    if (srvRequest.getCharacterEncoding() == null) {
        srvRequest.setCharacterEncoding(defaultRequestEncoding);
    }/* w  ww .  java 2  s . c om*/

    HttpServletRequest request = (HttpServletRequest) srvRequest;

    HttpServletResponse response = (HttpServletResponse) srvResponse;
    HttpSession session = request.getSession(true);

    if ("GET".equalsIgnoreCase(request.getMethod()) && request.getParameter("submissionResponse") != null) {
        doSubmissionResponse(request, response);
    } else {

        /* before servlet request */
        if (isXFormUpdateRequest(request)) {
            LOG.info("Start Update XForm");

            try {
                XFormsSession xFormsSession = WebUtil.getXFormsSession(request, session);
                xFormsSession.setRequest(request);
                xFormsSession.setResponse(response);
                xFormsSession.handleRequest();
            } catch (XFormsException e) {
                throw new ServletException(e);
            }
            LOG.info("End Update XForm");
        } else {

            /* do servlet request */
            LOG.info("Passing to Chain");
            BufferedHttpServletResponseWrapper bufResponse = new BufferedHttpServletResponseWrapper(
                    (HttpServletResponse) srvResponse);
            filterChain.doFilter(srvRequest, bufResponse);
            LOG.info("Returned from Chain");

            // response is already committed to the client, so nothing is to
            // be done
            if (bufResponse.isCommitted())
                return;

            //set mode of operation (scripted/nonscripted) by config
            if (this.mode == null)
                this.mode = "true";

            if (this.mode.equalsIgnoreCase("true")) {
                request.setAttribute(WebFactory.SCRIPTED, "true");
            } else if (this.mode.equalsIgnoreCase("false")) {
                request.setAttribute(WebFactory.SCRIPTED, "false");
            }

            /* dealing with response from chain */
            if (handleResponseBody(request, bufResponse)) {
                byte[] data = prepareData(bufResponse);
                if (data.length > 0) {
                    request.setAttribute(WebFactory.XFORMS_INPUTSTREAM, new ByteArrayInputStream(data));
                }
            }

            if (handleRequestAttributes(request)) {
                bufResponse.getOutputStream().close();
                LOG.info("Start Filter XForm");

                XFormsSession xFormsSession = null;
                try {
                    XFormsSessionManager sessionManager = DefaultXFormsSessionManagerImpl
                            .getXFormsSessionManager();
                    xFormsSession = sessionManager.createXFormsSession(request, response, session);
                    xFormsSession.setBaseURI(request.getRequestURL().toString());
                    xFormsSession.setXForms();
                    xFormsSession.init();

                    // FIXME patch for upload
                    XFormsSessionBase xFormsSessionBase = (XFormsSessionBase) xFormsSession;
                    reconfigure(xFormsSessionBase);

                    xFormsSession.handleRequest();
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
                    if (xFormsSession != null) {
                        xFormsSession.close(e);
                    }
                    throw new ServletException(e.getMessage());
                }

                LOG.info("End Render XForm");
            } else {
                srvResponse.getOutputStream().write(bufResponse.getData());
                srvResponse.getOutputStream().close();
            }
        }
    }
}

From source file:com.thoughtworks.go.server.GoServerContextHandlersTest.java

@Theory
public void shouldRedirectCruiseContextTargetedRequestsToCorrespondingGoUrl(HttpCall httpCall)
        throws IOException, ServletException {
    GoServer goServer = new GoServer(new SystemEnvironment(), new GoCipherSuite(sslSocketFactory),
            mock(GoWebXmlConfiguration.class));
    Handler legacyHandler = goServer.legacyRequestHandler();
    HttpServletResponse response = mock(HttpServletResponse.class);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    when(response.getWriter()).thenReturn(new PrintWriter(output));
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getMethod()).thenReturn(httpCall.method);
    legacyHandler.handle("/cruise" + httpCall.url, request, response, Handler.REQUEST);

    String responseBody = new String(output.toByteArray());
    assertThat(responseBody,//w w w.j  a v a  2 s .c  om
            is("Url(s) starting in '/cruise' have been permanently moved to '/go', please use the new path."));

    verify(response).setStatus(httpCall.expectedResponse);

    if (httpCall.shouldRedirect) {
        verify(response).setHeader("Location", "/go" + httpCall.url);
    }

    verify(response).setHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
    verify(response).getWriter();
    verifyNoMoreInteractions(response);
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.ProxyServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;/*from  w w w  . j  av a 2s. c  om*/

    ExtendedHttpMethod method;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        method = new ExtendedGetMethod();
    else
        method = new ExtendedPostMethod();

    method.setDecompress(false);

    // for this create ui server and port, properties.
    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getServerName());
    capturedData.setRequestMethod(httpRequest.getMethod());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setHttpRequestParameters(httpRequest);
    capturedData.setTargetURL(httpRequest.getRequestURL().toString());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // check connection header
    String connectionHeader = httpRequest.getHeader("Connection");
    if (connectionHeader != null) {
        connectionHeader = connectionHeader.toLowerCase();
        if (connectionHeader.indexOf("keep-alive") < 0 && connectionHeader.indexOf("close") < 0)
            connectionHeader = null;
    }

    // copy headers
    boolean xForwardedFor = false;
    @SuppressWarnings("unused")
    long contentLength = -1;
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if (dontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHeader != null && connectionHeader.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr))
            contentLength = request.getContentLength();

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                method.setRequestHeader(lhdr, val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
            }
        }
    }

    // Proxy headers
    method.setRequestHeader("Via", "SoapUI Monitor");
    if (!xForwardedFor)
        method.addRequestHeader("X-Forwarded-For", request.getRemoteAddr());

    if (method instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) method)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    StringBuffer url = new StringBuffer("http://");
    url.append(httpRequest.getServerName());
    if (httpRequest.getServerPort() != 80)
        url.append(":" + httpRequest.getServerPort());
    if (httpRequest.getServletPath() != null) {
        url.append(httpRequest.getServletPath());
        method.setPath(httpRequest.getServletPath());
        if (httpRequest.getQueryString() != null) {
            url.append("?" + httpRequest.getQueryString());
            method.setPath(httpRequest.getServletPath() + "?" + httpRequest.getQueryString());
        }
    }
    hostConfiguration.setHost(new URI(url.toString(), true));

    // SoapUI.log("PROXY to:" + url);

    monitor.fireBeforeProxy(request, response, method, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method);
    }

    // wait for transaction to end and store it.
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(method.getResponseBody());
    capturedData.setResponseHeader(method);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), method, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), method, capturedData.getRawResponseBody()));
    capturedData.setResponseContent(new String(method.getDecompressedResponseBody()));

    monitor.fireAfterProxy(request, response, method, capturedData);

    if (!response.isCommitted()) {
        StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
        // capturedData = null;

        // copy headers to response
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        for (String name : responseHeaders.keySet()) {
            for (String header : responseHeaders.get(name))
                httpResponse.addHeader(name, header);
        }

        IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());
    }

    synchronized (this) {
        if (checkContentType(method)) {
            monitor.addMessageExchange(capturedData);
        }
    }
}

From source file:net.bpelunit.framework.control.ws.WebServiceHandler.java

/**
 * //  w  ww  .j  ava2 s .  c o m
 * <p>
 * Handles one incoming HTTP request. The sequence is as follows:
 * </p>
 * <ul>
 * <li>Check incoming URL for the partner track name. If none, reject.</li>
 * <li>Find partner for the name. If none or partner has no activities,
 * reject.</li>
 * <li>Post incoming message with partner name to the runner. Wait for
 * answer.</li>
 * <li>Get incoming message from runner. Return message in HTTP Request.</li>
 * </ul>
 * 
 */
@Override
public void handle(String pathInContext, Request rawRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    wsLogger.info("Incoming request for path " + pathInContext);

    if (!request.getMethod().equals(HttpMethods.POST)) {
        wsLogger.error("Got a non-POST request - rejecting message " + pathInContext);
        // no POST method
        // let default 404 handler handle this situation.
        return;
    }

    if (fRunner == null) {
        wsLogger.error("Not initialized - rejecting message for URL " + pathInContext);
        // let default 404 handler handle this situaton.
        return;
    }
    // find target according to path in context

    String partnerName = getPartnerName(pathInContext);
    wsLogger.debug("Supposed partner name for this request: " + partnerName);

    PartnerTrack key;
    try {
        key = fRunner.findPartnerTrackForName(partnerName);
        if (key.isDone()) {
            wsLogger.info(
                    "Partner track " + partnerName + " has already finished its execution: replying with 404");
            return;
        }
    } catch (PartnerNotFoundException e1) {
        // Let default 404 handler handle this situation
        wsLogger.info(e1.getMessage());
        wsLogger.info("Rejecting message with 404.");
        return;
    }

    wsLogger.debug("A partner was found for the target URL: " + key);

    wsLogger.debug("Request method is: " + request.getMethod());

    IncomingMessage iMessage = new IncomingMessage();
    iMessage.setMessage(request.getInputStream());

    try {
        wsLogger.debug("Posting incoming message to blackboard...");
        fRunner.putWSIncomingMessage(key, iMessage);

        wsLogger.debug("Waiting for framework to supply answer...");
        final OutgoingMessage m2 = fRunner.getWSOutgoingMessage(key);

        wsLogger.debug("Got answer from framework, now sending...");

        int code = m2.getCode();
        String body = m2.getMessageAsString();

        wsLogger.debug("Answer is:\n" + body);
        for (String option : m2.getProtocolOptionNames()) {
            response.addHeader(option, m2.getProtocolOption(option));
        }
        sendResponse(response, code, body);

        wsLogger.debug("Posting \"message sent\" to framework...");
        fRunner.putWSOutgoingMessageSent(m2);

        wsLogger.info("Done handling request, result OK. " + code);

    } catch (TimeoutException e) {
        wsLogger.error("Timeout while waiting for framework to supply answer to incoming message");
        wsLogger.error("This most likely indicates a bug in the framework.");
        wsLogger.error("Sending fault.");
        sendResponse(response, HTTP_INTERNAL_ERROR, BPELUnitUtil.generateGenericSOAPFault());
    } catch (InterruptedException e) {
        wsLogger.error("Interrupted while waiting for framework for incoming message or answer.");
        wsLogger.error("This most likely indicates another error occurred.");
        wsLogger.error("Sending fault.");
        sendResponse(response, HTTP_INTERNAL_ERROR, BPELUnitUtil.generateGenericSOAPFault());
    } catch (Exception e) {
        // Debugging only
        e.printStackTrace();
        return;
    }
}

From source file:org.alfresco.encryption.DefaultEncryptionUtils.java

/**
 * {@inheritDoc}// ww  w.j  a  v a  2 s. c  o  m
 */
@Override
public byte[] decryptBody(HttpServletRequest req) throws IOException {
    if (req.getMethod().equals("POST")) {
        InputStream bodyStream = req.getInputStream();
        if (bodyStream != null) {
            // expect algorithParameters header
            AlgorithmParameters p = decodeAlgorithmParameters(req);

            // decrypt the body
            InputStream in = encryptor.decrypt(KeyProvider.ALIAS_SOLR, p, bodyStream);
            return IOUtils.toByteArray(in);
        } else {
            return null;
        }
    } else {
        return null;
    }
}

From source file:io.druid.server.AsyncManagementForwardingServletTest.java

private static Server makeTestServer(int port, ExpectedRequest expectedRequest) {
    Server server = new Server(port);
    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(new ServletHolder(new HttpServlet() {
        @Override/* w w w .  j a  va  2  s  .  c  o  m*/
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            handle(req, resp);
        }

        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            handle(req, resp);
        }

        @Override
        protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            handle(req, resp);
        }

        @Override
        protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            handle(req, resp);
        }

        private void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            boolean passed = expectedRequest.path.equals(req.getRequestURI());
            passed &= expectedRequest.query == null || expectedRequest.query.equals(req.getQueryString());
            passed &= expectedRequest.method.equals(req.getMethod());

            if (expectedRequest.headers != null) {
                for (Map.Entry<String, String> header : expectedRequest.headers.entrySet()) {
                    passed &= header.getValue().equals(req.getHeader(header.getKey()));
                }
            }

            passed &= expectedRequest.body == null
                    || expectedRequest.body.equals(IOUtils.toString(req.getReader()));

            expectedRequest.called = true;
            resp.setStatus(passed ? 200 : 400);
        }
    }), "/*");

    server.setHandler(handler);
    return server;
}