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.ucap.uccc.cmis.impl.atompub.CmisAtomPubServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    CallContext context = null;//w  w w . jav a2s .  c o  m
    try {
        if (METHOD_HEAD.equals(request.getMethod())) {
            request = new HEADHttpServletRequestWrapper(request);
            response = new NoBodyHttpServletResponseWrapper(response);
        } else {
            request = new QueryStringHttpServletRequestWrapper(request);
        }

        // set default headers
        response.addHeader("Cache-Control", "private, max-age=0");
        response.addHeader("Server", ServerVersion.OPENCMIS_SERVER);

        context = createContext(getServletContext(), request, response);
        dispatch(context, request, response);
    } catch (Exception e) {
        if (e instanceof CmisUnauthorizedException) {
            response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
        } else if (e instanceof CmisPermissionDeniedException) {
            if ((context == null) || (context.getUsername() == null)) {
                response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\"");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
            } else {
                response.sendError(getErrorCode((CmisPermissionDeniedException) e), e.getMessage());
            }
        } else {
            printError(e, response);
        }
    } finally {
        // we are done.
        response.flushBuffer();
    }
}

From source file:com.primeleaf.krystal.web.action.cpanel.EditDocumentClassAction.java

public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);

    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {// ww w  .  java  2 s .  co  m
            int documentClassId = 0;
            try {
                documentClassId = Integer.parseInt(
                        request.getParameter("classid") != null ? request.getParameter("classid") : "0");
            } catch (Exception e) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                return (new ManageDocumentClassesAction().execute(request, response));
            }
            String className = request.getParameter("txtClassName") != null
                    ? request.getParameter("txtClassName")
                    : "";
            String classDescription = request.getParameter("txtClassDescription") != null
                    ? request.getParameter("txtClassDescription")
                    : "";
            String visible = request.getParameter("radActive") != null ? request.getParameter("radActive")
                    : "N";
            String revisionControl = request.getParameter("radRevisionControl") != null
                    ? request.getParameter("radRevisionControl")
                    : "N";

            //24-Nov-2011 New fields added for controlling the file size and number of documents in the system
            int maximumFileSize = Integer.MAX_VALUE;
            int documentLimit = Integer.MAX_VALUE;

            //10-Sept-2012 New field added for controlling the expiry period
            int expiryPeriod = 0;

            //10-Nov-2012 New field added for controlling the accessibility of the class
            String accessType = request.getParameter("radAccessType") != null
                    ? request.getParameter("radAccessType")
                    : DocumentClass.ACCESS_TYPE_PUBLIC;

            if (!GenericValidator.maxLength(className, 50)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Document Class Name");
                return (new ManageDocumentClassesAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(classDescription, 50)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR,
                        "Value too large for Document class description");
                return (new ManageDocumentClassesAction().execute(request, response));
            }
            if (!GenericValidator.isInRange(documentLimit, 10000, 2147483647)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                return (new ManageDocumentClassesAction().execute(request, response));
            }
            try {
                expiryPeriod = request.getParameter("txtExpiryPeriod") != null
                        ? Integer.parseInt(request.getParameter("txtExpiryPeriod"))
                        : 0;
            } catch (Exception e) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                return (new ManageDocumentClassesAction().execute(request, response));
            }
            if (!GenericValidator.isInRange(expiryPeriod, 0, 9999)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                return (new ManageDocumentClassesAction().execute(request, response));
            }

            if (!"Y".equals(visible)) {
                visible = "N";
            }
            if (!"Y".equals(revisionControl)) {
                revisionControl = "N";
            }
            if (!DocumentClass.ACCESS_TYPE_USER.equals(accessType)) {
                accessType = DocumentClass.ACCESS_TYPE_PUBLIC;
            }

            DocumentClass documentClass = DocumentClassDAO.getInstance().readDocumentClassById(documentClassId);

            if (documentClass == null) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR,
                        "Document class with same name already exist");
                return (new ManageDocumentClassesAction().execute(request, response));
            }
            //Validate document class name if a class name has changed then check if the similar named class already exist in the database
            if (!documentClass.getClassName().equalsIgnoreCase(className)) {
                boolean isDocumentClassExist = DocumentClassDAO.getInstance().validateDocumentClass(className);
                if (isDocumentClassExist) {
                    request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Document Class");
                    return (new ManageDocumentClassesAction().execute(request, response));
                }
            }

            documentClass.setClassId((short) documentClassId);
            documentClass.setClassName(className);
            documentClass.setClassDescription(classDescription);

            //24-Nov-2011 New fields added for controlling the file size and number of documents in the system
            documentClass.setMaximumFileSize(maximumFileSize);
            documentClass.setDocumentLimit(documentLimit);

            if ("Y".equals(visible)) {
                documentClass.setVisible(true);
            } else {
                documentClass.setVisible(false);
            }

            if ("Y".equals(revisionControl)) {
                documentClass.setRevisionControlEnabled(true);
            } else {
                documentClass.setRevisionControlEnabled(false);
            }

            documentClass.setExpiryPeriod(expiryPeriod); //10-Sep-2012 Rahul Kubadia
            documentClass.setExpiryNotificationPeriod(-1);//08-May-2014 Rahul Kubadia

            DocumentClassDAO.getInstance().updateDocumentClass(documentClass);

            AuditLogManager.log(new AuditLogRecord(documentClass.getClassId(),
                    AuditLogRecord.OBJECT_DOCUMENTCLASS, AuditLogRecord.ACTION_EDITED,
                    loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO,
                    "ID : " + documentClass.getClassId(), "Name : " + documentClass.getClassName()));
            request.setAttribute(HTTPConstants.REQUEST_MESSAGE,
                    "Document class " + className + " updated successfully");
            return (new ManageDocumentClassesAction().execute(request, response));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        int documentClassId = 0;
        try {
            documentClassId = Integer
                    .parseInt(request.getParameter("classid") != null ? request.getParameter("classid") : "0");
        } catch (Exception e) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
            return (new ManageDocumentClassesAction().execute(request, response));
        }
        DocumentClass documentClass = DocumentClassDAO.getInstance().readDocumentClassById(documentClassId);
        if (documentClass == null) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Document Class");
            return (new ManageDocumentClassesAction().execute(request, response));
        }
        request.setAttribute("DOCUMENTCLASS", documentClass);
    }
    return (new EditDocumentClassView(request, response));
}

