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.mnt.base.web.servlets.AccessRouterServlet.java

@SuppressWarnings("unchecked")
@Override//from w  ww  .  java 2s  . co  m
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    WebUtils.setupContext(req, resp);

    if (!WebUtils.checkAuth(req, resp)) {
        return;
    }

    String reqMethod = req.getMethod();
    String requestUri = req.getRequestURI();
    Map<String, Object> parameterMap = null;

    String contentType = req.getHeader("content-type");

    if (HTTP_GET.equalsIgnoreCase(reqMethod) || HTTP_DELETE.equalsIgnoreCase(reqMethod)
            || HTTP_HEAD.equalsIgnoreCase(reqMethod) || !"application/json".equalsIgnoreCase(contentType)) {
        parameterMap = new LinkedHashMap<String, Object>();
        parameterMap.putAll(req.getParameterMap());
    } else {
        String requestContent = null;
        try {
            requestContent = HttpUtil.readData(req.getInputStream());
        } catch (IOException e) {
            log.error("Fail to read the http request content. SKIP the request.", e);
            resp.getOutputStream().close();
            return;
        }

        if (!CommonUtil.isEmpty(requestContent)) {
            try {
                parameterMap = (Map<String, Object>) JSONTool.convertJsonToObject(requestContent);
            } catch (Exception e) {
                if (log.isDebugEnabled()) {
                    log.debug("Fail to convert the json string to parameter map. SKIP the request: "
                            + requestContent, e);
                }

                InvalidPostHandler invalidPostHandler = null;

                try {
                    invalidPostHandler = BeanContext.getInstance().getBean("invalidPostHandler",
                            InvalidPostHandler.class);
                } catch (Exception skipe) {
                    // skip it
                }

                if (invalidPostHandler != null) {
                    try {
                        invalidPostHandler.handle(req, resp, requestContent);
                    } catch (Exception e1) {
                        log.error("error while handle invalid post request.", e);
                    }
                } else {
                    resp.getOutputStream().close();
                }
                return;
            }
        } else {
            parameterMap = new LinkedHashMap<String, Object>();
        }
    }

    actionControllerManager.dispatchRequest(requestUri, req.getMethod(), parameterMap,
            new HTMLResponseHandler(resp, BaseConfiguration.getResponseContentType()));
    CommonUtil.deepClear(parameterMap);

    WebUtils.clearContext();
}

From source file:com.castlemock.war.config.LoggingInterceptor.java

/**
 * The method handles incoming requests and logs them if debug mode is enabled. The method will log the following
 * things:// w ww .ja v  a 2  s .  c om
 *  1. The request URI
 *  2. The request method
 *  3. The controller responsible for handling the request
 * @param request The incoming request. The request will be parsed and logged
 * @param response The outgoing response
 * @param handler The handler contains information about the method and controller that has processed the incoming request
 * @param exception Outgoing exception
 * @see AbstractController
 */
@Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final Exception exception) {
    if (LOGGER.isDebugEnabled()) {
        final StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("Finished processing the following request: " + request.getRequestURI() + " ("
                + request.getMethod() + ").");
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            stringBuilder.append("This request was processed by the following controller: "
                    + handlerMethod.getBeanType().getSimpleName());
        }
        LOGGER.debug(stringBuilder.toString());
    }
}

From source file:de.adorsys.oauth.authdispatcher.matcher.BasicAuthAuthenticatorMatcher.java

@Override
public ValveBase match(HttpServletRequest request, AuthorizationRequest authorizationRequest) {
    // Real basic auth header
    if (isBasicAuthentication(request)) {
        return valve;
    }//from   www .j  a v a 2 s.  c o m

    // Deals only with POST Requests. So no need to match others.
    // @See com.nimbusds.oauth2.sdk.TokenRequest.parse(HTTPRequest)
    if (!StringUtils.equalsIgnoreCase("POST", request.getMethod())) {
        return null;
    }

    try {
        TokenRequest tokenRequest = TokenRequest.parse(FixedServletUtils.createHTTPRequest(request));
        if (tokenRequest.getAuthorizationGrant().getType() == GrantType.PASSWORD) {
            return valve;
        }
    } catch (Exception e) {
        // ignore silent
    }

    return null;
}

From source file:it.geosolutions.httpproxy.service.impl.ProxyHelperImpl.java

/**
 * Prepare a proxy method execution//from   ww  w .j  av a  2  s .c o  m
 * 
 * @param httpServletRequest
 * @param httpServletResponse
 * @param proxy
 * 
 * @return ProxyMethodConfig to execute the method
 * 
 * @throws IOException
 * @throws ServletException
 */
