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:org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.PostAuthnMissingClaimHandler.java

private void handlePostAuthenticationForMissingClaimsResponse(HttpServletRequest request,
        HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {

    if (log.isDebugEnabled()) {
        log.debug("Starting to process the response with missing claims");
    }/*from  w w w  .j a  v a 2 s  . c o m*/

    Map<String, String> claims = new HashMap<String, String>();
    Map<String, String> claimsForContext = new HashMap<String, String>();
    Map<String, String[]> requestParams = request.getParameterMap();
    boolean persistClaims = false;

    AuthenticatedUser user = context.getSequenceConfig().getAuthenticatedUser();

    Map<String, String> carbonToSPClaimMapping = new HashMap<>();
    Object spToCarbonClaimMappingObject = context.getProperty(FrameworkConstants.SP_TO_CARBON_CLAIM_MAPPING);

    if (spToCarbonClaimMappingObject instanceof Map) {

        Map<String, String> spToCarbonClaimMapping = (Map<String, String>) spToCarbonClaimMappingObject;

        for (Map.Entry<String, String> entry : spToCarbonClaimMapping.entrySet()) {
            carbonToSPClaimMapping.put(entry.getValue(), entry.getKey());
        }
    }

    for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
        if (entry.getKey().startsWith(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX)) {

            String localClaimURI = entry.getKey()
                    .substring(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX.length());
            claims.put(localClaimURI, entry.getValue()[0]);

            if (spToCarbonClaimMappingObject != null) {
                String spClaimURI = carbonToSPClaimMapping.get(localClaimURI);
                claimsForContext.put(spClaimURI, entry.getValue()[0]);
            } else {
                claimsForContext.put(localClaimURI, entry.getValue()[0]);
            }
        }
    }

    Map<ClaimMapping, String> authenticatedUserAttributes = FrameworkUtils.buildClaimMappings(claimsForContext);
    authenticatedUserAttributes.putAll(user.getUserAttributes());

    for (Map.Entry<Integer, StepConfig> entry : context.getSequenceConfig().getStepMap().entrySet()) {
        StepConfig stepConfig = entry.getValue();
        if (stepConfig.isSubjectAttributeStep()) {

            if (stepConfig.getAuthenticatedUser() != null) {
                user = stepConfig.getAuthenticatedUser();
            }

            if (!user.isFederatedUser()) {
                persistClaims = true;
            } else {
                String associatedID = null;
                UserProfileAdmin userProfileAdmin = UserProfileAdmin.getInstance();
                String subject = user.getAuthenticatedSubjectIdentifier();
                try {
                    associatedID = userProfileAdmin.getNameAssociatedWith(stepConfig.getAuthenticatedIdP(),
                            subject);
                    if (StringUtils.isNotBlank(associatedID)) {
                        String fullQualifiedAssociatedUserId = FrameworkUtils
                                .prependUserStoreDomainToName(associatedID
                                        + UserCoreConstants.TENANT_DOMAIN_COMBINER + context.getTenantDomain());
                        UserCoreUtil.setDomainInThreadLocal(UserCoreUtil.extractDomainFromName(associatedID));
                        user = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(
                                fullQualifiedAssociatedUserId);
                        persistClaims = true;
                    }
                } catch (UserProfileException e) {
                    throw new PostAuthenticationFailedException("Error while handling missing mandatory claims",
                            "Error while getting association for " + subject, e);
                }
            }
            break;
        }
    }

    if (persistClaims) {

        if (log.isDebugEnabled()) {
            log.debug("Local user mapping found. Claims will be persisted");
        }

        try {
            Map<String, String> claimMapping = context.getSequenceConfig().getApplicationConfig()
                    .getClaimMappings();

            Map<String, String> localIdpClaims = new HashMap<>();
            for (Map.Entry<String, String> entry : claims.entrySet()) {
                String localClaim = claimMapping.get(entry.getKey());
                localIdpClaims.put(localClaim, entry.getValue());
            }

            if (log.isDebugEnabled()) {
                log.debug("Updating user profile of user : " + user.getUserName());
            }

            UserRealm realm = getUserRealm(user.getTenantDomain());
            UserStoreManager userStoreManager = realm.getUserStoreManager()
                    .getSecondaryUserStoreManager(user.getUserStoreDomain());

            userStoreManager.setUserClaimValues(user.getUserName(), localIdpClaims, null);
        } catch (UserStoreException e) {
            throw new PostAuthenticationFailedException("Error while handling missing mandatory claims",
                    "Error while updating claims for local user. Could not update profile", e);
        }
    }
    context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
}

