Example usage for javax.servlet.http HttpServletRequest getParameterValues

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

Introduction

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

Prototype

public String[] getParameterValues(String name);

Source Link

Document

Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.

Usage

From source file:com.mothsoft.alexis.web.ChartServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)/* ww w . ja va2  s  .  c o  m*/
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String[] pathComponents = request.getPathInfo().split("/");
    final String graphType = pathComponents[1];

    if ("line".equals(graphType)) {

        final String[] dataSets = request.getParameterValues("ds");

        final String w = request.getParameter("w");
        final Integer width = w == null ? 405 : Integer.valueOf(w);

        final String h = request.getParameter("h");
        final Integer height = h == null ? 325 : Integer.valueOf(h);

        final String n = request.getParameter("n");
        final Integer numberOfSamples = n == null ? 12 : Integer.valueOf(n);

        final String title = request.getParameter("title");

        final long start = System.currentTimeMillis();
        doLineGraph(request, response, title, dataSets, width, height, numberOfSamples);
        logger.debug("Graph took: " + (System.currentTimeMillis() - start) + " milliseconds");
    }
}

From source file:org.openmrs.module.logmanager.web.controller.ConfigController.java

/**
 * Handles an reload configuration request
 * @param request the http request/*  w  w  w . ja  va2  s  .  c o m*/
 */
private void reloadConfigurations(HttpServletRequest request) {
    LogManagerService svc = Context.getService(LogManagerService.class);
    boolean succeeded = true;

    if (request.getParameter("internalConfig") != null)
        svc.loadConfigurationFromSource();

    if (request.getParameter("externalConfig") != null)
        svc.loadConfiguration();

    String[] moduleConfigs = request.getParameterValues("moduleConfigs");
    if (moduleConfigs != null)
        svc.loadConfigurationFromModules(moduleConfigs);

    WebUtils.setInfoMessage(request,
            Constants.MODULE_ID + ".config." + (succeeded ? "reloadSuccess" : "reloadError"), null);
}