public ProxyMethodConfig prepareProxyMethod(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, ProxyService proxy) throws IOException, ServletException {
    URL url = null;
    String user = null, password = null;
    Map<?, ?> pars;
    String method = httpServletRequest.getMethod();

    if (HttpMethods.METHOD_GET.equals(method)) {
        // Obtain pars from parameter map
        pars = httpServletRequest.getParameterMap();
    } else {
        //Parse the queryString to not read the request body calling getParameter from httpServletRequest
        // so the method can simply forward the request body
        pars = splitQuery(httpServletRequest.getQueryString());
    }

    // Obtain ProxyMethodConfig from pars
    for (Object key : pars.keySet()) {

        String value = (pars.get(key) instanceof String) ? (String) pars.get(key)
                : ((String[]) pars.get(key))[0];

        if ("user".equals(key)) {
            user = value;
        } else if ("password".equals(key)) {
            password = value;
        } else if ("url".equals(key)) {
            url = new URL(value);
        }
    }

    // get url from the attribute if present
    if (url == null) {
        String urlString = (String) httpServletRequest.getAttribute("url");
        if (urlString != null)
            url = new URL(urlString);
    }

    if (url != null) {
        // init and return the config
        proxy.onInit(httpServletRequest, httpServletResponse, url);
        return new ProxyMethodConfig(url, user, password, method);
    } else {
        return null;
    }
}

From source file:org.mocksy.rules.http.HttpProxyRule.java

protected HttpRequestBase getProxyMethod(HttpServletRequest request) {
    String proxyUrl = this.proxyUrl;
    proxyUrl += request.getPathInfo();// ww  w  .j  a va2 s  .com
    if (request.getQueryString() != null) {
        proxyUrl += "?" + request.getQueryString();
    }
    HttpRequestBase method = null;
    if ("GET".equals(request.getMethod())) {
        method = new HttpGet(proxyUrl);
        method.addHeader("Cache-Control", "no-cache");
        method.addHeader("Pragma", "no-cache");
    } else if ("POST".equals(request.getMethod())) {
        method = new HttpPost(proxyUrl);

        Map<String, String[]> paramMap = request.getParameterMap();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String paramName : paramMap.keySet()) {
            String[] values = paramMap.get(paramName);
            for (String value : values) {
                NameValuePair param = new BasicNameValuePair(paramName, value);
                params.add(param);
            }
        }

        try {
            ((HttpPost) method).setEntity(new UrlEncodedFormEntity(params));
        } catch (UnsupportedEncodingException e) {
            // don't worry, this won't happen
        }
    }

    Enumeration headers = request.getHeaderNames();
    while (headers.hasMoreElements()) {
        String header = (String) headers.nextElement();
        if ("If-Modified-Since".equals(header) || "Content-Length".equals(header)
                || "Transfer-Encoding".equals(header))
            continue;
        Enumeration values = request.getHeaders(header);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            method.addHeader(header, value);
        }
    }

    return method;
}

From source file:fi.okm.mpass.shibboleth.profile.impl.BuildMetaRestResponse.java

/** {@inheritDoc} */
@Override/*from   w  w  w .  ja  v a2 s  .c  om*/
@Nonnull
public Event execute(@Nonnull final RequestContext springRequestContext) {
    ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this);
    final HttpServletRequest httpRequest = getHttpServletRequest();
    pushHttpResponseProperties();
    final HttpServletResponse httpResponse = getHttpServletResponse();

    try {
        final Writer out = new OutputStreamWriter(httpResponse.getOutputStream(), "UTF-8");

        if (!HttpMethod.GET.toString().equals(httpRequest.getMethod())) {
            log.warn("{}: Unsupported method attempted {}", getLogPrefix(), httpRequest.getMethod());
            out.append(makeErrorResponse(HttpStatus.SC_METHOD_NOT_ALLOWED,
                    httpRequest.getMethod() + " not allowed", "Only GET is allowed"));
        } else if (metaDTO != null) {
            final Gson gson = new Gson();
            out.append(gson.toJson(getMetaDTO()));
            httpResponse.setStatus(HttpStatus.SC_OK);
        } else {
            out.append(
                    makeErrorResponse(HttpStatus.SC_NOT_IMPLEMENTED, "Not implemented on the server side", ""));
        }
        out.flush();
    } catch (IOException e) {
        log.error("{}: Could not encode the JSON response", getLogPrefix(), e);
        httpResponse.setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE);
        return ActionSupport.buildEvent(this, EventIds.IO_ERROR);
    }
    return ActionSupport.buildProceedEvent(this);
}

