Example usage for javax.servlet.http HttpServletRequest getParameterMap

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

Introduction

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

Prototype

public Map<String, String[]> getParameterMap();

Source Link

Document

Returns a java.util.Map of the parameters of this request.

Usage

From source file:de.drv.dsrv.utility.spring.web.LoggingHandlerInterceptor.java

@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler) {
    // Prfe, ob Log-Level aktiviert ist
    if (LOG.isDebugEnabled()) {
        // Schreibe Log-Meldung
        LOG.debug("URL " + request.getRequestURL() + " aufgerufen");

        // Schreibe Parameter
        for (final Object key : request.getParameterMap().keySet()) {
            // Prfe, ob Parameter gltig (ungleich null) ist
            if (key != null) {
                // Prfe, ob sich um ein Passwort handelt
                if (key.toString().matches(PASSWORT_REGEX)) {
                    LOG.debug("+ Parameter: " + key.toString() + "=********");
                } else {
                    LOG.debug("+ Parameter: " + key.toString() + "=" + request.getParameter(key.toString()));
                }/*from   www. j a  v  a2 s  .  c o  m*/
            }
        }
    }

    // Fhre weitere Verarbeitung durch
    return true;
}

From source file:org.entando.entando.plugins.jpoauth2.aps.internalservlet.login.LoginAction.java

/**
 * Initiate the login process with OAuth2
 * This gets also invoked when returning from the login page with all the 
 * arguments needed to complete the authentication process
 * @return/*from w w  w.  ja va  2s  .  com*/
 */
public String access() {
    UserDetails user = getCurrentUser();
    HttpServletRequest request = this.getRequest();

    try {
        String callback = getCallbackUrl();
        Map pmap = request.getParameterMap();

        // first we set default path for error JSP
        setBasedir("jpoauth2");
        if (null == pmap || pmap.isEmpty() || !pmap.containsKey(REQUEST_PARAM_CODE)) {

            // retrieve the manager to use for the authentication flow
            String id = request.getParameter(REQUEST_PARAM_SERVICE_ID);
            _logger.info("Retrieving manager for id '{}'", id);

            String value = getIndexerManager().getManagerById(id);
            String managerName = "jp".concat(value).concat("Manager");
            _logger.info("Looking for manager: '{}'", managerName);

            IOAuth2Manager oauth2Manager = (IOAuth2Manager) ApsWebApplicationUtils.getBean(managerName,
                    request);
            // set path for error JSP
            setBasedir(value);
            _logger.info("Setting: base '{}' for error messages", value);
            String state = encodeState(getRedirectPage(), id);
            String redirUrl = oauth2Manager.getAuthorizationNewURL(callback, state);

            _logger.debug("Sending user to authentication page '{}'", redirUrl);
            ServletActionContext.getResponse().sendRedirect(redirUrl);
            return NONE;

        } else {

            _logger.debug("Retrieving login authentication '{}'", "tokenUrl");
            String code = request.getParameter(REQUEST_PARAM_CODE);
            String state = request.getParameter(REQUEST_PARAM_STATE);
            String id = decodeStateService(state);
            String portalPage = decodeStatePortalPage(state);
            String portalRedirectUrl = getPageUrl(portalPage);
            _logger.debug("Will redirect to '{}' after login", portalRedirectUrl);

            setRedirectPage(portalRedirectUrl);

            String value = getIndexerManager().getManagerById(id);
            String managerName = "jp".concat(value).concat("Manager");
            _logger.info("Looking for manager: '{}'", managerName);
            IOAuth2Manager oauth2Manager = (IOAuth2Manager) ApsWebApplicationUtils.getBean(managerName,
                    request);

            if (StringUtils.isNotBlank(code)) {
                DefaultHttpClient client = new DefaultHttpClient();
                HttpPost post = oauth2Manager.getAuthenticationUrlPost(callback, code);

                try {
                    HttpResponse response = client.execute(post);
                    int status = response.getStatusLine().getStatusCode();
                    AbstractOAuth2Service serviceData = null;

                    if (status == HttpStatus.SC_OK) {
                        _logger.debug("ok, parsing response to get access token");
                        try {
                            serviceData = oauth2Manager.processAnswer(response);
                            OAuth2Session sessionServices = (OAuth2Session) request.getSession()
                                    .getAttribute(OAuth2SystemConstants.SESSIONPARAM_SERVICE_OBJECT);
                            if (null == sessionServices) {
                                sessionServices = new OAuth2Session();
                                _logger.debug("Creating OAuth2 session object for service '{}'", id);
                            } else {
                                _logger.debug("OAuth2 session object found, appending new service '{}'", id);
                            }
                            sessionServices.addServiceData(id, serviceData);
                            request.getSession().setAttribute(OAuth2SystemConstants.SESSIONPARAM_SERVICE_OBJECT,
                                    sessionServices);
                        } catch (Throwable t) {
                            _logger.info("Error detected while negotiating access token", t);
                        }
                        oauth2Manager.postLogin(serviceData);
                    } else {
                        _logger.info("Invalid status on response '{}' ", status);
                        return "error";
                    }
                } finally {
                    post.releaseConnection();
                }

            } else {
                _logger.error("'{}' parameter not found in the request, cannot proceed", REQUEST_PARAM_CODE);
                return "error";
            }
        }
    } catch (Throwable t) {
        _logger.error("login with OAuth2 failed!", t);
        return "error";
    }

    return "redirect";
}

