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.tc.utils.XSPUtils.java

public static boolean isGet() {
    HttpServletRequest req = XSPUtils.getRequest();
    return "GET".equals(req.getMethod());
}

From source file:com.tc.utils.XSPUtils.java

public static boolean isPost() {
    HttpServletRequest req = XSPUtils.getRequest();
    return "POST".equals(req.getMethod());
}

From source file:com.zimbra.cs.servlet.util.CsrfUtil.java

/**
 *
 * @param req/*from   www. j a va2 s  .  co  m*/
 * @param allowedRefHost
 * @return
 * @throws MalformedURLException
 */
public static boolean isCsrfRequestBasedOnReferrer(final HttpServletRequest req, final String[] allowedRefHost)
        throws MalformedURLException {

    List<String> allowedRefHostList = Arrays.asList(allowedRefHost);
    boolean csrfReq = false;

    String method = req.getMethod();
    if (!method.equalsIgnoreCase("POST")) {
        csrfReq = false;
        return csrfReq;
    }

    String host = getRequestHost(req);
    String referrer = req.getHeader(HttpHeaders.REFERER);
    String refHost = null;

    if (!StringUtil.isNullOrEmpty(referrer)) {
        URL refURL = null;
        if (referrer.contains("http") || referrer.contains("https")) {
            refURL = new URL(referrer);
        } else {
            refURL = new URL("http://" + referrer);
        }
        refHost = refURL.getHost().toLowerCase();
    }

    if (refHost == null) {
        csrfReq = false;
    } else if (refHost.equalsIgnoreCase(host)) {
        csrfReq = false;
    } else {
        if (allowedRefHost != null && allowedRefHostList.contains(refHost)) {
            csrfReq = false;
        } else {
            csrfReq = true;
        }
    }

    if (ZimbraLog.soap.isDebugEnabled()) {
        ZimbraLog.soap.debug("Host : %s, Referrer host :%s, Allowed Hosts:[%s] Soap req is %s", host, refHost,
                Joiner.on(',').join(allowedRefHostList), (csrfReq ? " not allowed." : " allowed."));
    }

    return csrfReq;
}

From source file:net.yacy.http.ProxyHandler.java

public final static synchronized void logProxyAccess(HttpServletRequest request) {

    final StringBuilder logMessage = new StringBuilder(80);

    // Timestamp//from  w ww.  j a v  a 2  s  .  c o m
    logMessage.append(GenericFormatter.SHORT_SECOND_FORMATTER.format(new Date()));
    logMessage.append(' ');

    // Remote Host
    final String clientIP = request.getRemoteAddr();
    logMessage.append(clientIP);
    logMessage.append(' ');

    // Method
    final String requestMethod = request.getMethod();
    logMessage.append(requestMethod);
    logMessage.append(' ');

    // URL
    logMessage.append(request.getRequestURL());
    final String requestArgs = request.getQueryString();
    if (requestArgs != null) {
        logMessage.append("?").append(requestArgs);
    }

    HTTPDProxyHandler.proxyLog.fine(logMessage.toString());

}

From source file:org.frontcache.core.FCUtils.java

/**
 * /*from   w ww  .jav a2 s.co  m*/
 * @param request
 * @return
 */
public static String getRequestURL(HttpServletRequest request) {
    String requestURL = request.getRequestURL().toString();

    if ("GET".equals(request.getMethod())) {
        // add parameters for storing 
        // POST method parameters are not stored because they can be huge (e.g. file upload)
        StringBuffer sb = new StringBuffer(requestURL);
        if (!request.getParameterMap().isEmpty())
            sb.append("?").append(request.getQueryString());

        requestURL = sb.toString();
    }
    return requestURL;
}

From source file:com.easyjf.web.core.FrameworkEngine.java

/**
 * ?requestform/*  w  ww  . j a va 2 s. c o  m*/
 * 
 * @param request
 * @param formName
 * @return ??Form
 */
