Example usage for javax.servlet.http HttpServletRequest getParameter

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

Introduction

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

Prototype

public String getParameter(String name);

Source Link

Document

Returns the value of a request parameter as a String, or null if the parameter does not exist.

Usage

From source file:edu.stanford.muse.webapp.Accounts.java

/** does account setup and login (and look up default folder if well-known account) from the given request.
 * request params are loginName<N>, password<N>, etc (see loginForm for details).
 * returns an object with {status: 0} if success, or {status: <non-zero>, errorMessage: '... '} if failure.
 * if success and account has a well-known sent mail folder, the returned object also has something like: 
 * {defaultFolder: '[Gmail]/Sent Mail', defaultFolderCount: 1033}
 * accounts on the login page are numbered 0 upwards. */
public static JSONObject login(HttpServletRequest request, int accountNum) throws IOException, JSONException {
    JSONObject result = new JSONObject();

    HttpSession session = request.getSession();
    // allocate the fetcher if it doesn't already exist
    MuseEmailFetcher m = null;/* w  w  w  .jav  a 2s  . c  o  m*/
    synchronized (session) // synchronize, otherwise may lose the fetcher when multiple accounts are specified and are logged in to simult.
    {
        m = (MuseEmailFetcher) JSPHelper.getSessionAttribute(session, "museEmailFetcher");
        boolean doIncremental = request.getParameter("incremental") != null;

        if (m == null || !doIncremental) {
            m = new MuseEmailFetcher();
            session.setAttribute("museEmailFetcher", m);
        }
    }

    // note: the same params get posted with every accountNum
    // we'll update for all account nums, because sometimes account #0 may not be used, only #1 onwards. This should be harmless.
    // we used to do only altemailaddrs, but now also include the name.
    updateUserInfo(request);

    String accountType = request.getParameter("accountType" + accountNum);
    if (Util.nullOrEmpty(accountType)) {
        result.put("status", 1);
        result.put("errorMessage", "No information for account #" + accountNum);
        return result;
    }

    String loginName = request.getParameter("loginName" + accountNum);
    String password = request.getParameter("password" + accountNum);
    String protocol = request.getParameter("protocol" + accountNum);
    //   String port = request.getParameter("protocol" + accountNum);  // we don't support pop/imap on custom ports currently. can support server.com:port syntax some day
    String server = request.getParameter("server" + accountNum);
    String defaultFolder = request.getParameter("defaultFolder" + accountNum);

    if (server != null)
        server = server.trim();

    if (loginName != null)
        loginName = loginName.trim();

    // for these ESPs, the user may have typed in the whole address or just his/her login name
    if (accountType.equals("gmail") && loginName.indexOf("@") < 0)
        loginName = loginName + "@gmail.com";
    if (accountType.equals("yahoo") && loginName.indexOf("@") < 0)
        loginName = loginName + "@yahoo.com";
    if (accountType.equals("live") && loginName.indexOf("@") < 0)
        loginName = loginName + "@live.com";
    if (accountType.equals("stanford") && loginName.indexOf("@") < 0)
        loginName = loginName + "@stanford.edu";
    if (accountType.equals("gmail"))
        server = "imap.gmail.com";

    // add imapdb stuff here.
    boolean imapDBLookupFailed = false;
    String errorMessage = "";
    int errorStatus = 0;

    if (accountType.equals("email") && Util.nullOrEmpty(server)) {
        log.info("accountType = email");

        defaultFolder = "Sent";

        {
            // ISPDB from Mozilla
            imapDBLookupFailed = true;

            String emailDomain = loginName.substring(loginName.indexOf("@") + 1);
            log.info("Domain: " + emailDomain);

            // from http://suhothayan.blogspot.in/2012/05/how-to-install-java-cryptography.html
            // to get around the need for installingthe unlimited strength encryption policy files.
            try {
                Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
                field.setAccessible(true);
                field.set(null, java.lang.Boolean.FALSE);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            //            URL url = new URL("https://live.mozillamessaging.com/autoconfig/v1.1/" + emailDomain);
            URL url = new URL("https://autoconfig.thunderbird.net/v1.1/" + emailDomain);
            try {
                URLConnection urlConnection = url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(in);

                NodeList configList = doc.getElementsByTagName("incomingServer");
                log.info("configList.getLength(): " + configList.getLength());

                int i;
                for (i = 0; i < configList.getLength(); i++) {
                    Node config = configList.item(i);
                    NamedNodeMap attributes = config.getAttributes();
                    if (attributes.getNamedItem("type").getNodeValue().equals("imap")) {
                        log.info("[" + i + "] type: " + attributes.getNamedItem("type").getNodeValue());
                        Node param = config.getFirstChild();
                        String nodeName, nodeValue;
                        String paramHostName = "";
                        String paramUserName = "";
                        do {
                            if (param.getNodeType() == Node.ELEMENT_NODE) {
                                nodeName = param.getNodeName();
                                nodeValue = param.getTextContent();
                                log.info(nodeName + "=" + nodeValue);
                                if (nodeName.equals("hostname")) {
                                    paramHostName = nodeValue;
                                } else if (nodeName.equals("username")) {
                                    paramUserName = nodeValue;
                                }
                            }
                            param = param.getNextSibling();
                        } while (param != null);

                        log.info("paramHostName = " + paramHostName);
                        log.info("paramUserName = " + paramUserName);

                        server = paramHostName;
                        imapDBLookupFailed = false;
                        if (paramUserName.equals("%EMAILADDRESS%")) {
                            // Nothing to do with loginName
                        } else if (paramUserName.equals("%EMAILLOCALPART%")
                                || paramUserName.equals("%USERNAME%")) {
                            // Cut only local part
                            loginName = loginName.substring(0, loginName.indexOf('@') - 1);
                        } else {
                            imapDBLookupFailed = true;
                            errorMessage = "Invalid auto configuration";
                        }

                        break; // break after find first IMAP host name
                    }
                }
            } catch (Exception e) {
                Util.print_exception("Exception trying to read ISPDB", e, log);
                errorStatus = 2; // status code = 2 => ispdb lookup failed
                errorMessage = "No automatic configuration available for " + emailDomain
                        + ", please use the option to provide a private (IMAP) server. \nDetails: "
                        + e.getMessage()
                        + ". \nRunning with java -Djavax.net.debug=all may provide more details.";
            }
        }
    }

    if (imapDBLookupFailed) {
        log.info("ISPDB Fail");
        result.put("status", errorStatus);
        result.put("errorMessage", errorMessage);
        // add other fields here if needed such as server name attempted to be looked up in case the front end wants to give a message to the user
        return result;
    }

    boolean isServerAccount = accountType.equals("gmail") || accountType.equals("email")
            || accountType.equals("yahoo") || accountType.equals("live") || accountType.equals("stanford")
            || accountType.equals("gapps") || accountType.equals("imap") || accountType.equals("pop")
            || accountType.startsWith("Thunderbird");

    if (isServerAccount) {
        boolean sentOnly = "on".equals(request.getParameter("sent-messages-only"));
        return m.addServerAccount(server, protocol, defaultFolder, loginName, password, sentOnly);
    } else if (accountType.equals("mbox") || accountType.equals("tbirdLocalFolders")) {
        try {
            String mboxDir = request.getParameter("mboxDir" + accountNum);
            String emailSource = request.getParameter("emailSource" + accountNum);
            // for non-std local folders dir, tbird prefs.js has a line like: user_pref("mail.server.server1.directory-rel", "[ProfD]../../../../../../tmp/tb");
            log.info("adding mbox account: " + mboxDir);
            errorMessage = m.addMboxAccount(emailSource, mboxDir, accountType.equals("tbirdLocalFolders"));
            if (!Util.nullOrEmpty(errorMessage)) {
                result.put("errorMessage", errorMessage);
                result.put("status", 1);
            } else
                result.put("status", 0);
        } catch (MboxFolderNotReadableException e) {
            result.put("errorMessage", e.getMessage());
            result.put("status", 1);
        }
    } else {
        result.put("errorMessage", "Sorry, unknown account type: " + accountType);
        result.put("status", 1);
    }
    return result;
}

From source file:com.hrm.controller.RegisterController.java

/**
 * author qwc/*from   www  . j a  v a  2  s . c  o  m*/
 * 2017316?10:38:28
 * @param request
 * ?
 */
@RequestMapping("testmain")
public static void testmain(HttpServletRequest request) {
    String password = request.getParameter("telphone");
    System.out.println("" + password);
    System.out.println("MD5?" + string2MD5(password));
    System.out.println("" + convertMD5(password));
    System.out.println("" + convertMD5(convertMD5(password)));
}

From source file:com.ofbizcn.securityext.login.LoginEvents.java

public static void setUsername(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String domain = EntityUtilProperties.getPropertyValue("url.properties", "cookie.domain", delegator);
    // first try to get the username from the cookie
    synchronized (session) {
        if (UtilValidate.isEmpty(getUsername(request))) {
            // create the cookie and send it back
            Cookie cookie = new Cookie(usernameCookieName, request.getParameter("USERNAME"));
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setPath("/");
            cookie.setDomain(domain);//w w w . j  a v a2  s.c  om
            response.addCookie(cookie);
        }
    }
}

From source file:fr.paris.lutece.plugins.directory.web.DirectoryApp.java

/**
 * re init the map query used for searching
 * @param request the HttpServletRequest
 * @param searchFields the searchFields//from   www  .jav a2s  .  c om
 * @param directory the directory
 */
private static void initMapQuery(HttpServletRequest request, DirectorySiteSearchFields searchFields,
        Directory directory) {
    if ((request.getParameter(INIT_MAP_QUERY) != null) || ((request.getParameter(PARAMETER_SEARCH) == null)
            && (searchFields.getIdDirectory() != directory.getIdDirectory()))) {
        searchFields.setMapQuery(null);
    }
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils.java

/**
 * Check if the request was triggered by an Ajax call.
 * @param request the request//from ww  w .jav  a 2s  .  c om
 * @return <code>true</code> if Ajax
 */
public static boolean isAjax(final HttpServletRequest request) {

    String ajaxHeaderName = (String) ReflectionUtils.getConfigProperty("ajaxHeader");

    // check the current request's headers
    if (request.getHeader(ajaxHeaderName) != null) {
        return true;
    }

    // look for an ajax=true parameter
    if ("true".equals(request.getParameter("ajax"))) {
        return true;
    }

    // check the SavedRequest's headers
    SavedRequest savedRequest = (SavedRequest) request.getSession().getAttribute(WebAttributes.SAVED_REQUEST);
    if (savedRequest != null) {
        return !savedRequest.getHeaderValues(ajaxHeaderName).isEmpty();
    }

    return false;
}

From source file:morph.plugin.views.annotation.ServletAnnotationMappingUtils.java

/**
 * Check whether the given request matches the specified parameter conditions.
 * @param params  the parameter conditions, following
 *                {@link org.springframework.web.bind.annotation.RequestMapping#params() RequestMapping.#params()}
 * @param request the current HTTP request to check
 *///from w  ww  .  ja  va 2s .  c  om
public static boolean checkParameters(String[] params, HttpServletRequest request) {
    if (!ObjectUtils.isEmpty(params)) {
        for (String param : params) {
            int separator = param.indexOf('=');
            if (separator == -1) {
                if (param.startsWith("!")) {
                    if (WebUtils.hasSubmitParameter(request, param.substring(1))) {
                        return false;
                    }
                } else if (!WebUtils.hasSubmitParameter(request, param)) {
                    return false;
                }
            } else {
                boolean negated = separator > 0 && param.charAt(separator - 1) == '!';
                String key = !negated ? param.substring(0, separator) : param.substring(0, separator - 1);
                String value = param.substring(separator + 1);
                if (!value.equals(request.getParameter(key))) {
                    return negated;
                }
            }
        }
    }
    return true;
}

From source file:fr.paris.lutece.plugins.mylutece.util.SecurityUtils.java

/**
 * Update security parameters from request parameters
 * @param parameterService Parameter service
 * @param request Request to get the parameter from
 * @param plugin The plugin/*from www  . j a  v a 2  s.co  m*/
 */
public static void updateSecurityParameters(IUserParameterService parameterService, HttpServletRequest request,
        Plugin plugin) {
    updateParameterValue(parameterService, plugin, MARK_FORCE_CHANGE_PASSWORD_REINIT,
            request.getParameter(MARK_FORCE_CHANGE_PASSWORD_REINIT));
    updateParameterValue(parameterService, plugin, MARK_PASSWORD_MINIMUM_LENGTH,
            request.getParameter(MARK_PASSWORD_MINIMUM_LENGTH));

    if (getBooleanSecurityParameter(parameterService, plugin, MARK_USE_ADVANCED_SECURITY_PARAMETERS)) {
        updateParameterValue(parameterService, plugin, MARK_PASSWORD_FORMAT_UPPER_LOWER_CASE,
                request.getParameter(MARK_PASSWORD_FORMAT_UPPER_LOWER_CASE));
        updateParameterValue(parameterService, plugin, MARK_PASSWORD_FORMAT_NUMERO,
                request.getParameter(MARK_PASSWORD_FORMAT_NUMERO));
        updateParameterValue(parameterService, plugin, MARK_PASSWORD_FORMAT_SPECIAL_CHARACTERS,
                request.getParameter(MARK_PASSWORD_FORMAT_SPECIAL_CHARACTERS));
        updateParameterValue(parameterService, plugin, MARK_PASSWORD_DURATION,
                request.getParameter(MARK_PASSWORD_DURATION));
        updateParameterValue(parameterService, plugin, MARK_PASSWORD_HISTORY_SIZE,
                request.getParameter(MARK_PASSWORD_HISTORY_SIZE));
        updateParameterValue(parameterService, plugin, MARK_MAXIMUM_NUMBER_PASSWORD_CHANGE,
                request.getParameter(MARK_MAXIMUM_NUMBER_PASSWORD_CHANGE));
        updateParameterValue(parameterService, plugin, MARK_TSW_SIZE_PASSWORD_CHANGE,
                request.getParameter(MARK_TSW_SIZE_PASSWORD_CHANGE));
        updateParameterValue(parameterService, plugin, MARK_NOTIFY_USER_PASSWORD_EXPIRED,
                request.getParameter(MARK_NOTIFY_USER_PASSWORD_EXPIRED));
    }

    // Time of life of accounts
    updateParameterValue(parameterService, plugin, MARK_ACCOUNT_LIFE_TIME,
            request.getParameter(MARK_ACCOUNT_LIFE_TIME));

    // Time before the first alert when an account will expire
    updateParameterValue(parameterService, plugin, MARK_TIME_BEFORE_ALERT_ACCOUNT,
            request.getParameter(MARK_TIME_BEFORE_ALERT_ACCOUNT));

    // Number of alerts sent to a user when his account will expire
    updateParameterValue(parameterService, plugin, MARK_NB_ALERT_ACCOUNT,
            request.getParameter(MARK_NB_ALERT_ACCOUNT));

    // Time between alerts
    updateParameterValue(parameterService, plugin, MARK_TIME_BETWEEN_ALERTS_ACCOUNT,
            request.getParameter(MARK_TIME_BETWEEN_ALERTS_ACCOUNT));

    updateParameterValue(parameterService, plugin, MARK_ACCESS_FAILURES_MAX,
            request.getParameter(MARK_ACCESS_FAILURES_MAX));

    updateParameterValue(parameterService, plugin, MARK_ACCESS_FAILURES_INTERVAL,
            request.getParameter(MARK_ACCESS_FAILURES_INTERVAL));
    updateParameterValue(parameterService, plugin, MARK_ACCESS_FAILURES_CAPTCHA,
            request.getParameter(MARK_ACCESS_FAILURES_CAPTCHA));
    updateParameterValue(parameterService, plugin, MARK_ENABLE_UNBLOCK_IP,
            request.getParameter(MARK_ENABLE_UNBLOCK_IP));
    updateParameterValue(parameterService, plugin, MARK_ENABLE_TOKEN_LOGIN,
            request.getParameter(MARK_ENABLE_TOKEN_LOGIN));

}

From source file:fr.paris.lutece.portal.service.portal.ThemesService.java

/**
 * Get the theme code depending of the different priorities. The priorities are :
 * <ol>//from  w  ww.jav  a2  s .  co m
 * <li>the theme of test (in case you want to test a page with a specific theme)</li>
 * <li>the theme choosen by the user</li>
 * <li>the global theme : the one choosen in the back office for the whole site</li>
 * <li>the page theme : a theme specified for a page</li>
 * </ol>
 *
 * @param data The PageData object
 * @param request The HttpServletRequest
 * @return the theme
 */
public static Theme getTheme(PageData data, HttpServletRequest request) {
    String strTheme = StringUtils.EMPTY;

    // The code_theme of the page
    String strPageTheme = data.getTheme();

    if ((strPageTheme != null) && (strPageTheme.compareToIgnoreCase(GLOBAL_THEME) != 0)) {
        strTheme = strPageTheme;
    }

    // The theme of the user
    String strUserTheme = getUserTheme(request);

    if (strUserTheme != null) {
        strTheme = strUserTheme;
    }

    // the test theme (choosen for a page to test the different theme from the backoffice theme section)
    String themeTest = request.getParameter(THEME_TEST);

    if (themeTest != null) {
        strTheme = themeTest;
    }

    Theme theme = getGlobalTheme(strTheme);

    return theme;
}

From source file:com.moss.appkeep.server.HttpPublisher.java

public static ComponentRequest parse(HttpServletRequest request) {
    List<String> parts = splitWell(request.getPathInfo(), "/");

    RootType type = RootType.read(parts.get(0));

    if (type != RootType.BY_COMPONENT_ID) {
        return null;
    }/*from w w w  .  jav  a2 s  . c  o m*/

    ComponentId componentId;
    ComponentType componentType;
    {
        String fileName = parts.get(1);

        int pos = fileName.lastIndexOf('.');

        componentId = new ComponentId(fileName.substring(0, pos));
        componentType = ComponentType.valueOf(fileName.substring(pos + 1).toUpperCase());
    }

    //      System.out.println("Component ID: " + componentId);
    //      System.out.println("Component Type: " + componentType);

    List<String> endorsementStrings = splitWell(request.getParameter("with-endorsements"), ";");

    List<ComponentEndorsement> endorsements = new LinkedList<ComponentEndorsement>();

    for (String next : endorsementStrings) {
        int delimiterPos = next.indexOf(':');
        String typeString = next.substring(0, delimiterPos);
        String value = next.substring(delimiterPos + 1);
        //         System.out.println("Type " + typeString + ", value=" + value);

        EndorsementType endorsementType = EndorsementType.valueOf(typeString.toUpperCase());
        ComponentEndorsement e = endorsementType.parse(value);
        endorsements.add(e);
        //         System.out.println("Endorsement " + e);
    }

    return new ComponentRequest(endorsements, componentId, componentType);
}

From source file:com.company.project.core.connector.JSONHelper.java

/**
 * This method would create a string consisting of a JSON document with all
 * the necessary elements set from the HttpServletRequest request.
 * /* w  ww.jav  a2  s  . co m*/
 * @param request
 *            The HttpServletRequest
 * @return the string containing the JSON document.
 * @throws Exception
 *             If there is any error processing the request.
 */
public static String createJSONString(HttpServletRequest request, String controller) throws Exception {
    JSONObject obj = new JSONObject();
    try {
        Field[] allFields = Class
                .forName("com.microsoft.windowsazure.activedirectory.sdk.graph.models." + controller)
                .getDeclaredFields();
        String[] allFieldStr = new String[allFields.length];
        for (int i = 0; i < allFields.length; i++) {
            allFieldStr[i] = allFields[i].getName();
        }
        List<String> allFieldStringList = Arrays.asList(allFieldStr);
        Enumeration<String> fields = request.getParameterNames();

        while (fields.hasMoreElements()) {

            String fieldName = fields.nextElement();
            String param = request.getParameter(fieldName);
            if (allFieldStringList.contains(fieldName)) {
                if (param == null || param.length() == 0) {
                    if (!fieldName.equalsIgnoreCase("password")) {
                        obj.put(fieldName, JSONObject.NULL);
                    }
                } else {
                    if (fieldName.equalsIgnoreCase("password")) {
                        obj.put("passwordProfile", new JSONObject("{\"password\": \"" + param + "\"}"));
                    } else {
                        obj.put(fieldName, param);

                    }
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return obj.toString();
}