From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java

private void prepareHttpMethod(HttpServletRequest servletReq) throws IOException {

    if (servletReq.getMethod().equalsIgnoreCase("GET")) {
        prepareGetMethod(servletReq);//  w  w w  .  j  a  v a  2s  .c o  m
    } else if (servletReq.getMethod().equalsIgnoreCase("POST")) {
        preparePostMethod(servletReq);
    } else {
        throw new IOException("Unsupport HTTP method: " + servletReq.getMethod());
    }

    httpStatusCode = 0;
    responseHeaderMap = null;
}

From source file:com.acc.storefront.interceptors.beforeview.SeoRobotsFollowBeforeViewHandler.java

@Override
public void beforeView(final HttpServletRequest request, final HttpServletResponse response,
        final ModelAndView modelAndView) {
    // Check to see if the controller has specified a Index/Follow directive for robots
    if (modelAndView != null && !modelAndView.getModel().containsKey("metaRobots")) {
        // Build a default directive
        String robotsValue = "no-index,no-follow";

        if (RequestMethod.GET.name().equalsIgnoreCase(request.getMethod())) {
            if (request.isSecure()) {
                robotsValue = "no-index,follow";
            }//from  w w w .  j a  va 2s. c  o m
            //Since no model attribute metaRobots can be set for JSON response, then configure that servlet path in the xml.
            //If its a regular response and this setting has to be overriden then set model attribute metaRobots
            else if (CollectionUtils.contains(getRobotIndexForJSONMapping().keySet().iterator(),
                    request.getServletPath())) {
                robotsValue = getRobotIndexForJSONMapping().get(request.getServletPath());
            } else {
                robotsValue = "index,follow";
            }
        } else if (RequestMethod.POST.name().equalsIgnoreCase(request.getMethod())) {
            robotsValue = "no-index,no-follow";
        }

        modelAndView.addObject("metaRobots", robotsValue);
    }

    if (modelAndView != null && modelAndView.getModel().containsKey("metatags")) {
        final MetaElementData metaElement = new MetaElementData();
        metaElement.setName("robots");
        metaElement.setContent((String) modelAndView.getModel().get("metaRobots"));
        ((List<MetaElementData>) modelAndView.getModel().get("metatags")).add(metaElement);
    }
}

From source file:mobi.jenkinsci.ci.JenkinsCIPlugin.java

