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:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.TunnelServlet.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 a2 s  .  c  o m

    ExtendedHttpMethod postMethod;

    // for this create ui server and port, properties.
    InetSocketAddress inetAddress = new InetSocketAddress(sslEndPoint, sslPort);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        postMethod = new ExtendedGetMethod();
    else
        postMethod = new ExtendedPostMethod();

    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getRemoteHost());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setTargetURL(this.prot + inetAddress.getHostName());

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

    // copy headers
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if ("host".equals(lhdr)) {
            Enumeration<?> vals = httpRequest.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val.startsWith("127.0.0.1")) {
                    postMethod.addRequestHeader(hdr, sslEndPoint);
                }
            }
            continue;
        }

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                postMethod.addRequestHeader(hdr, val);
            }
        }

    }

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

    HostConfiguration hostConfiguration = new HostConfiguration();

    httpRequest.getProtocol();
    hostConfiguration.getParams().setParameter(SoapUIHostConfiguration.SOAPUI_SSL_CONFIG,
            settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPATH, "") + " "
                    + settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPASSWORD, ""));
    hostConfiguration.setHost(new URI(this.prot + sslEndPoint, true));

    hostConfiguration = ProxyUtils.initProxySettings(settings, httpState, hostConfiguration, prot + sslEndPoint,
            new DefaultPropertyExpansionContext(project));

    if (sslEndPoint.indexOf("/") < 0)
        postMethod.setPath("/");
    else
        postMethod.setPath(sslEndPoint.substring(sslEndPoint.indexOf("/"), sslEndPoint.length()));

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

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

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(postMethod.getResponseBody());
    capturedData.setResponseHeader(postMethod);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), postMethod, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), postMethod, capturedData.getRawResponseBody()));

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

    StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
    // 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());

    postMethod.releaseConnection();

    synchronized (this) {
        monitor.addMessageExchange(capturedData);
    }

    capturedData = null;
}

From source file:com.ecs.cms.web.mvc.view.MappingJacksonJsonView.java

/**
 * Prepares the view given the specified model, merging it with static
 * attributes and a RequestContext attribute, if necessary. Delegates to
 * renderMergedOutputModel for the actual rendering.
 * /*  w w  w  .j av a  2  s  .c  o m*/
 * @see #renderMergedOutputModel
 */
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if ("GET".equals(request.getMethod().toUpperCase())) {
        Map<String, String[]> params = request.getParameterMap();

        if (params.containsKey("callback")) {
            response.getOutputStream().write(new String(params.get("callback")[0] + "(").getBytes());
            super.render(model, request, response);
            response.getOutputStream().write(");".getBytes());
            response.setContentType("application/javascript");
        } else {
            super.render(model, request, response);
        }
    } else {
        super.render(model, request, response);
    }
}

From source file:com.bluexml.side.framework.alfresco.shareLanguagePicker.CustomWebScriptView.java

protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    // Expose the model object as request attributes.
    exposeModelAsRequestAttributes(model, request);

    if (logger.isDebugEnabled())
        logger.debug("Processing request (" + request.getMethod() + ") " + request.getRequestURL()
                + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));

    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding("UTF-8");
    }/* ww  w . ja va2 s.co m*/

    Locale resolveLocale = localeResolver.resolveLocale(request);
    localeResolver.setLocale(request, response, resolveLocale);

    // hand off to the WebScript Servlet View runtime
    WebScriptViewRuntime runtime = new WebScriptViewRuntime(getUrl(), container, authenticatorFactory, request,
            response, serverProperties);
    runtime.executeScript();
}

From source file:com.qut.middleware.spep.authn.bindings.impl.AuthnPostBindingImpl.java

public void handleRequest(HttpServletRequest request, HttpServletResponse response, AuthnProcessorData data,
        SPEP spep) throws AuthenticationException {
    if (request.getMethod().equals(HTTP_GET)) {
        this.handleAuthnRequest(request, response, data, spep);
    } else if (request.getMethod().equals(HTTP_POST)) {
        this.handleAuthnResponse(request, response, data, spep);
    } else {/*from   ww  w.j a  v a 2 s  . c om*/
        throw new AuthenticationException(
                "Unsupported HTTP request method for this binding: " + request.getMethod());
    }
}

From source file:com.sdl.odata.controller.AbstractODataController.java