From source file:com.aipo.container.protocol.AipoDataServiceServlet.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Map<String, String[]> loadParameters(HttpServletRequest servletRequest,
        Map<String, FormDataItem> formItems) {
    Map<String, String[]> parameterMap = new HashMap<String, String[]>();

    // requestParameter???
    Map<String, String[]> map = servletRequest.getParameterMap();
    for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        String key = (String) entry.getKey();
        String[] _value = (String[]) entry.getValue();
        String[] value = new String[_value.length];
        for (int i = 0; i < _value.length; i++) {
            value[i] = _value[i];/*from   w ww.  ja va 2 s.  co  m*/
        }
        parameterMap.put(key, value);
    }

    if (servletRequest.getContentType() != null) {
        // Content-type?multipart/form-data??????
        if (ContentTypes.MULTIPART_FORM_CONTENT_TYPE
                .equals(ContentTypes.extractMimePart(servletRequest.getContentType()))) {
            if (formParser.isMultipartContent(servletRequest)) {
                Collection<FormDataItem> items = null;
                try {
                    items = formParser.parse(servletRequest);
                } catch (IOException e) {
                    // ignore
                }
                if (items != null) {
                    for (FormDataItem item : items) {
                        if (item.isFormField()) {
                            String value = item.getAsString();
                            String key = item.getFieldName();
                            if (value != null) {
                                try {
                                    value = new String(value.getBytes("iso-8859-1"), "utf-8");
                                } catch (UnsupportedEncodingException e) {
                                    // ignore
                                }
                            }
                            String[] valueArray = { value };
                            if (parameterMap.containsKey(key)) {
                                String[] preValue = parameterMap.get(key);
                                valueArray = Arrays.copyOf(preValue, preValue.length + 1);
                                valueArray[preValue.length] = value;
                            }
                            parameterMap.put(key, valueArray);
                        } else {
                            formItems.put(item.getFieldName(), item);
                        }
                    }
                }
            }

        }

        // Content-type?application/x-www-form-urlencoded??????
        if ("application/x-www-form-urlencoded"
                .equals(ContentTypes.extractMimePart(servletRequest.getContentType()))) {
            try {
                List<NameValuePair> params = URLEncodedUtils
                        .parse(new URI("http://localhost:8080?" + getBodyAsString(servletRequest)), "UTF-8");
                for (NameValuePair param : params) {
                    String[] valueArray = { param.getValue() };
                    if (parameterMap.containsKey(param.getName())) {
                        String[] preValue = parameterMap.get(param.getName());
                        valueArray = Arrays.copyOf(preValue, preValue.length + 1);
                        valueArray[preValue.length] = param.getValue();
                    }
                    parameterMap.put(param.getName(), valueArray);
                }
            } catch (URISyntaxException e) {
                // ignore
            }
        }
    }

    return parameterMap;
}