private HttpRequestBase getNewHttpRequest(final HttpServletRequest req, final String url) throws IOException {
    HttpRequestBase newReq = null;//  w  w w. ja  va 2s.com
    if (req == null || req.getMethod().equalsIgnoreCase("get")) {
        newReq = new HttpGet(url);
    } else {
        final HttpPost post = new HttpPost(url);
        final ByteArrayOutputStream reqBody = new ByteArrayOutputStream();
        copyHeaders(post, req);
        IOUtils.copy(req.getInputStream(), reqBody);
        post.setEntity(new ByteArrayEntity(reqBody.toByteArray()));
        newReq = post;
    }

    return newReq;
}

From source file:name.martingeisse.api.request.ApiRequestCycle.java

/**
 * Constructor./*ww  w . j a v a 2  s  .co m*/
 * @param request the request
 * @param response the response
 * @throws MalformedRequestPathException if the request path (taken from the request URI) is malformed
 */
public ApiRequestCycle(final HttpServletRequest request, final HttpServletResponse response)
        throws MalformedRequestPathException {
    this.request = request;
    this.response = response;

    this.requestMethod = (request.getMethod().equalsIgnoreCase("POST") ? ApiRequestMethod.POST
            : ApiRequestMethod.GET);
    final String uri = request.getRequestURI();
    final String requestPathText = (uri.startsWith("/") ? uri.substring(1) : uri);
    this.requestPath = ApiRequestPathChain.parse(requestPathText);
    this.parameters = new ApiRequestParameters(request);
    this.attributes = new HashMap<ApiRequestAttributeKey<?>, Object>();

}

From source file:com.exxonmobile.ace.hybris.storefront.interceptors.beforeview.SeoRobotsFollowBeforeViewHandler.java

@Override
public void beforeView(final HttpServletRequest request, final HttpServletResponse response,
        final ModelAndView modelAndView) {
    // Check to see if the controller has specified a Index/Follow directive for robots
    if (modelAndView != null && !modelAndView.getModel().containsKey("metaRobots")) {
        // Build a default directive
        String robotsValue = "no-index,no-follow";

        if (RequestMethod.GET.name().equalsIgnoreCase(request.getMethod())) {
            if (request.isSecure()) {
                robotsValue = "no-index,follow";
            }/*from   w  w w  .j  a v a  2s.c om*/
            //Since no model attribute metaRobots can be set for JSON response, then configure that servlet path in the xml.
            //If its a regular response and this setting has to be overriden then set model attribute metaRobots
            else if (CollectionUtils.contains(getRobotIndexForJSONMapping().keySet().iterator(),
                    request.getServletPath())) {
                robotsValue = getRobotIndexForJSONMapping().get(request.getServletPath());
            } else {
                robotsValue = "index,follow";
            }
        } else if (RequestMethod.POST.name().equalsIgnoreCase(request.getMethod())) {
            robotsValue = "no-index,no-follow";
        }

        modelAndView.addObject("metaRobots", robotsValue);

    }

    if (modelAndView != null && modelAndView.getModel().containsKey("metatags")) {
        final MetaElementData metaElement = new MetaElementData();
        metaElement.setName("robots");
        metaElement.setContent((String) modelAndView.getModel().get("metaRobots"));
        ((List<MetaElementData>) modelAndView.getModel().get("metatags")).add(metaElement);
    }
}

From source file:org.apache.hadoop.gateway.AuditLoggingTest.java

@Test
/**//from   ww w  .j av  a 2  s .  c  o  m
 * Empty filter chain. Two events with same correlation ID are expected:
 * 
 * action=access request_type=uri outcome=unavailable
 * action=access request_type=uri outcome=success message=Response status: 404
 */