From source file:com.ari.controller.catalog.CategoryController.java

private String addSortLink(SortOption sortOption) {

    Map<String, String> attrs = new HashMap<String, String>();

    BroadleafRequestContext blcContext = BroadleafRequestContext.getBroadleafRequestContext();
    HttpServletRequest request = blcContext.getRequest();

    String baseUrl = request.getRequestURL().toString();
    Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap());

    String key = ProductSearchCriteria.SORT_STRING;
    String sortField = sortOption.getSortCondition();

    List<String[]> sortedFields = new ArrayList<String[]>();

    String[] paramValues = params.get(key);
    if (paramValues != null && paramValues.length > 0) {
        String sortQueries = paramValues[0];
        for (String sortQuery : sortQueries.split(",")) {
            String[] sort = sortQuery.split(" ");
            if (sort.length == 2) {
                sortedFields.add(new String[] { sort[0], sort[1] });
            }//from  w w w .j av a 2 s.  co  m
        }
    }

    boolean currentlySortingOnThisField = false;
    boolean currentlyAscendingOnThisField = false;

    for (String[] sortedField : sortedFields) {
        if (sortField.equals(sortedField[0])) {
            currentlySortingOnThisField = true;
            currentlyAscendingOnThisField = sortedField[1].equals("asc");
            sortedField[1] = currentlyAscendingOnThisField ? "desc" : "asc";
        }
    }

    String sortString = sortField;
    String classString = "";

    if (currentlySortingOnThisField) {
        classString += "active ";
        if (currentlyAscendingOnThisField) {
            sortString += " desc";
            classString += "asc ";
        } else {
            sortString += " asc";
            classString += "desc ";
        }
    } else {
        sortString += " asc";
        classString += "asc ";
        params.remove(ProductSearchCriteria.PAGE_NUMBER);
    }

    boolean allowMultipleSorts = false;

    if (allowMultipleSorts) {
        StringBuilder sortSb = new StringBuilder();
        for (String[] sortedField : sortedFields) {
            sortSb.append(sortedField[0]).append(" ").append(sortedField[1]).append(",");
        }

        sortString = sortSb.toString();
        if (sortString.charAt(sortString.length() - 1) == ',') {
            sortString = sortString.substring(0, sortString.length() - 1);
        }
    }

    params.put(key, new String[] { sortString });

    String url = ProcessorUtils.getUrl(baseUrl, params);

    //TODO
    attrs.put("class", classString);
    attrs.put("href", url);

    return url;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.admin.SparqlQueryController.java

/**
 * If a query has been provided, we answer it directly, bypassing the
 * Freemarker mechanisms.//from  w w  w . ja  v  a  2  s .c  om
 */
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    if (!isAuthorizedToDisplayPage(req, resp, SimplePermission.USE_SPARQL_QUERY_PAGE.ACTION)) {
        return;
    }
    if (req.getParameterMap().containsKey("query")) {
        respondToQuery(req, resp);
    } else {
        super.doGet(req, resp);
    }
}

From source file:mx.edu.um.mateo.general.web.OrganizacionController.java

@RequestMapping(value = "/centrosDeCosto", params = "term", produces = "application/json")
public @ResponseBody List<Map<String, String>> centrosDeCosto(HttpServletRequest request,
        @RequestParam("term") String filtro) {
    log.debug("Buscando Centros de Costo por {}", filtro);
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//from   w  w  w.  j a v a  2s . c om

    List<CentroCosto> centrosDeCosto = centroCostoDao.busca(filtro, ambiente.obtieneUsuario());
    List<Map<String, String>> resultados = new ArrayList<>();
    for (CentroCosto centroCosto : centrosDeCosto) {
        Map<String, String> map = new HashMap<>();
        map.put("id", centroCosto.getId().getIdCosto());
        map.put("value", centroCosto.getNombreCompleto());
        resultados.add(map);
    }

    return resultados;
}