From source file:com.primeleaf.krystal.web.action.cpanel.NewDocumentClassAction.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 {// w  ww.j  av  a  2s .co m
            String className = request.getParameter("txtClassName") != null
                    ? request.getParameter("txtClassName")
                    : "";
            String classDescription = request.getParameter("txtClassDescription") != null
                    ? request.getParameter("txtClassDescription")
                    : "";
            String isRevCtl = request.getParameter("radRevisionControl") != null
                    ? request.getParameter("radRevisionControl")
                    : "N";
            String active = request.getParameter("radActive") != null ? request.getParameter("radActive") : "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-Sep-2012 New field added for controlling the expiry period of the doucment
            int expiryPeriod = 0;

            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));
            }
            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(active)) {
                active = "N";
            }
            if (!"Y".equals(isRevCtl)) {
                isRevCtl = "N";
            }

            boolean isDocumentClassExist = DocumentClassDAO.getInstance().validateDocumentClass(className);

            if (isDocumentClassExist) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR,
                        "Document class " + className + " already exist");
                return (new ManageDocumentClassesAction().execute(request, response));
            }

            DocumentClass documentClass = new DocumentClass();
            documentClass.setClassName(className);
            documentClass.setClassDescription(classDescription);

            if (isRevCtl.equals("Y")) {
                documentClass.setRevisionControlEnabled(true);
            } else {
                documentClass.setRevisionControlEnabled(false);
            }
            if (active.equals("Y")) {
                documentClass.setVisible(true);
            } else {
                documentClass.setVisible(false);
            }
            documentClass.setIndexId(-1);

            documentClass.setIndexCount(0);

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

            documentClass.setCreatedBy(loggedInUser.getUserName());

            documentClass.setDataTableName("");

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

            ArrayList<IndexDefinition> indexDefinitions = new ArrayList<IndexDefinition>();
            documentClass.setIndexDefinitions(indexDefinitions);
            DocumentClassDAO.getInstance().addDocumentClass(documentClass);

            AuditLogManager.log(new AuditLogRecord(documentClass.getClassId(),
                    AuditLogRecord.OBJECT_DOCUMENTCLASS, AuditLogRecord.ACTION_CREATED,
                    loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO,
                    "ID : " + documentClass.getClassId(), "Name : " + documentClass.getClassName()));
            request.setAttribute(HTTPConstants.REQUEST_MESSAGE,
                    "Document class " + className + " added successfully");
            return (new ManageDocumentClassesAction().execute(request, response));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return (new NewDocumentClassView(request, response));
}

From source file:photosharing.api.conx.UploadFileDefinition.java

/**
 * manages upload file definition/*from   w  ww  .j ava 2 s  . c  om*/
 * 
 * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void run(HttpServletRequest request, HttpServletResponse response) {
    // HTTP Method that the request was made with:
    String method = request.getMethod();

    /**
     * get the users bearer token
     */
    HttpSession session = request.getSession(false);
    OAuth20Data data = (OAuth20Data) session.getAttribute(OAuth20Handler.CREDENTIALS);
    String bearer = data.getAccessToken();

    // Create a Comment
    if (method.compareTo("POST") == 0) {
        String nonce = getNonce(bearer, response);
        if (!nonce.isEmpty()) {
            uploadFile(bearer, nonce, request, response);
        }
    } else {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
    }

}

From source file:com.platform.middlewares.plugins.WalletPlugin.java