From source file:mx.edu.um.mateo.activos.web.ActivoController.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  av a  2s  .c  om*/

    List<CentroCosto> centrosDeCosto = centroCostoDao.buscaPorEmpresa(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:de.iew.web.utils.ValidatingFormAuthenticationFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {
    LoginForm loginForm = new LoginForm();

    /*//from   w w w  .  j  av a  2 s .  c  om
    Validiere zuerst die Logindaten. Da wir hier in einem Filter sind,
    mssen wir die Validierung per Hand vornehmen. Das Validierungsergebnis
    wird dann im Fehlerfall durch eine Exception mitgeteilt.
            
    @see <a href="http://static.springsource.org/spring/docs/3.0.x/reference/validation.html">http://static.springsource.org/spring/docs/3.0.x/reference/validation.html</a>
    */
    DataBinder binder = new DataBinder(loginForm);
    binder.setValidator(this.validator);

    MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(request.getParameterMap());
    binder.bind(mutablePropertyValues);
    binder.validate();

    BindingResult results = binder.getBindingResult();

    if (results.hasErrors()) {
        throw new LoginFormValidationException("validation failed", results);
    }

    return super.attemptAuthentication(request, response);
}

From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationResponseServlet.java

@SuppressWarnings("unchecked")
private void doIdRes(HttpServletRequest request, HttpServletResponse response)
        throws MessageException, DiscoveryException, AssociationException, IOException, ServletException {
    LOG.debug("id_res");
    LOG.debug("request URL: " + request.getRequestURL());

    // force UTF-8 encoding
    try {//from w w w.ja  v a2  s . c  o m
        request.setCharacterEncoding("UTF8");
        response.setCharacterEncoding("UTF8");
    } catch (UnsupportedEncodingException e) {
        throw new MessageException(e);
    }

    ParameterList parameterList = new ParameterList(request.getParameterMap());
    DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute("openid-disc");
    LOG.debug("request context path: " + request.getContextPath());
    LOG.debug("request URI: " + request.getRequestURI());
    String receivingUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getLocalPort()
            + request.getRequestURI();
    String queryString = request.getQueryString();
    if (queryString != null && queryString.length() > 0) {
        receivingUrl += "?" + queryString;
    }
    LOG.debug("receiving url: " + receivingUrl);
    ConsumerManager consumerManager = AuthenticationRequestServlet.getConsumerManager(request);
    VerificationResult verificationResult = consumerManager.verify(receivingUrl, parameterList, discovered);
    Identifier identifier = verificationResult.getVerifiedId();
    if (null != identifier) {

        Date authenticationTime = null;
        String userId = identifier.getIdentifier();
        List<String> authnPolicies = new LinkedList<String>();
        Map<String, Object> attributeMap = new HashMap<String, Object>();
        LOG.debug("userId: " + userId);
        Message authResponse = verificationResult.getAuthResponse();

        // verify return_to nonce
        AuthSuccess authResp = AuthSuccess.createAuthSuccess(parameterList);

        String returnTo = authResp.getReturnTo();
        String requestReturnTo = (String) request.getSession()
                .getAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);
        if (null == returnTo || null == requestReturnTo) {
            showErrorPage("Insufficient args for validation of " + " \"openid.return_to\".", null, request,
                    response);
            return;
        }
        if (!consumerManager.verifyReturnTo(requestReturnTo, authResp)) {
            showErrorPage("Invalid \"return_to\" in response!", null, request, response);
            return;
        }
        // cleanup
        request.getSession().removeAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);

        // AX
        if (authResponse.hasExtension(AxMessage.OPENID_NS_AX)) {

            MessageExtension messageExtension = authResponse.getExtension(AxMessage.OPENID_NS_AX);
            if (messageExtension instanceof FetchResponse) {

                FetchResponse fetchResponse = (FetchResponse) messageExtension;

                Map<String, String> attributeTypes = fetchResponse.getAttributeTypes();
                for (Map.Entry<String, String> entry : attributeTypes.entrySet()) {
                    attributeMap.put(entry.getValue(), fetchResponse.getAttributeValue(entry.getKey()));
                }

            }

        }

        // PAPE
        if (authResponse.hasExtension(PapeResponse.OPENID_NS_PAPE)) {

            MessageExtension messageExtension = authResponse.getExtension(PapeResponse.OPENID_NS_PAPE);
            if (messageExtension instanceof PapeResponse) {

                PapeResponse papeResponse = (PapeResponse) messageExtension;

                authnPolicies = papeResponse.getAuthPoliciesList();
                authenticationTime = papeResponse.getAuthDate();

            }
        }

        OpenIDAuthenticationResponse openIDAuthenticationResponse = new OpenIDAuthenticationResponse(
                authenticationTime, userId, authnPolicies, attributeMap);
        request.getSession().setAttribute(this.responseSessionAttribute, openIDAuthenticationResponse);

        response.sendRedirect(request.getContextPath() + this.redirectPage);
    } else {
        showErrorPage("No verified identifier", null, request, response);
    }
}

From source file:com.erudika.para.rest.Signer.java

private Request<?> buildAWSRequest(HttpServletRequest req, Set<String> headersUsed) {
    Map<String, String> headers = new HashMap<String, String>();
    for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements();) {
        String head = e.nextElement().toLowerCase();
        if (headersUsed.contains(head)) {
            headers.put(head, req.getHeader(head));
        }/*from w  w  w  . j a v a  2s.c  o m*/
    }

    Map<String, String> params = new HashMap<String, String>();
    for (Map.Entry<String, String[]> param : req.getParameterMap().entrySet()) {
        params.put(param.getKey(), param.getValue()[0]);
    }

    String path = req.getRequestURI();
    String endpoint = StringUtils.removeEndIgnoreCase(req.getRequestURL().toString(), path);
    String httpMethod = req.getMethod();
    InputStream entity;
    try {
        entity = new BufferedInputStream(req.getInputStream());
        if (entity.available() <= 0) {
            entity = null;
        }
    } catch (IOException ex) {
        logger.error(null, ex);
        entity = null;
    }

    return buildAWSRequest(httpMethod, endpoint, path, headers, params, entity);
}