public void testNoFiltersAudit() throws ServletException, IOException {
    FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
    EasyMock.replay(config);

    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
    GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(request.getMethod()).andReturn(METHOD).anyTimes();
    EasyMock.expect(request.getPathInfo()).andReturn(PATH).anyTimes();
    EasyMock.expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    EasyMock.expect(request.getRemoteAddr()).andReturn(ADDRESS).anyTimes();
    EasyMock.expect(request.getRemoteHost()).andReturn(HOST).anyTimes();
    EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes();
    EasyMock.expect(context.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(gatewayConfig)
            .anyTimes();
    EasyMock.expect(gatewayConfig.getHeaderNameForRemoteAddress()).andReturn("Custom-Forwarded-For").anyTimes();
    EasyMock.replay(request);
    EasyMock.replay(context);
    EasyMock.replay(gatewayConfig);

    HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.replay(response);

    FilterChain chain = EasyMock.createNiceMock(FilterChain.class);
    EasyMock.replay(chain);

    GatewayFilter gateway = new GatewayFilter();
    gateway.init(config);
    gateway.doFilter(request, response, chain);
    gateway.destroy();

    assertThat(CollectAppender.queue.size(), is(1));
    Iterator<LoggingEvent> iterator = CollectAppender.queue.iterator();
    LoggingEvent accessEvent = iterator.next();
    verifyAuditEvent(accessEvent, CONTEXT_PATH + PATH, ResourceType.URI, Action.ACCESS,
            ActionOutcome.UNAVAILABLE, null, "Request method: GET");
}

From source file:com.microsoft.applicationinsights.web.spring.RequestNameHandlerInterceptorAdapter.java

private String generateRequestName(HttpServletRequest request, Object handler) {

    // Some handlers, such as built-in ResourceHttpRequestHandler are not of type HandlerMethod.
    if (!(handler instanceof HandlerMethod)) {
        return null;
    }//from www  .  j  a  v a 2 s  . com

    HandlerMethod handlerMethod = (HandlerMethod) handler;
    String controller = handlerMethod.getBeanType().getSimpleName();
    String action = handlerMethod.getMethod().getName();

    String method = request.getMethod();

    return String.format("%s %s/%s", method, controller, action);
}

From source file:eu.freme.broker.tools.internationalization.EInternationalizationFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) {
        chain.doFilter(req, res);/*from   www  .  java  2  s  . c  om*/
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) req;
    HttpServletResponse httpResponse = (HttpServletResponse) res;

    if (httpRequest.getMethod().equals("OPTIONS")) {
        chain.doFilter(req, res);
        return;
    }

    String uri = httpRequest.getRequestURI();
    for (Pattern pattern : endpointBlacklistRegex) {
        if (pattern.matcher(uri).matches()) {
            chain.doFilter(req, res);
            return;
        }
    }

    String informat = getInformat(httpRequest);
    String outformat = getOutformat(httpRequest);

    if (outformat != null && (informat == null || !outformat.equals(informat))) {
        Exception exception = new BadRequestException("Can only convert to outformat \"" + outformat
                + "\" when informat is also \"" + outformat + "\"");
        exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception);
        return;
    }

    if (outformat != null && !outputFormats.contains(outformat)) {
        Exception exception = new BadRequestException("\"" + outformat + "\" is not a valid output format");
        exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception);
        return;
    }

    if (informat == null) {
        chain.doFilter(req, res);
        return;
    }

    boolean roundtripping = false;
    if (outformat != null) {
        roundtripping = true;
        logger.debug("convert from " + informat + " to " + outformat);
    } else {
        logger.debug("convert input from " + informat + " to nif");
    }

    // do conversion of informat to nif
    // create BodySwappingServletRequest

    String inputQueryString = req.getParameter("input");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try (InputStream requestInputStream = inputQueryString == null ? /*
                                                                     * read
                                                                     * data
                                                                     * from
                                                                     * request
                                                                     * body
                                                                     */req.getInputStream()
            : /*
              * read data from query string input
              * parameter
              */new ReaderInputStream(new StringReader(inputQueryString), "UTF-8")) {
        // copy request content to buffer
        IOUtils.copy(requestInputStream, baos);
    }

    // create request wrapper that converts the body of the request from the
    // original format to turtle
    Reader nif;

    byte[] baosData = baos.toByteArray();
    if (baosData.length == 0) {
        Exception exception = new BadRequestException("No input data found in request.");
        exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception);
        return;
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(baosData);
    try {
        nif = eInternationalizationApi.convertToTurtle(bais, informat.toLowerCase());
    } catch (ConversionException e) {
        logger.error("Error", e);
        throw new InternalServerErrorException("Conversion from \"" + informat + "\" to NIF failed");
    }

    BodySwappingServletRequest bssr = new BodySwappingServletRequest((HttpServletRequest) req, nif,
            roundtripping);

    if (!roundtripping) {
        chain.doFilter(bssr, res);
        return;
    }

    ConversionHttpServletResponseWrapper dummyResponse;

    try {
        dummyResponse = new ConversionHttpServletResponseWrapper(httpResponse, eInternationalizationApi,
                new ByteArrayInputStream(baosData), informat, outformat);

        chain.doFilter(bssr, dummyResponse);

        ServletOutputStream sos = httpResponse.getOutputStream();

        byte[] data = dummyResponse.writeBackToClient();
        httpResponse.setContentLength(data.length);
        sos.write(data);
        sos.flush();
        sos.close();

    } catch (ConversionException e) {
        e.printStackTrace();
        // exceptionHandlerService.writeExceptionToResponse((HttpServletResponse)res,new
        // InternalServerErrorException());
    }
}