@Override
public boolean handle(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) {//from w w w.  jav  a  2s . c om
    if (!target.startsWith("/_wallet"))
        return false;

    if (target.startsWith("/_wallet/info") && request.getMethod().equalsIgnoreCase("get")) {
        Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
        final MainActivity app = MainActivity.app;
        if (app == null) {
            Log.e(TAG, "handle: context is null: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(500, "context is null", baseRequest, response);
        }
        BRWalletManager wm = BRWalletManager.getInstance(app);
        JSONObject jsonResp = new JSONObject();
        try {
            jsonResp.put("no_wallet", wm.noWalletForPlatform(app));
            jsonResp.put("watch_only", false);
            jsonResp.put("receive_address", BRWalletManager.getReceiveAddress());
            return BRHTTPHelper.handleSuccess(200, jsonResp.toString().getBytes(), baseRequest, response, null);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e(TAG, "handle: json error: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(500, "json error", baseRequest, response);
        }

    } else if (target.startsWith("/_wallet/format") && request.getMethod().equalsIgnoreCase("get")) {
        Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
        String amount = request.getParameter("amount");
        if (Utils.isNullOrEmpty(amount)) {
            Log.e(TAG, "handle: amount is not specified: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(400, null, baseRequest, response);
        }
        long satAmount;

        if (amount.contains(".")) {
            // assume full bitcoins
            satAmount = new BigDecimal(amount).multiply(new BigDecimal("100000000")).longValue();
        } else {
            satAmount = Long.valueOf(amount);
        }
        return BRHTTPHelper.handleSuccess(200, BRStringFormatter
                .getFormattedCurrencyString(Locale.getDefault().getISO3Language(), satAmount).getBytes(),
                baseRequest, response, null);
    } else if (target.startsWith("/_wallet/sign_bitid") && request.getMethod().equalsIgnoreCase("post")) {
        Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
        /**
         * POST /_wallet/sign_bitid
                
         Sign a message using the user's BitID private key. Calling this WILL trigger authentication
                
         Request body: application/json
         {
         "prompt_string": "Sign in to My Service", // shown to the user in the authentication prompt
         "string_to_sign": "https://bitid.org/bitid?x=2783408723", // the string to sign
         "bitid_url": "https://bitid.org/bitid", // the bitid url for deriving the private key
         "bitid_index": "0" // the bitid index as a string (just pass "0")
         }
                
         Response body: application/json
         {
         "signature": "oibwaeofbawoefb" // base64-encoded signature
         }
         */
        final MainActivity app = MainActivity.app;
        if (app == null) {
            Log.e(TAG, "handle: context is null: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(500, "context is null", baseRequest, response);
        }
        String contentType = request.getHeader("content-type");
        if (contentType == null || !contentType.equalsIgnoreCase("application/json")) {
            Log.e(TAG,
                    "handle: content type is not application/json: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(400, null, baseRequest, response);
        }
        String reqBody = null;
        try {
            reqBody = new String(IOUtils.toByteArray(request.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Utils.isNullOrEmpty(reqBody)) {
            Log.e(TAG, "handle: reqBody is empty: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(400, null, baseRequest, response);
        }

        try {
            JSONObject obj = new JSONObject(reqBody);
            continuation = ContinuationSupport.getContinuation(request);
            continuation.suspend(response);
            globalBaseRequest = baseRequest;
            RequestHandler.tryBitIdUri(app, obj.getString("bitid_url"), obj);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e(TAG, "handle: Failed to parse Json request body: " + target + " " + baseRequest.getMethod());
            return true;
        }

        return true;
    }

    Log.e(TAG, "handle: WALLET PLUGIN DID NOT HANDLE: " + target + " " + baseRequest.getMethod());
    return true;
}

From source file:com.radutoader.archetype.web.filters.RewriteRule.java

@Override
public RewriteMatch matches(HttpServletRequest request, HttpServletResponse response) {

    if (true)// deactivate
        return null;

    // return null if we don't want the request
    if (request.getHeader("upgrade") != null) {// its case insensitive
        return null;
    }//from  w  w  w  .j av  a2 s .  c  o m

    if (RequestMethod.POST.toString().equalsIgnoreCase(request.getMethod()))
        return null;

    if (request.getRequestURI().startsWith(request.getContextPath() + "/j_"))
        return null;

    if (request.getRequestURI().startsWith(request.getContextPath() + "/static"))
        return null;
    if (request.getRequestURI().startsWith(request.getContextPath() + "/resou"))
        return null;

    if (request.getRequestURI().endsWith("/") //
            || request.getRequestURI().endsWith(".mp3") || request.getRequestURI().endsWith(".js")
            || request.getRequestURI().endsWith(".mp4") || request.getRequestURI().endsWith(".mpeg")
            || request.getRequestURI().endsWith(".webm") || request.getRequestURI().endsWith(".ogg")
            || request.getRequestURI().endsWith(".acc") || request.getRequestURI().endsWith(".wav")
            || request.getRequestURI().endsWith(".avi") || request.getRequestURI().endsWith(".css")
            || request.getRequestURI().endsWith(".html") || request.getRequestURI().endsWith(".htm")
            || request.getRequestURI().endsWith(".swf") || request.getRequestURI().endsWith(".do")
            || request.getRequestURI().endsWith(".json") || request.getRequestURI().endsWith(".txt")
            || request.getRequestURI().endsWith(".ejs") || request.getRequestURI().endsWith(".woff")
            || request.getRequestURI().endsWith(".ttf") || request.getRequestURI().endsWith(".png")
            || request.getRequestURI().endsWith(".jpg") || request.getRequestURI().endsWith(".jpeg")
            || request.getRequestURI().endsWith(".gif") || request.getRequestURI().endsWith(".php")
            || request.getRequestURI().endsWith(".xls") || request.getRequestURI().endsWith(".xlsx")
            || request.getRequestURI().endsWith(".pdf") || request.getRequestURI().endsWith(".gz")
            || request.getRequestURI().endsWith(".xml") || request.getRequestURI().endsWith(".page")
            || request.getRequestURI().endsWith(".ico") || request.getRequestURI().endsWith(".map"))
        return null;

    String url = null;
    String queryString = null;
    try {
        // grab the things out of the url we need
        url = request.getRequestURI();
        queryString = request.getQueryString();
    } catch (NumberFormatException e) {
        // if we don't get a good id then return null
        return null;
    }

    // match required with clean parameters
    return new RewriteMatch(url, queryString);
}