From source file:org.esgf.globusonline.GOFormView2Controller.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView doPost(final HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();

    /* Get the params from the form request */
    String dataset_name = request.getParameter("id");
    String[] file_names = request.getParameterValues("child_id");
    String[] file_urls = request.getParameterValues("child_url");
    String goUserName = request.getParameter("goUserName");
    String myProxyServerStr = request.getParameter(GOFORMVIEW_MYPROXY_SERVER);
    String myProxyUserName = request.getParameter(GOFORMVIEW_SRC_MYPROXY_USER);
    String myProxyUserPass = request.getParameter("myProxyUserPass");
    //String goEmail = request.getParameter("goEmail");

    LOG.debug("GOFormView2Controller: dataset_name = " + dataset_name);
    LOG.debug("GOFormView2Controller: file_names = " + file_names);
    LOG.debug("GOFormView2Controller: file_urls = " + file_urls);

    LOG.debug("goUserName: " + goUserName + " " + "myProxyUserName: " + myProxyUserName + " "
            + "myProxyUserPass: " + "*****" + " myProxyServerStr: " + myProxyServerStr);
    System.out.println("goUserName: " + goUserName + " " + "myProxyUserName: " + myProxyUserName + " "
            + "myProxyUserPass: " + "*****" + " myProxyServerStr: " + myProxyServerStr);

    StringBuffer errorStatus = new StringBuffer("Steps leading up to the error are shown below:<br><br>");
    errorStatus.append("Globus Online Username entered: ");
    errorStatus.append(goUserName);/* w w  w  .ja  v a2s . com*/
    errorStatus.append("<br>MyProxy Username entered: ");
    errorStatus.append(myProxyUserName);
    errorStatus.append("<br>");

    try {
        LOG.debug("Initializing Globus Online Transfer object");

        JGOTransfer transfer = new JGOTransfer(goUserName, myProxyServerStr, myProxyUserName, myProxyUserPass,
                CA_CERTIFICATE_FILE);

        transfer.setVerbose(true);
        transfer.initialize();

        LOG.debug("Globus Online Transfer object Initialize complete");

        errorStatus.append("Globus Online Transfer object Initialize complete<br>");

        String userCertificateFile = transfer.getUserCertificateFile();
        LOG.debug("Retrieved user credential file: " + userCertificateFile);

        LOG.debug("About to retrieve available endpoints");
        Vector<EndpointInfo> endpoints = transfer.listEndpoints();
        LOG.debug("We pulled down " + endpoints.size() + " endpoints");
        errorStatus.append("Endpoints retrieved<br>");

        // Make sure if any of the user's local endpoints are
        // globus connect endpoints, they are listed first
        endpoints = Utils.bringGCEndpointsToTop(goUserName, endpoints);

        if (request.getParameter(GOFORMVIEW_MODEL) != null) {

        } else {
            LOG.debug("Placing all info in the model");
            model.put(GOFORMVIEW_FILE_URLS, file_urls);
            model.put(GOFORMVIEW_FILE_NAMES, file_names);
            model.put(GOFORMVIEW_DATASET_NAME, dataset_name);
            model.put(GOFORMVIEW_USER_CERTIFICATE, userCertificateFile);
            model.put(GOFORMVIEW_GO_USERNAME, goUserName);
            model.put(GOFORMVIEW_SRC_MYPROXY_USER, myProxyUserName);
            model.put(GOFORMVIEW_SRC_MYPROXY_PASS, myProxyUserPass);
            model.put(GOFORMVIEW_MYPROXY_SERVER, myProxyServerStr);

            String[] endPointNames = getDestinationEndpointNames(endpoints);
            String[] endPointInfos = constructEndpointInfos(endpoints);

            LOG.debug("Retrieved an array of " + endPointNames.length + " Endpoint names");
            LOG.debug("Retrieved an array of " + endPointInfos.length + " EndpointInfo strings");

            model.put(GOFORMVIEW_ENDPOINTS, endPointNames);
            model.put(GOFORMVIEW_ENDPOINTINFOS, endPointInfos);

            LOG.debug("All info placed in the model!");
        }
    } catch (MyProxyException me) {
        String error = me.toString();
        if (error.contains("invalid password")) {
            error = "We could not start your download because of the following error:<br><br>The password you provided for your ESGF account with username \""
                    + myProxyUserName
                    + "\" is incorrect.<br><br>Please use your browser back button to go to the previous page, and try the request again.";
        } else {
            error = errorStatus.toString() + "<br><b>Main Error:</b><br><br>" + me.toString();
        }
        model.put(GOFORMVIEW_ERROR, "error");
        model.put(GOFORMVIEW_ERROR_MSG, error);
        LOG.error("Failed to initialize Globus Online: " + me);
    } catch (JGOTransferException jgte) {
        String error = jgte.toString();
        if (error.contains(
                "Endpoint List failure: ClientError.AuthenticationFailed(400 Authentication Failed)")) {
            error = "Your Globus Online Account \"" + goUserName
                    + "\" is not linked to the ESGF Portal account.<br><br>Please follow steps in <a href=\"https://github.com/ESGF/esgf.github.io/wiki/ESGF_GO_AccountSetup\">https://github.com/ESGF/esgf.github.io/wiki/ESGF_GO_AccountSetup</a> to link accounts.";
        }
        model.put(GOFORMVIEW_ERROR, "error");
        model.put(GOFORMVIEW_ERROR_MSG, error);
        LOG.error("Failed to initialize Globus Online: " + jgte);
    } catch (Exception e) {
        String error = errorStatus.toString() + "<br><b>Main Error:</b><br><br>" + e.toString();
        model.put(GOFORMVIEW_ERROR, "error");
        model.put(GOFORMVIEW_ERROR_MSG, error);
        LOG.error("Failed to initialize Globus Online: " + e);
        e.printStackTrace();
    }
    return new ModelAndView("goformview2", model);
}