From source file:contestWebsite.AdminPanel.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    UserCookie userCookie = UserCookie.getCookie(req);
    boolean loggedIn = userCookie != null && userCookie.authenticate();
    if (loggedIn && userCookie.isAdmin()) {
        Map<String, String[]> params = req.getParameterMap();

        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
        try {//  w  w w.  jav  a 2  s.c  om
            Entity info = Retrieve.contestInfo();
            Entity contestInfo = info != null ? info : new Entity("contestInfo");
            String view = params.get("view")[0];

            boolean testingMode;
            if (view.equals("general")) {
                testingMode = params.get("testing") != null && !params.containsKey("changePass");
            } else if (contestInfo.hasProperty("testingMode")) {
                testingMode = (boolean) contestInfo.getProperty("testingMode");
            } else {
                testingMode = false;
            }

            String[] stringPropNames = {}, textPropNames = {};

            if (view.equals("general")) {
                contestInfo.setProperty("levels", StringUtils.join(params.get("levels"), "+"));
                contestInfo.setProperty("price", Integer.parseInt(params.get("price")[0]));
                contestInfo.setProperty("testingMode", testingMode);
                contestInfo.setProperty("complete", params.get("complete") != null);
                contestInfo.setProperty("hideFullNames", params.get("fullnames") != null);

                stringPropNames = new String[] { "title", "endDate", "startDate", "editStartDate",
                        "editEndDate", "classificationQuestion", "testDownloadURL" };
            } else if (view.equals("tabulation")) {
                for (Level level : Level.values()) {
                    String[] docNames = params.get("doc" + level.getName());
                    if (docNames != null) {
                        contestInfo.setProperty("doc" + level.getName(), docNames[0]);
                    }

                    String[] schoolGroupsParam = params.get(level.toString() + "SchoolGroups");
                    if (schoolGroupsParam != null) {
                        try {
                            Yaml yaml = new Yaml();
                            Map<String, List<String>> schoolGroups = (Map<String, List<String>>) yaml
                                    .load(schoolGroupsParam[0]);
                            Map<String, String> schoolGroupNames = new HashMap<String, String>();
                            if (schoolGroups == null) {
                                schoolGroups = new HashMap<String, List<String>>();
                            }
                            for (Entry<String, List<String>> schoolGroupEntry : schoolGroups.entrySet()) {
                                for (String school : schoolGroupEntry.getValue()) {
                                    schoolGroupNames.put(school, schoolGroupEntry.getKey());
                                }
                            }
                            contestInfo.setProperty(level.toString() + "SchoolGroups",
                                    new Text(schoolGroupsParam[0]));
                            contestInfo.setProperty(level.toString() + "SchoolGroupsNames",
                                    new Text(new Yaml().dump(schoolGroupNames)));
                        } catch (Exception e) {
                            e.printStackTrace();
                            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
                            return;
                        }
                    }
                }

                for (Subject subject : Subject.values()) {
                    String[] subjectColors = params.get("color" + subject.getName());
                    if (subjectColors != null) {
                        contestInfo.setProperty("color" + subject.getName(), subjectColors[0]);
                    }
                }

                if (params.get("submitType")[0].equals("enqueueTabulationTask")) {
                    Queue queue = QueueFactory.getDefaultQueue();
                    TaskOptions options = withUrl("/tabulate")
                            .retryOptions(RetryOptions.Builder.withTaskRetryLimit(0));

                    for (Level level : Level.values()) {
                        String[] docNames = params.get("doc" + level.getName());
                        if (docNames != null) {
                            options.param("doc" + level.getName(), docNames[0]);
                        }
                    }

                    queue.add(options);
                }
            } else if (view.equals("content")) {
                GeoPt location = new GeoPt(Float.parseFloat(params.get("location_lat")[0]),
                        Float.parseFloat(params.get("location_long")[0]));
                contestInfo.setProperty("location", location);

                Yaml yaml = new Yaml();
                String[] mapPropNames = { "schedule", "directions" };
                for (String propName : mapPropNames) {
                    String text = params.get(propName)[0];

                    try {
                        @SuppressWarnings("unused")
                        HashMap<String, String> map = (HashMap<String, String>) yaml.load(text);
                        contestInfo.setProperty(propName, new Text(text));
                    } catch (Exception e) {
                        e.printStackTrace();
                        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
                        return;
                    }
                }

                String slideshowText = params.get("slideshow")[0];
                try {
                    @SuppressWarnings("unused")
                    ArrayList<ArrayList<String>> list = (ArrayList<ArrayList<String>>) yaml.load(slideshowText);
                    contestInfo.setProperty("slideshow", new Text(slideshowText));
                } catch (Exception e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
                    return;
                }

                stringPropNames = new String[] { "school", "address" };
                textPropNames = new String[] { "aboutText" };
            } else if (view.equals("awards")) {
                JSONObject awardCriteria = new JSONObject(), qualifyingCriteria = new JSONObject();
                ;
                for (Entry<String, String[]> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("counts_")) {
                        awardCriteria.put(entry.getKey().replace("counts_", ""),
                                Integer.parseInt(entry.getValue()[0]));
                    } else if (entry.getKey().startsWith("qualifying_")) {
                        if (!entry.getValue()[0].isEmpty()) {
                            qualifyingCriteria.put(entry.getKey().replace("qualifying_", ""),
                                    Integer.parseInt(entry.getValue()[0]));
                        }
                    }
                }
                contestInfo.setProperty("awardCriteria", new Text(awardCriteria.toString()));
                contestInfo.setProperty("qualifyingCriteria", new Text(qualifyingCriteria.toString()));
            } else if (view.equals("emails")) {
                stringPropNames = new String[] { "email", "account" };
                textPropNames = new String[] { "forgotPassEmail", "questionEmail", "registrationEmail" };
            } else if (view.equals("apis")) {
                stringPropNames = new String[] { "OAuth2ClientSecret", "OAuth2ClientId", "siteVerification",
                        "publicKey", "privateKey" };
                textPropNames = new String[] { "googleAnalytics" };
            }

            for (String propName : stringPropNames) {
                contestInfo.setProperty(propName, params.get(propName)[0]);
            }

            for (String propName : textPropNames) {
                contestInfo.setProperty(propName, new Text(params.get(propName)[0]));
            }

            datastore.put(contestInfo);

            Query query = new Query("user")
                    .setFilter(new FilterPredicate("user-id", FilterOperator.EQUAL, "admin"));
            Entity user = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0);
            String hash = (String) user.getProperty("hash");
            String salt = (String) user.getProperty("salt");

            if (testingMode) {
                String newHash = Password.getSaltedHash("password");
                resp.addCookie(new Cookie("user-id",
                        URLEncoder.encode("admin" + "$" + newHash.split("\\$")[1], "UTF-8")));

                user.setProperty("salt", newHash.split("\\$")[0]);
                user.setProperty("hash", newHash.split("\\$")[1]);
                datastore.put(user);
                resp.sendRedirect("/adminPanel?updated=1");
            } else if (params.containsKey("changePass")) {
                String curPassword = params.get("curPassword")[0];
                String confPassword = params.get("confPassword")[0];
                String newPassword = params.get("newPassword")[0];

                if (Password.check(curPassword, salt + "$" + hash)) {
                    if (confPassword.equals(newPassword)) {
                        String newHash = Password.getSaltedHash(newPassword);
                        resp.addCookie(new Cookie("user-id",
                                URLEncoder.encode("admin" + "$" + newHash.split("\\$")[1], "UTF-8")));

                        user.setProperty("salt", newHash.split("\\$")[0]);
                        user.setProperty("hash", newHash.split("\\$")[1]);
                        datastore.put(user);
                        resp.sendRedirect("/adminPanel?updated=1");
                    } else {
                        resp.sendRedirect("/adminPanel?confPassError=1");
                    }
                } else {
                    resp.sendRedirect("/adminPanel?passError=1");
                }
            } else {
                resp.sendRedirect("/adminPanel?updated=1");
            }
            txn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        } finally {
            if (txn.isActive()) {
                txn.rollback();
            }
        }
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Contest Administrator privileges required for that operation");
    }
}