/**
 * Converts an {@code HttpServletRequest} to an {@code ODataRequest}.
 *
 * @param servletRequest The {@code HttpServletRequest}.
 * @return An {@code ODataRequest} containing the request information.
 * @throws java.io.IOException If an I/O error occurs.
 */// ww w. j  a  va2 s .  com
private ODataRequest buildODataRequest(HttpServletRequest servletRequest) throws IOException {
    ODataRequest.Builder builder = new ODataRequest.Builder();

    builder.setMethod(ODataRequest.Method.valueOf(servletRequest.getMethod()));

    // Unfortunately, HttpServletRequest makes it difficult to get the full URI
    StringBuilder sb = getRequestURL(servletRequest);
    String queryString = servletRequest.getQueryString();
    if (!isNullOrEmpty(queryString)) {
        sb.append('?').append(queryString);
    }
    builder.setUri(sb.toString());

    // Unfortunately, HttpServletRequest has a very old-style API to iterate the headers
    Enumeration e = servletRequest.getHeaderNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        String value = servletRequest.getHeader(name);
        builder.setHeader(name, value);
    }

    // Read the request body
    InputStream in = servletRequest.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int count;
    byte[] buffer = new byte[BUFFER_SIZE];
    while ((count = in.read(buffer)) != -1) {
        out.write(buffer, 0, count);
    }
    builder.setBody(out.toByteArray());

    return builder.build();
}

From source file:me.smoe.lzy.filter.AccessLogFilter.java

private void logAccessAPI(HttpServletRequest request) {
    try {// www.  j  a  v a2 s.  c  o  m
        User user = (User) request.getSession().getAttribute(Constants.SESSION_USER);
        String userId = user != null ? user.getId() : "NOT_LOGIN";
        String remoteAddr = request.getRemoteAddr();
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        String userAgent = StringUtils.defaultString(request.getHeader("User-Agent"));

        String queryString = request.getQueryString();
        if (queryString != null) {
            queryString = URLDecoder.decode(request.getQueryString(), Constants.CHARSET);
        }
        requestURI = requestURI
                + (StringUtils.isNotEmpty(queryString) ? ("?" + queryString) : StringUtils.EMPTY);

        Logger.getRestAccessLogger().info(
                String.format("[%s] [%s] [%s] %s [%s]", userId, remoteAddr, method, requestURI, userAgent));
    } catch (Exception e) {
        Logger.getRestAccessLogger().warn("AccessAPI logger error: " + e.getMessage(), e);
    }
}

From source file:technology.tikal.gae.http.cache.AbstractCacheController.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    boolean next = true;
    if (request.getMethod().equals("POST") || request.getMethod().equals("DELETE")) {
        startCreateOrUpdate(request, response);
    }// ww  w. j  av a 2  s  .  c o  m
    if (request.getMethod().equals("GET") && isQueryRelated(request, response)) {
        String requestETag = request.getHeader("If-None-Match");
        if (httpCacheQueryService.validateEtag(request.getRequestURI(), requestETag)) {
            if (AbstractCacheController.LOGGER.isInfoEnabled()) {
                AbstractCacheController.LOGGER
                        .info("se pide al cliente que use el cache para el recurso:" + request.getRequestURI());
            }
            response.setStatus(304);
            next = false;
        } else {
            response.setHeader("Cache-Control", cacheControl);
            httpCacheQueryService.setEtag(request, response);
        }
    }
    return next;
}

From source file:com.devicehive.application.filter.SwaggerFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    URL requestUrl = new URL(request.getRequestURL().toString());
    logger.debug("Swagger filter triggered by '{}: {}'. Request will be redirected to swagger page",
            request.getMethod(), requestUrl);

    String swaggerJsonUrl = String.format("%s://%s:%s%s%s/swagger.json", requestUrl.getProtocol(),
            requestUrl.getHost(),/*from   www .  ja v a 2  s.  co  m*/
            requestUrl.getPort() == -1 ? requestUrl.getDefaultPort() : requestUrl.getPort(),
            request.getContextPath(), JerseyConfig.REST_PATH);
    String url = request.getContextPath() + "/swagger.html?url=" + swaggerJsonUrl;

    logger.debug("Request is being redirected to '{}'", url);
    response.sendRedirect(url);
}

From source file:net.community.chest.gitcloud.facade.backend.git.BackendUploadPackFactory.java