From source file:org.openmrs.web.controller.report.export.RowPerObsDataExportListController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db/*from  w  ww .j  a v a 2s.com*/
 * 
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();
    if (Context.isAuthenticated()) {
        String[] reportList = request.getParameterValues("dataExportId");
        String action = request.getParameter("action");

        AdministrationService as = Context.getAdministrationService();

        String success = "";
        String error = "";

        MessageSourceAccessor msa = getMessageSourceAccessor();
        String deleted = msa.getMessage("general.deleted");
        String notDeleted = msa.getMessage("general.cannot.delete");
        String textDataExport = msa.getMessage("reportingcompatibility.DataExport.dataExport");
        String noneDeleted = msa.getMessage("reportingcompatibility.DataExport.nonedeleted");

        String generated = msa.getMessage("reportingcompatibility.DataExport.generated");
        String notGenerated = msa.getMessage("reportingcompatibility.DataExport.notGenerated");
        String noneGenerated = msa.getMessage("reportingcompatibility.DataExport.noneGenerated");

        if (msa.getMessage("reportingcompatibility.DataExport.generate").equals(action)) {
            if (reportList == null)
                success = noneGenerated;
            else {
                ReportObjectService rs = (ReportObjectService) Context.getService(ReportObjectService.class);
                EvaluationContext evalContext = new EvaluationContext();
                evalContext.addParameterValue(
                        new Parameter("general.user", "Authenticated User", org.openmrs.User.class, null),
                        Context.getAuthenticatedUser());
                for (String id : reportList) {
                    DataExportReportObject report = null;
                    try {
                        report = (DataExportReportObject) rs.getReportObject(Integer.valueOf(id));
                        DataExportUtil.generateExport(report, null, evalContext);
                        if (!success.equals(""))
                            success += "<br/>";
                        success += textDataExport + " '" + report.getName() + "' " + generated;
                    } catch (Exception e) {
                        log.warn("Error generating report object", e);
                        if (!error.equals(""))
                            error += "<br/>";
                        if (report == null)
                            error += textDataExport + " #" + id + " " + notGenerated;
                        else
                            error += textDataExport + " '" + report.getName() + "' " + notGenerated;
                    }
                }
            }
        } else if (msa.getMessage("reportingcompatibility.DataExport.delete").equals(action)) {

            if (reportList != null) {
                for (String p : reportList) {
                    // TODO convenience method deleteDataExport(Integer) ??
                    try {
                        as.deleteReportObject(Integer.valueOf(p));
                        if (!success.equals(""))
                            success += "<br/>";
                        success += textDataExport + " " + p + " " + deleted;
                    } catch (APIException e) {
                        log.warn("Error deleting report object", e);
                        if (!error.equals(""))
                            error += "<br/>";
                        error += textDataExport + " " + p + " " + notDeleted;
                    }
                }
            } else {
                success += noneDeleted;
            }
        }

        view = getSuccessView();
        if (!success.equals(""))
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);
        if (!error.equals(""))
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);
    }

    return new ModelAndView(new RedirectView(view));
}

