Example usage for javax.servlet.http HttpServletRequest getParameterNames

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

Introduction

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

Prototype

public Enumeration<String> getParameterNames();

Source Link

Document

Returns an Enumeration of String objects containing the names of the parameters contained in this request.

Usage

From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.java

@RequestMapping(value = "/wfs", method = RequestMethod.GET)
public void doWfsRequest(@RequestParam("ogpids") Set<String> layerIds, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse) throws Exception {
    Enumeration paramNames = servletRequest.getParameterNames();
    String ogcRequest = "";
    String typeName = "";
    while (paramNames.hasMoreElements()) {
        String param = (String) paramNames.nextElement();
        if (param.equalsIgnoreCase("version")) {

        } else if (param.equalsIgnoreCase("request")) {
            logger.info("request: " + servletRequest.getParameter(param));
            ogcRequest = servletRequest.getParameter(param);
        } else if (param.equalsIgnoreCase("typename")) {
            typeName = servletRequest.getParameter(param);
        }//from   ww  w  .j av a2 s. c  om
    }

    if (ogcRequest.equalsIgnoreCase("describefeaturetype") || ogcRequest.equalsIgnoreCase("getfeature")) {
        //TODO: strip all the params and rebuild the request with only sanctioned parameters, in case of fussy servers
        String remoteUrl = getOgcUrlFromLayerName(typeName, "wfs");
        String newQuery = removeParamFromQuery(servletRequest.getQueryString(), "ogpids");
        if (ogcRequest.equalsIgnoreCase("describefeaturetype")) {
            newQuery = removeParamFromQuery(newQuery, "srsname");
        }
        remoteUrl += "?" + newQuery;
        logger.info("remote url:" + remoteUrl);
        doProxy(remoteUrl, servletRequest, servletResponse);
    }

}

From source file:com.astamuse.asta4d.web.test.dispatch.RequestDispatcherTest.java

@Test(dataProvider = "data")
public void execute(String method, String url, int status, ContentProvider contentProvider) throws Exception {
    WebApplicationContext context = (WebApplicationContext) Context.getCurrentThreadContext();
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();
    HttpSession session = mock(HttpSession.class);

    when(request.getParameterNames()).thenReturn(Collections.emptyEnumeration());
    when(request.getCookies()).thenReturn(new Cookie[0]);
    when(request.getHeaderNames()).thenReturn(Collections.emptyEnumeration());
    when(request.getSession(true)).thenReturn(session);

    when(request.getRequestURI()).thenReturn(url);
    when(request.getContextPath()).thenReturn("");
    when(request.getMethod()).thenReturn(method);

    final ByteArrayOutputStream responseBos = new ByteArrayOutputStream();
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override/*  ww  w . j  a va 2s .  c o m*/
        public void write(int b) throws IOException {
            responseBos.write(b);
        }
    });

    HandyRuleSet ruleSet = new HandyRuleSet();
    initTestRules(ruleSet);

    if (url.equals("/index-rewrite")) {
        context.setAccessURI("/index");
    }

    dispatcher.dispatchAndProcess(ruleSet.getArrangedRuleList());

    // verify status at first then when contentProvider is null, we do not
    // need to do more verification
    if (status != 0) {
        verify(response).setStatus(status);
    }

    if (contentProvider == null) {
        return;
    }

    // prepare expected results
    HttpServletResponse expectedResponse = mock(HttpServletResponse.class);

    final ByteArrayOutputStream expectedBos = new ByteArrayOutputStream();
    when(expectedResponse.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override
        public void write(int b) throws IOException {
            expectedBos.write(b);
        }
    });

    final List<Pair<String, String>> expectedHeaderList = new LinkedList<>();

    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            expectedHeaderList.add(Pair.of((String) args[0], (String) args[1]));
            return null;
        }
    }).when(expectedResponse).addHeader(anyString(), anyString());

    UrlMappingRule currentRule = context.getCurrentRule();
    contentProvider.produce(currentRule, expectedResponse);

    // verify extra contents like headers and output stream

    for (Pair<String, String> pair : expectedHeaderList) {
        verify(response).addHeader(pair.getKey(), pair.getValue());
    }

    Assert.assertEquals(new String(responseBos.toByteArray()), new String(expectedBos.toByteArray()));

}

From source file:main.MainFormImpl.java