From source file:io.cettia.ProtocolTest.java

@Test
public void protocol() throws Exception {
    final DefaultServer server = new DefaultServer();
    server.onsocket(new Action<ServerSocket>() {
        @Override/*from w  w w  .  ja v  a 2s.c  om*/
        public void on(final ServerSocket socket) {
            log.debug("socket.uri() is {}", socket.uri());
            socket.on("abort", new VoidAction() {
                @Override
                public void on() {
                    socket.close();
                }
            }).on("echo", new Action<Object>() {
                @Override
                public void on(Object data) {
                    socket.send("echo", data);
                }
            }).on("/reply/inbound", new Action<Reply<Map<String, Object>>>() {
                @Override
                public void on(Reply<Map<String, Object>> reply) {
                    Map<String, Object> data = reply.data();
                    switch ((String) data.get("type")) {
                    case "resolved":
                        reply.resolve(data.get("data"));
                        break;
                    case "rejected":
                        reply.reject(data.get("data"));
                        break;
                    }
                }
            }).on("/reply/outbound", new Action<Map<String, Object>>() {
                @Override
                public void on(Map<String, Object> data) {
                    switch ((String) data.get("type")) {
                    case "resolved":
                        socket.send("test", data.get("data"), new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    case "rejected":
                        socket.send("test", data.get("data"), null, new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    }
                }
            });
        }
    });
    final HttpTransportServer httpTransportServer = new HttpTransportServer().ontransport(server);
    final WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().ontransport(server);

    org.eclipse.jetty.server.Server jetty = new org.eclipse.jetty.server.Server();
    ServerConnector connector = new ServerConnector(jetty);
    jetty.addConnector(connector);
    connector.setPort(8000);
    ServletContextHandler handler = new ServletContextHandler();
    jetty.setHandler(handler);
    handler.addEventListener(new ServletContextListener() {
        @Override
        @SuppressWarnings("serial")
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            ServletRegistration regSetup = context.addServlet("/setup", new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse res)
                        throws ServletException, IOException {
                    Map<String, String[]> params = req.getParameterMap();
                    if (params.containsKey("heartbeat")) {
                        server.setHeartbeat(Integer.parseInt(params.get("heartbeat")[0]));
                    }
                    if (params.containsKey("_heartbeat")) {
                        server.set_heartbeat(Integer.parseInt(params.get("_heartbeat")[0]));
                    }
                }
            });
            regSetup.addMapping("/setup");
            // For HTTP transport
            Servlet servlet = new AsityServlet().onhttp(httpTransportServer);
            ServletRegistration.Dynamic reg = context.addServlet(AsityServlet.class.getName(), servlet);
            reg.setAsyncSupported(true);
            reg.addMapping("/cettia");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    });
    // For WebSocket transport
    ServerContainer container = WebSocketServerContainerInitializer.configureContext(handler);
    ServerEndpointConfig config = ServerEndpointConfig.Builder.create(AsityServerEndpoint.class, "/cettia")
            .configurator(new Configurator() {
                @Override
                public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
                    return endpointClass.cast(new AsityServerEndpoint().onwebsocket(wsTransportServer));
                }
            }).build();
    container.addEndpoint(config);

    jetty.start();

    CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node")
            .addArgument("./src/test/resources/runner").addArgument("--cettia.transports")
            .addArgument("websocket,httpstream,httplongpoll");
    DefaultExecutor executor = new DefaultExecutor();
    // The exit value of mocha is the number of failed tests.
    executor.execute(cmdLine);

    jetty.stop();
}

From source file:co.propack.sample.payment.service.gateway.NullPaymentGatewayWebResponseServiceImpl.java