From source file:net.chwise.websearch.SearchServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String queryText = req.getParameter("q");
    if (queryText == null)
        queryText = "";
    String[] smilesQueriesString = req.getParameterValues("sq");

    //Join text query with structures query
    StringBuffer sb = new StringBuffer();
    boolean nonEmptyQuery = isQuery(queryText);
    if (nonEmptyQuery)
        sb.append(queryText);//from   ww w. j  ava  2 s. c o m

    if (smilesQueriesString != null) {
        for (String structSmiles : smilesQueriesString) {

            if (!isQuery(structSmiles))
                continue;

            String escapedSmiles = QueryParser.escape(structSmiles);

            if (nonEmptyQuery) {
                sb.append(" AND ");
            }

            sb.append(" smiles:");
            sb.append(escapedSmiles);
            nonEmptyQuery = true;
        }
    }

    String joinedTextChemicalQuery = sb.toString();

    LOGGER.log(Level.INFO, "Query: {0}", joinedTextChemicalQuery);

    int from = 0;
    int numShow = 10;

    String strFrom = req.getParameter("from");
    String strNumShow = req.getParameter("numShow");

    if (strFrom != null)
        from = Integer.parseInt(strFrom);

    if (strNumShow != null)
        numShow = Math.min(Integer.parseInt(strNumShow), 20);

    int to = from + numShow;

    Integer[] fromTo = { new Integer(from), new Integer(to) };
    LOGGER.log(Level.INFO, "Requested results range: from {0} to {1}", fromTo);

    JSONObject jsonResponse = new JSONObject();
    JSONArray jsonResult = new JSONArray();
    try {
        //Preapre for search
        String directorySourceClassName = getServletConfig().getInitParameter("directorySourceClassName");
        String directorySourceParams = getServletConfig().getInitParameter("directorySourceParams");
        Directory directory = directorySource.getDirectory(directorySourceClassName, directorySourceParams);

        IndexReader reader = null;

        reader = IndexReader.open(directory);
        IndexSearcher searcher = new IndexSearcher(reader);

        //Perform query
        Query query = null;
        Analyzer analyzer = getAnalyzer();
        query = new MultiFieldQueryParser(Version.LUCENE_43, getTextFields(), analyzer, getFieldWeights())
                .parse(joinedTextChemicalQuery);

        TopScoreDocCollector collector = TopScoreDocCollector.create(to, true); //TODO: use from, to
        searcher.search(query, collector);
        ScoreDoc[] hits = collector.topDocs().scoreDocs;
        int totalResults = collector.getTotalHits();

        LOGGER.log(Level.INFO, "Found {0} documents", hits.length);

        //Wrap results into json object
        HighlightedFragmentsRetriever highlighter = new HighlightedFragmentsRetriever();

        to = Math.min(to, hits.length);

        for (int i = from; i < to; ++i) {
            ScoreDoc hit = hits[i];
            Document foundDoc = searcher.doc(hit.doc);

            JSONObject jsonDoc = extractJSON(query, analyzer, highlighter, foundDoc);
            jsonResult.put(jsonDoc);
        }

        jsonResponse.put("result", jsonResult);
        jsonResponse.put("total", totalResults);

    } catch (ParseException e) {
        JSONObject jsonFailure = SearchFailureJSONResponse.create("info", "We couldn't understand query",
                "Use quotes for phrase search. Use AND,OR,NOT for boolean search");
        try {
            jsonResponse.put("failure", jsonFailure);
        } catch (JSONException e1) {
            e1.printStackTrace();
            throw new RuntimeException(e1);
        }
    } catch (RuntimeException e) {
        if (e.getCause() instanceof InvalidSmilesException) {
            JSONObject jsonFailure = SearchFailureJSONResponse.create("info", "We couldn't understand query",
                    "Your structure formula doesn't seem like correct SMILES. Use structure editor for generating correct SMILES structures");
            try {
                jsonResponse.put("failure", jsonFailure);
            } catch (JSONException e1) {
                e1.printStackTrace();
                throw new RuntimeException(e1);
            }
        } else {
            e.printStackTrace();
            throw e;
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception in servlet SearchServlet", e);
    }

    resp.setContentType("application/json");
    PrintWriter out = resp.getWriter();

    out.print(jsonResponse);
    out.flush();
}

From source file:CreateGameServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONObject json = new JSONObject();

    Enumeration paramNames = request.getParameterNames();
    String params[] = new String[1];
    int i = 0;//  w  w  w .j  a  v  a 2  s . c o m
    while (paramNames.hasMoreElements()) {
        String paramName = (String) paramNames.nextElement();
        String[] paramValues = request.getParameterValues(paramName);
        params[i] = paramValues[0];
        i++;
    }
    //System.out.println("param0->"+params[0]);

    DatabaseHandler db = new DatabaseHandler();

    conn = db.makeConnection();

    try {
        stmt = conn.createStatement();

        String query = "INSERT INTO game (hoster,nameplayer1) VALUES (\"" + params[0] + "\",\"" + params[0]
                + "\")";
        //System.out.println(query);

        int updatedRows = stmt.executeUpdate(query);
        if (updatedRows == 1) {
            json.put("reply", "done");
        } else {
            json.put("reply", "undone");
        }

        query = "SELECT id FROM game WHERE hoster=\"" + params[0] + "\"";
        PreparedStatement prstmt = conn.prepareStatement(query);
        ResultSet rs = prstmt.executeQuery();
        String id = "0";
        while (rs.next()) {
            id = rs.getString("id");
        }
        //System.out.println("id-> "+id);
        if (!id.equals("0")) {
            json.put("gameid", id);
        }

    } catch (SQLException ex) {
        Logger.getLogger(CreateGameServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json.toString());

    db.closeAllConnections(conn, stmt);

}

From source file:net.duckling.ddl.web.controller.LynxDirectionController.java