public static WebForm creatWebForm(HttpServletRequest request, String formName, Module module) {
    Map textElement = new HashMap();
    Map fileElement = new HashMap();
    String contentType = request.getContentType();
    String reMethod = request.getMethod();
    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))
            && (reMethod.equalsIgnoreCase("post"))) {
        //  multipart/form-data
        File file = new File(request.getSession().getServletContext().getRealPath("/temp"));
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(webConfig.getUploadSizeThreshold());
        factory.setRepository(file);
        ServletFileUpload sf = new ServletFileUpload(factory);
        sf.setSizeMax(webConfig.getMaxUploadFileSize());
        sf.setHeaderEncoding(request.getCharacterEncoding());
        List reqPars = null;
        try {
            reqPars = sf.parseRequest(request);
            for (int i = 0; i < reqPars.size(); i++) {
                FileItem it = (FileItem) reqPars.get(i);
                if (it.isFormField()) {
                    textElement.put(it.getFieldName(), it.getString(request.getCharacterEncoding()));// ??
                } else {
                    fileElement.put(it.getFieldName(), it);// ???
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
    } else if ((contentType != null) && contentType.equals("text/xml")) {
        StringBuffer buffer = new StringBuffer();
        try {
            String s = request.getReader().readLine();
            while (s != null) {
                buffer.append(s + "\n");
                s = request.getReader().readLine();
            }
        } catch (Exception e) {
            logger.error(e);
        }
        textElement.put("xml", buffer.toString());
    } else {
        textElement = request2map(request);
    }
    // logger.debug("????");
    WebForm wf = findForm(formName);
    wf.setValidate(module.isValidate());// ?validate?Form
    if (wf != null) {
        wf.setFileElement(fileElement);
        wf.setTextElement(textElement);
    }
    return wf;
}

From source file:grails.converters.XML.java

/**
 * Parses the give XML (read from the POST Body of the Request)
 *
 * @param request an HttpServletRequest/*from   w w  w. ja v a2s.c  o m*/
 * @return a groovy.util.XmlSlurper
 * @throws ConverterException
 */
public static Object parse(HttpServletRequest request) throws ConverterException {
    Object xml = request.getAttribute(CACHED_XML);
    if (xml != null)
        return xml;

    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = Converter.DEFAULT_REQUEST_ENCODING;
    }
    try {
        if (!request.getMethod().equalsIgnoreCase("GET")) {
            xml = parse(request.getInputStream(), encoding);
            request.setAttribute(CACHED_XML, xml);
        }
        return xml;
    } catch (IOException e) {
        throw new ConverterException("Error parsing XML", e);
    }
}

From source file:gov.va.vinci.chartreview.util.CRSchemaXML.java

/**
 * Parses the give CRSchemaXML (read from the POST Body of the Request)
 *
 * @param request an HttpServletRequest/*from  w  w  w.  j  a va2s .com*/
 * @return a groovy.util.XmlSlurper
 * @throws ConverterException
 */
public static Object parse(HttpServletRequest request) throws ConverterException {
    Object xml = request.getAttribute(CACHED_XML);
    if (xml != null)
        return xml;

    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = Converter.DEFAULT_REQUEST_ENCODING;
    }
    try {
        if (!request.getMethod().equalsIgnoreCase("GET")) {
            xml = parse(request.getInputStream(), encoding);
            request.setAttribute(CACHED_XML, xml);
        }
        return xml;
    } catch (IOException e) {
        throw new ConverterException("Error parsing CRSchemaXML", e);
    }
}

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, Server server,
        String uri, AuthToken authToken) throws IOException, ServiceException {
    if (server == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "cannot find remote server");
        return;/*ww  w .  j av a  2 s  . c o  m*/
    }
    HttpMethod method;
    String url = getProxyUrl(req, server, uri);
    mLog.debug("Proxy URL = %s", url);
    if (req.getMethod().equalsIgnoreCase("GET")) {
        method = new GetMethod(url.toString());
    } else if (req.getMethod().equalsIgnoreCase("POST") || req.getMethod().equalsIgnoreCase("PUT")) {
        PostMethod post = new PostMethod(url.toString());
        post.setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
        method = post;
    } else {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "cannot proxy method: " + req.getMethod());
        return;
    }
    HttpState state = new HttpState();
    String hostname = method.getURI().getHost();
    if (authToken != null) {
        authToken.encode(state, false, hostname);
    }
    try {
        proxyServletRequest(req, resp, method, state);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.jadyounan.Packager.java

/**
 * Servlet handler , should listen on the callback URL (as in webServiceURL)
 * @param requestPath//from   w w  w.  ja v  a 2s  . c  o m
 * @param req
 * @param servletRequest
 * @param servletResponse
 * @throws Exception
 */
public static void handle(String requestPath, Request req, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse) throws Exception {

    StringTokenizer st = new StringTokenizer(requestPath, "/");
    st.nextToken();
    String companyDomain = st.nextToken();

    String version = st.nextToken();

    byte bytes[] = new byte[] {};

    switch (st.nextToken().toLowerCase()) {
    case "log": {
        bytes = new byte[] {};

        byte r[] = org.eclipse.jetty.util.IO.readBytes(servletRequest.getInputStream());

        System.out.println("LOG " + new String(r));
    }
        break;
    case "devices": {
        String deviceID = st.nextToken();

        String authToken = req.getHeader("Authorization").split(" ")[1];

        // use the authToken to get the userID who started the request

        switch (servletRequest.getMethod().toUpperCase()) {
        case "DELETE":
            //handle deleting the token from your database
            break;
        default: {
            //handle adding the token/deviceID to your database
        }
            break;
        }

        FLUSH.updatePushDevices(userID);

        bytes = new byte[] {};
    }
        break;
    case "pushpackages": {
        /**
         * Safari requests the pacakge
         */
        String id = st.nextToken();

        JSONObject obj = new JSONObject(
                new String(org.eclipse.jetty.util.IO.readBytes(servletRequest.getInputStream())));

        String userID = obj.getString("user_id");

        String authenticationToken = "..a random string so you can later identify the user who started the request";

        bytes = createPackageFile(authenticationToken);
    }
        break;
    default:
        bytes = new byte[] {};
        break;
    }

    servletResponse.setStatus(200);
    servletResponse.setContentLength(bytes.length);
    try (OutputStream out = servletResponse.getOutputStream()) {
        out.write(bytes);
        out.flush();
    }
}