/**
 * Override to provide population of current form with request parameters when validation fails.
 *
 * @see org.apache.struts.action.ActionForm#validate(org.apache.struts.action.ActionMapping, javax.servlet.http.HttpServletRequest)
 *///from  w  w  w. ja  v  a 2s  . c  o  m
public org.apache.struts.action.ActionErrors validate(org.apache.struts.action.ActionMapping mapping,
        javax.servlet.http.HttpServletRequest request) {
    final org.apache.struts.action.ActionErrors errors = super.validate(mapping, request);
    if (errors != null && !errors.isEmpty()) {
        // we populate the current form with only the request parameters
        Object currentForm = request.getSession().getAttribute("form");
        // if we can't get the 'form' from the session, try from the request
        if (currentForm == null) {
            currentForm = request.getAttribute("form");
        }
        if (currentForm != null) {
            final java.util.Map parameters = new java.util.HashMap();
            for (final java.util.Enumeration names = request.getParameterNames(); names.hasMoreElements();) {
                final String name = String.valueOf(names.nextElement());
                parameters.put(name, request.getParameter(name));
            }
            try {
                org.apache.commons.beanutils.BeanUtils.populate(currentForm, parameters);
            } catch (Exception exception) {
                // ignore if we have an exception here (we just don't populate).
            }
        }
    }
    return errors;
}

From source file:fr.paris.lutece.plugins.asynchronousupload.service.AbstractAsynchronousUploadHandler.java

/**
 * {@inheritDoc}/*from w ww  .jav  a 2s .  com*/
 */
@Override
public void doRemoveFile(HttpServletRequest request, String strFieldName) {
    if (hasRemoveFlag(request, strFieldName)) {
        HttpSession session = request.getSession(false);

        if (session != null) {
            // Some previously uploaded files were deleted
            // Build the prefix of the associated checkboxes
            String strPrefix = getUploadCheckboxPrefix() + strFieldName;

            // Look for the checkboxes in the request
            Enumeration<String> enumParamNames = request.getParameterNames();
            List<Integer> listIndexes = new ArrayList<Integer>();

            while (enumParamNames.hasMoreElements()) {
                String strParamName = enumParamNames.nextElement();

                if (strParamName.startsWith(strPrefix)) {
                    // Get the index from the name of the checkbox
                    listIndexes.add(Integer.parseInt(strParamName.substring(strPrefix.length())));
                }
            }

            Collections.sort(listIndexes);
            Collections.reverse(listIndexes);

            for (int nIndex : listIndexes) {
                removeFileItem(strFieldName, session, nIndex);
            }
        }
    }
}

From source file:com.liusoft.dlog4j.action.ActionExtend.java

/**
 * Action???????? /*w  w w. ja va 2s.co  m*/
 * 1.??eventSubmit_XxxxdoXxxx
 * 2.?__method?do
 */
public final ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws Exception {
    ActionForward af = beforeExecute(mapping, form, req, res);
    if (af != null)
        return af;

    String param = null;
    String value = null;

    String __method = req.getParameter(METHOD_IDENT_PARAM);
    if (StringUtils.isNotBlank(__method)) {
        param = METHOD_PREFIX + __method;
    } else {
        for (Enumeration params = req.getParameterNames(); params.hasMoreElements();) {
            String t_param = (String) params.nextElement();
            if (t_param.startsWith(SUBMIT_BUTTON_PREFIX)) {
                value = req.getParameter(t_param);
                param = METHOD_PREFIX + t_param.substring(SUBMIT_BUTTON_PREFIX.length());
                break;
            }
        }
    }

    if (param == null)
        param = "doDefault";

    try {
        return callActionMethod(mapping, form, req, res, param, value);
    } catch (InvocationTargetException e) {
        Throwable t = e.getCause();
        if (t instanceof IllegalAccessException) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }
        log.error("Exception occur when calling " + param + " in action:" + getClass().getName(), t);
        if (t instanceof Exception)
            throw (Exception) t;
        else
            throw new Exception(t);
    } catch (NoSuchMethodException e) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return null;
    } finally {
        afterExecute(mapping, form, req, res);
    }
}