@Override
public PaymentResponseDTO translateWebResponse(HttpServletRequest request) throws PaymentException {
    PaymentResponseDTO responseDTO = new PaymentResponseDTO(PaymentType.CREDIT_CARD,
            NullPaymentGatewayType.NULL_GATEWAY).rawResponse(webResponsePrintService.printRequest(request));

    Map<String, String[]> paramMap = request.getParameterMap();

    Money amount = Money.ZERO;//  w w w  .  ja v  a2  s. co  m
    if (paramMap.containsKey(NullPaymentGatewayConstants.TRANSACTION_AMT)) {
        String amt = paramMap.get(NullPaymentGatewayConstants.TRANSACTION_AMT)[0];
        amount = new Money(amt);
    }

    boolean approved = false;
    if (paramMap.containsKey(NullPaymentGatewayConstants.RESULT_SUCCESS)) {
        String[] msg = paramMap.get(NullPaymentGatewayConstants.RESULT_SUCCESS);
        if (ArrayUtils.contains(msg, "true")) {
            approved = true;
        }
    }

    PaymentTransactionType type = PaymentTransactionType.AUTHORIZE_AND_CAPTURE;
    if (!configuration.isPerformAuthorizeAndCapture()) {
        type = PaymentTransactionType.AUTHORIZE;
    }

    responseDTO.successful(approved).amount(amount).paymentTransactionType(type)
            .orderId(paramMap.get(NullPaymentGatewayConstants.ORDER_ID)[0])
            .responseMap(NullPaymentGatewayConstants.GATEWAY_TRANSACTION_ID,
                    paramMap.get(NullPaymentGatewayConstants.GATEWAY_TRANSACTION_ID)[0])
            .responseMap(NullPaymentGatewayConstants.RESULT_MESSAGE,
                    paramMap.get(NullPaymentGatewayConstants.RESULT_MESSAGE)[0])
            .billTo().addressFirstName(paramMap.get(NullPaymentGatewayConstants.BILLING_FIRST_NAME)[0])
            .addressLastName(paramMap.get(NullPaymentGatewayConstants.BILLING_LAST_NAME)[0])
            .addressLine1(paramMap.get(NullPaymentGatewayConstants.BILLING_ADDRESS_LINE1)[0])
            .addressLine2(paramMap.get(NullPaymentGatewayConstants.BILLING_ADDRESS_LINE2)[0])
            .addressCityLocality(paramMap.get(NullPaymentGatewayConstants.BILLING_CITY)[0])
            .addressStateRegion(paramMap.get(NullPaymentGatewayConstants.BILLING_STATE)[0])
            .addressPostalCode(paramMap.get(NullPaymentGatewayConstants.BILLING_ZIP)[0])
            .addressCountryCode(paramMap.get(NullPaymentGatewayConstants.BILLING_COUNTRY)[0]).done()
            .creditCard().creditCardHolderName(paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_NAME)[0])
            .creditCardLastFour(paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_LAST_FOUR)[0])
            .creditCardType(paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_TYPE)[0])
            .creditCardExpDate(paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_EXP_DATE)[0]).done();

    return responseDTO;

}

From source file:at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20BaseRequest.java

private void checkAllowedParameters(final HttpServletRequest request) {
    Logger.debug("Going to check for allowed parameters");
    this.allowedParameters.add(OAuth20Constants.PARAM_MOA_ACTION);
    this.allowedParameters.add(OAuth20Constants.PARAM_MOA_MOD);

    @SuppressWarnings("rawtypes")
    Iterator iter = request.getParameterMap().keySet().iterator();
    while (iter.hasNext()) {
        String name = (String) iter.next();
        if (!this.allowedParameters.contains(name)) {

            Logger.debug("Found wrong parameter: " + name);
            throw new OAuth20WrongParameterException(name);
        }//from w  w w  .j av  a2s.c o m
    }

}

From source file:org.openmrs.module.fbregistrationapp.fragment.controller.MatchingPatientsFragmentController.java

private void addToPatient(Patient patient, AppDescriptor app, PersonName name, PersonAddress address,
        HttpServletRequest request) throws IOException {
    NavigableFormStructure formStructure = RegisterPatientFormBuilder.buildFormStructure(app);

    patient.addName(name);//from   w w  w  . j a v a 2s .  co  m
    patient.addAddress(address);

    if (formStructure != null) {
        RegisterPatientFormBuilder.resolvePersonAttributeFields(formStructure, patient,
                request.getParameterMap());
    }
}

From source file:com.googlesource.gerrit.plugins.github.velocity.VelocityViewServlet.java

private PluginVelocityModel initVelocityModel(HttpServletRequest request) {
    PluginVelocityModel model = modelProvider.get();
    GitHubLogin gitHubLogin = loginProvider.get(request);
    model.put("myself", gitHubLogin.getMyself());
    model.put("user", userProvider.get());
    model.put("hub", gitHubLogin.getHub());

    for (Entry<String, String[]> reqPar : request.getParameterMap().entrySet()) {
        model.put(reqPar.getKey(), reqPar.getValue());
    }/*from   w  ww  .j  ava2  s  .com*/
    return model;
}