@RequestMapping(params = "func=deleteResources")
@WebLog(method = "deleteResources", params = "rids[]")
public void deleteResources(HttpServletRequest request, HttpServletResponse response) {
    String[] ridStrs = request.getParameterValues("rids[]");
    List<Integer> rids = new ArrayList<Integer>();
    JSONObject o = new JSONObject();
    if (ridStrs == null) {
        o.put("result", false);
        o.put("message", "??");
    } else {//from w w  w  .  jav  a2  s .  c o m
        for (String r : ridStrs) {
            try {
                rids.add(Integer.parseInt(r));
            } catch (Exception e) {
            }
        }
        if (rids.size() > 0) {
            VWBContext context = VWBContext.createContext(request, UrlPatterns.T_TEAM_HOME);
            boolean b = false;
            for (Integer rid : rids) {
                b = resourceOperateService.deleteAuthValidate(VWBContext.getCurrentTid(), rid,
                        context.getCurrentUID());
                if (!b) {
                    break;
                }
            }
            if (!b) {
                o.put("result", false);
                o.put("message", "???");
            } else {
                String uid = VWBSession.getCurrentUid(request);
                resourceOperateService.deleteResource(VWBContext.getCurrentTid(), rids, uid);
                o.put("result", true);
                o.put("message", "???");
            }
        }
    }
    JsonUtil.writeJSONObject(response, o);
}

From source file:com.krawler.esp.handlers.ProfileHandler.java

public static void deletecompany(Session session, HttpServletRequest request) throws ServiceException {
    try {//  www  . j a  v a 2s.  co  m
        String[] ids = request.getParameterValues("cmpid");
        for (int i = 0; i < ids.length; i++) {
            Company c = (Company) session.load(Company.class, ids[i]);
            c.setDeleted(1);
            session.saveOrUpdate(c);
        }
    } catch (Exception e) {
        throw ServiceException.FAILURE("ProfileHandler.deletecompanies", e);
    }
}

From source file:biblivre3.cataloging.bibliographic.JsonBiblioHandler.java

private IFJson search(final HttpServletRequest request) {
    String itemType = request.getParameter("ITEM_TYPE");
    if (itemType == null) {
        itemType = "ALL";
    }/*from   w  w w .  j  a  v  a 2 s .co  m*/

    String[] boolOp = request.getParameterValues("BOOL_OP");
    String[] searchTerms = request.getParameterValues("SEARCH_TERM");
    String[] searchAttr = request.getParameterValues("SEARCH_ATTR");

    boolean listAll = !checkSearchTerms(searchTerms);
    int offset;
    try {
        offset = Integer.parseInt(request.getParameter("offset"));
    } catch (Exception e) {
        offset = 0;
    }

    String base = request.getParameter("base");
    if (base == null) {
        base = Database.MAIN.toString();
    }

    BiblioSearchBO bsbo = new BiblioSearchBO();
    BiblioSearchResultsDTO bdto;

    if (listAll) {
        // Busca Completa
        bdto = bsbo.list(base, itemType, offset);
    } else {
        bdto = bsbo.search(base, itemType, searchTerms, searchAttr, boolOp, offset);
    }

    if (bdto != null && bdto.al != null) {
        return bdto;
    } else {
        return new ErrorDTO("MESSAGE_FOUND_NONE", "warning");
    }
}

From source file:com.ms.commons.summer.web.handler.ObjectArrayDataBinder.java

@SuppressWarnings("unchecked")
private int initParamAndValues(HttpServletRequest request, String name, Map<String, String[]> paramAndValues) {
    int size = -1;
    boolean checkPrefix = false;
    if (StringUtils.isNotEmpty(name)) {
        checkPrefix = true;/*w ww  . ja  va 2s  . c o m*/
    }
    for (Enumeration<String> parameterNames = request.getParameterNames(); parameterNames.hasMoreElements();) {
        String parameterName = parameterNames.nextElement();
        if (checkPrefix && parameterName.startsWith(name + ".")) {
            String[] values = request.getParameterValues(parameterName);
            if (values != null && values.length > 0) {
                paramAndValues.put(parameterName.substring(name.length() + 1), values);
                if (size == -1) {
                    size = values.length;
                } else if (size != values.length) {
                    fieldError = new FieldError(name, name, "?");
                    return -1;
                }
            }
        }
    }
    return size;
}