From source file:com.yuga.ygplatform.modules.sys.interceptor.LogInterceptor.java

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) throws Exception {

    String requestRri = request.getRequestURI();
    String uriPrefix = request.getContextPath() + Global.getAdminPath();

    if ((StringUtils.startsWith(requestRri, uriPrefix) && (StringUtils.endsWith(requestRri, "/save")
            || StringUtils.endsWith(requestRri, "/delete") || StringUtils.endsWith(requestRri, "/import")
            || StringUtils.endsWith(requestRri, "/updateSort"))) || ex != null) {

        User user = UserUtils.getUser();
        if (user != null && user.getId() != null) {

            StringBuilder params = new StringBuilder();
            int index = 0;
            for (Object param : request.getParameterMap().keySet()) {
                params.append((index++ == 0 ? "" : "&") + param + "=");
                params.append(StringUtils.abbr(StringUtils.endsWithIgnoreCase((String) param, "password") ? ""
                        : request.getParameter((String) param), 100));
            }/*  w  ww . j av  a2  s .  co  m*/

            Log log = new Log();
            log.setType(ex == null ? Log.TYPE_ACCESS : Log.TYPE_EXCEPTION);
            log.setCreateBy(user);
            log.setCreateDate(new Date());
            log.setRemoteAddr(StringUtils.getRemoteAddr(request));
            log.setUserAgent(request.getHeader("user-agent"));
            log.setRequestUri(request.getRequestURI());
            log.setMethod(request.getMethod());
            log.setParams(params.toString());
            log.setException(ex != null ? ex.toString() : "");
            logDao.save(log);

            logger.debug("save log {type: {}, loginName: {}, uri: {}}, ", log.getType(), user.getLoginName(),
                    log.getRequestUri());

        }
    }

    //      logger.debug(": {}, ?: {}, ?: {}, ?: {}", 
    //            Runtime.getRuntime().maxMemory(), Runtime.getRuntime().totalMemory(), Runtime.getRuntime().freeMemory(), 
    //            Runtime.getRuntime().maxMemory()-Runtime.getRuntime().totalMemory()+Runtime.getRuntime().freeMemory()); 

}