From source file:com.sg.rest.filters.LoggerFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
        LOGGER.error(NON_HTTP_REQUEST + System.lineSeparator() + request.getInputStream().toString());
        throw new RuntimeException(EXPECTING_AN_HTTP_REQUEST);
    }/*from ww  w. j av  a2 s  . c o  m*/

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    StringBuilder sb = new StringBuilder();
    //General header
    sb.append(System.lineSeparator());
    sb.append(INCOMING_REQUEST);
    //Request url
    sb.append(System.lineSeparator());
    sb.append(REQUEST_URL);
    sb.append(httpRequest.getRequestURL());
    //Method
    sb.append(System.lineSeparator());
    sb.append(METHOD);
    sb.append(httpRequest.getMethod());
    //Parameters
    if (httpRequest.getParameterNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(PARAMETERS);
        Enumeration enParams = httpRequest.getParameterNames();
        while (enParams.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String paramName = (String) enParams.nextElement();
            sb.append(paramName);
            sb.append(" : ");
            sb.append(httpRequest.getParameter(paramName));
        }
    }
    //Attributes
    if (httpRequest.getAttributeNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(ATTRIBUTES);
        Enumeration enAttribs = httpRequest.getAttributeNames();
        while (enAttribs.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String attribName = (String) enAttribs.nextElement();
            sb.append(attribName);
            sb.append(" : ");
            sb.append(httpRequest.getAttribute(attribName));
        }
    }
    //Headers
    if (httpRequest.getHeaderNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(HEADERS);
        Enumeration enHeaders = httpRequest.getHeaderNames();
        while (enHeaders.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String headerName = (String) enHeaders.nextElement();
            sb.append(headerName);
            sb.append(" : ");
            sb.append(httpRequest.getHeader(headerName));
        }
    }
    //AuthType
    if (httpRequest.getAuthType() != null && !httpRequest.getAuthType().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(AUTH_TYPE);
        sb.append(httpRequest.getAuthType());
    }
    //Cookies
    if (httpRequest.getCookies() != null && httpRequest.getCookies().length > 0) {
        sb.append(System.lineSeparator());
        sb.append(COOKIES);
        for (Cookie cookie : httpRequest.getCookies()) {
            sb.append(System.lineSeparator());
            sb.append(cookie.getName());
            sb.append(" : ");
            sb.append(cookie.getValue());
        }
    }
    //RemoteAddr
    if (httpRequest.getRemoteAddr() != null && !httpRequest.getRemoteAddr().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_ADDR);
        sb.append(httpRequest.getRemoteAddr());
    }
    //RemoteHost
    if (httpRequest.getRemoteHost() != null && !httpRequest.getRemoteHost().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_HOST);
        sb.append(httpRequest.getRemoteHost());
    }
    //User principal
    if (httpRequest.getUserPrincipal() != null) {
        if (httpRequest.getUserPrincipal().getName() != null
                && !httpRequest.getUserPrincipal().getName().isEmpty()) {
            sb.append(System.lineSeparator());
            sb.append(PRINCIPAL);
            sb.append(httpRequest.getUserPrincipal().getName());
        }
    }
    //Body
    ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest(
            (HttpServletRequest) request);
    String body = IOUtils.toString(wrappedRequest.getReader());
    if (body != null && !body.isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(BODY);
        sb.append(System.lineSeparator());
        sb.append(body);
    }
    wrappedRequest.resetInputStream();

    LOGGER.info(sb.toString());
    chain.doFilter(wrappedRequest, response);
}

From source file:br.mdarte.exemplo.academico.accessControl.Login.java

/**
 * /*from w ww .j a  va 2  s  .  c  o m*/
 */
private ActionForward __possuiLoginSenha(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final String value = String.valueOf(LoginControllerFactory.getLoginControllerInstance()
            .possuiLoginSenha(mapping, request, response, servlet));

    if (value.equals("false")) {
        ActionForward forward = mapping.findForward("entrar.login");

        if (__urlCasoDeUso != null && __contexto != null) {
            Enumeration nomeParametros = request.getParameterNames();
            StringBuffer parametros = new StringBuffer("");
            if (nomeParametros.hasMoreElements()) {
                parametros.append("?");
                while (nomeParametros.hasMoreElements()) {
                    String nome = nomeParametros.nextElement().toString();
                    parametros.append(nome + "=" + request.getParameter(nome));
                    if (nomeParametros.hasMoreElements()) {
                        parametros.append("@AND@");
                    }
                }
            }
            org.apache.struts.action.ActionRedirect redirect = new org.apache.struts.action.ActionRedirect(
                    forward);
            redirect.addParameter("nextPath", __contexto + __urlCasoDeUso + parametros.toString());
            forward = redirect;
        }
        return forward;
    }
    if (value.equals("true")) {
        return _verificarLogin(mapping, form, request, response);
    }

    // we take the last action in case we have an invalid return value from the controller
    return _verificarLogin(mapping, form, request, response);
}