@Override
public UploadPack create(final C request, Repository db)
        throws ServiceNotEnabledException, ServiceNotAuthorizedException {
    final File dir = db.getDirectory();
    final String logPrefix;
    if (request instanceof HttpServletRequest) {
        HttpServletRequest req = (HttpServletRequest) request;
        logPrefix = "create(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                + "]";
    } else {//from  w  w w .  j a  va 2s.co  m
        logPrefix = "create(" + dir.getAbsolutePath() + ")";
    }
    if (logger.isDebugEnabled()) {
        logger.debug(logPrefix + ": " + dir.getAbsolutePath());
    }

    UploadPack up = new UploadPack(db) {
        @Override
        @SuppressWarnings("synthetic-access")
        public void upload(InputStream input, OutputStream output, OutputStream messages) throws IOException {
            InputStream effIn = input;
            OutputStream effOut = output, effMessages = messages;
            if (logger.isTraceEnabled()) {
                LineLevelAppender inputAppender = new LineLevelAppender() {
                    @Override
                    public void writeLineData(CharSequence lineData) throws IOException {
                        logger.trace(logPrefix + " upload(C): " + lineData);
                    }

                    @Override
                    public boolean isWriteEnabled() {
                        return true;
                    }
                };
                effIn = new TeeInputStream(effIn, new HexDumpOutputStream(inputAppender), true);

                LineLevelAppender outputAppender = new LineLevelAppender() {
                    @Override
                    public void writeLineData(CharSequence lineData) throws IOException {
                        logger.trace(logPrefix + " upload(S): " + lineData);
                    }

                    @Override
                    public boolean isWriteEnabled() {
                        return true;
                    }
                };
                effOut = new TeeOutputStream(effOut, new HexDumpOutputStream(outputAppender));

                if (effMessages != null) {
                    LineLevelAppender messagesAppender = new LineLevelAppender() {
                        @Override
                        public void writeLineData(CharSequence lineData) throws IOException {
                            logger.trace(logPrefix + " upload(M): " + lineData);
                        }

                        @Override
                        public boolean isWriteEnabled() {
                            return true;
                        }
                    };
                    // TODO review the decision to use an AsciiLineOutputStream here
                    effMessages = new TeeOutputStream(effMessages, new AsciiLineOutputStream(messagesAppender));
                }
            }

            super.upload(effIn, effOut, effMessages);
        }

        @Override
        @SuppressWarnings("synthetic-access")
        public void sendAdvertisedRefs(RefAdvertiser adv) throws IOException, ServiceMayNotContinueException {
            RefAdvertiser effAdv = adv;
            if (logger.isTraceEnabled() && (adv instanceof PacketLineOutRefAdvertiser)) {
                PacketLineOut pckOut = (PacketLineOut) ReflectionUtils.getField(pckOutField, adv);
                effAdv = new PacketLineOutRefAdvertiser(pckOut) {
                    private final PacketLineOut pckLog = new PacketLineOut( // TODO review the decision to use an AsciiLineOutputStream here
                            new AsciiLineOutputStream(new LineLevelAppender() {
                                @Override
                                public void writeLineData(CharSequence lineData) throws IOException {
                                    logger.trace(logPrefix + " S: " + lineData);
                                }

                                @Override
                                public boolean isWriteEnabled() {
                                    return true;
                                }
                            }));

                    @Override
                    protected void writeOne(CharSequence line) throws IOException {
                        String s = line.toString();
                        super.writeOne(s);
                        pckLog.writeString(s);
                    }

                    @Override
                    protected void end() throws IOException {
                        super.end();
                        pckLog.end();
                    }
                };
            }

            super.sendAdvertisedRefs(effAdv);
        }
    };
    up.setTimeout(uploadTimeoutValue);
    return up;
}

From source file:com.carfinance.core.filter.HiddenHttpMethodFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    logger.debug("@@@@@@@@@@@@@@@@@@@??@@@@@@@@@@@@@@@@@@@");
    logger.debug("@@@@@@@@@@@@@@@@@@@ " + request.getMethod().toUpperCase()
            + "@@@@@@@@@@@@@@@@@@@");
    String paramValue = request.getParameter(this.methodParam);
    if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {
        String method = paramValue.toUpperCase(Locale.ENGLISH);
        logger.debug("@@@@@@@@???" + method + "@@@@@@@@");
        HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
        filterChain.doFilter(wrapper, response);
    } else {//from w  w  w . j a  v a  2 s . c o m
        logger.debug("@@@@@@@@@@@@@@@@@@@@???@@@@@@@@@@@@@@@@@@@@");
        filterChain.doFilter(request, response);
    }
}