From source file:com.redhat.rhn.frontend.taglibs.ColumnTag.java

protected String renderHeaderData(String hdr, String arg) {
    if (DYNAMIC_HEADER.equals(hdr)) {
        return arg;
    }//from  w  w w.  java  2 s  .c o  m

    String contents = null;
    if (arg != null) {
        contents = LocalizationService.getInstance().getMessage(hdr, arg);
    } else {
        contents = LocalizationService.getInstance().getMessage(hdr);
    }

    String retval = null;
    if (this.sortProperty != null) {
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        String pageUrl;
        Map params = new TreeMap(request.getParameterMap());
        String sortOrder = request.getParameter(RequestContext.SORT_ORDER);

        if (RequestContext.SORT_ASC.equals(sortOrder)) {
            params.put(RequestContext.SORT_ORDER, RequestContext.SORT_DESC);
        } else {
            params.put(RequestContext.SORT_ORDER, RequestContext.SORT_ASC);
        }
        params.put(RequestContext.LIST_SORT, sortProperty);
        pageUrl = ServletUtils.pathWithParams("", params);

        String title = LocalizationService.getInstance().getMessage("listdisplay.sortyby");
        retval = "<a title=\"" + title + "\" href=\"" + pageUrl + "\">" + contents + "</a>";
    } else {
        retval = contents;
    }

    return retval;
}

From source file:com.tecapro.inventory.common.util.LogUtil.java

/**
 * Error log output//ww w .  j  a va 2s. c  om
 * 
 * @param zform
 * @param request
 * @param e
 * @param method
 */
public void errorLog(Log log, BaseForm zform, HttpServletRequest request, Throwable e, String method) {

    errorLog(log, BaseAction.class.getSimpleName(), method, zform.getValue().getInfo(),
            "------ Error Information ------");
    errorLog(log, BaseAction.class.getSimpleName(), method, zform.getValue().getInfo(), e);

    errorLog(log, BaseAction.class.getSimpleName(), method, zform.getValue().getInfo(),
            "------ Input Information ------");
    errorLog(log, BaseAction.class.getSimpleName(), method, zform.getValue().getInfo(),
            dump(request.getParameterMap()));

    errorLog(log, BaseAction.class.getSimpleName(), method, zform.getValue().getInfo(),
            "------ Output Information ------");
    errorLog(log, BaseAction.class.getSimpleName(), method, zform.getValue().getInfo(), dump(zform));

}