From source file:net.ontopia.topicmaps.webed.impl.utils.ReqParamUtils.java

/**
 * INTERNAL: Builds the Parameters object from an HttpServletRequest
 * object./* w  w w  .  j a  v a2  s. c o m*/
 * @since 2.0
 */
public static Parameters decodeParameters(HttpServletRequest request, String charenc)
        throws ServletException, IOException {

    String ctype = request.getHeader("content-type");
    log.debug("Content-type: " + ctype);
    Parameters params = new Parameters();

    if (ctype != null && ctype.startsWith("multipart/form-data")) {
        // special file upload request, so use FileUpload to decode
        log.debug("Decoding with FileUpload; charenc=" + charenc);
        try {
            FileUpload upload = new FileUpload(new DefaultFileItemFactory());
            Iterator iterator = upload.parseRequest(request).iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                log.debug("Reading: " + item);
                if (item.isFormField()) {
                    if (charenc != null)
                        params.addParameter(item.getFieldName(), item.getString(charenc));
                    else
                        params.addParameter(item.getFieldName(), item.getString());
                } else
                    params.addParameter(item.getFieldName(), new FileParameter(item));
            }
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

    } else {
        // ordinary web request, so retrieve info and stuff into Parameters object
        log.debug("Normal parameter decode, charenc=" + charenc);
        if (charenc != null)
            request.setCharacterEncoding(charenc);
        Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String param = (String) enumeration.nextElement();
            params.addParameter(param, request.getParameterValues(param));
        }
    }

    return params;
}

From source file:com.hypersocket.auth.json.AuthenticatedController.java

AuthenticationState createAuthenticationState(String scheme, HttpServletRequest request,
        HttpServletResponse response) throws AccessDeniedException, UnsupportedEncodingException {

    Map<String, Object> environment = new HashMap<String, Object>();
    for (BrowserEnvironment env : BrowserEnvironment.values()) {
        if (request.getHeader(env.toString()) != null) {
            environment.put(env.toString(), request.getHeader(env.toString()));
        }//from  ww w .j  a  va2 s. c o  m
    }

    AuthenticationState state = authenticationService.createAuthenticationState(scheme, request.getRemoteAddr(),
            environment, sessionUtils.getLocale(request));

    Enumeration<?> names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        state.addParameter(name, URLDecoder.decode(request.getParameter(name), "UTF-8"));
    }

    request.getSession().setAttribute(AUTHENTICATION_STATE_KEY, state);
    return state;
}

From source file:com.iorga.webappwatcher.RequestLogFilter.java

@SuppressWarnings("unchecked")
private RequestEventLog createRequestEventLog(final HttpServletRequest httpRequest, final String requestURI) {
    final RequestEventLog logRequest = EventLogManager.getInstance().addEventLog(RequestEventLog.class);
    logRequest.setRequestURI(requestURI);
    logRequest.setMethod(httpRequest.getMethod());
    final Enumeration<String> parameterNames = httpRequest.getParameterNames();
    final List<Parameter> parameters = new LinkedList<Parameter>();
    while (parameterNames.hasMoreElements()) {
        final String parameterName = parameterNames.nextElement();
        parameters.add(new Parameter(parameterName, httpRequest.getParameterValues(parameterName)));
    }/*from  w w w . j av a 2s. c  o  m*/
    logRequest.setParameters(parameters.toArray(new Parameter[parameters.size()]));
    final Enumeration<String> headerNames = httpRequest.getHeaderNames();
    final List<Header> headers = new LinkedList<Header>();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        headers.add(new Header(headerName, httpRequest.getHeader(headerName)));
    }
    logRequest.setHeaders(headers.toArray(new Header[headers.size()]));
    final Principal userPrincipal = httpRequest.getUserPrincipal();
    if (userPrincipal != null) {
        logRequest.setPrincipal(userPrincipal.getName());
    }
    final Thread currentThread = Thread.currentThread();
    logRequest.setThreadName(currentThread.getName());
    logRequest.setThreadId(currentThread.getId());
    return logRequest;
}