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:edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet.java

/**
 * A child class may call this if logging is set to debug level.
 *//*from  ww  w. jav  a 2s.  com*/
protected void dumpRequestParameters(HttpServletRequest req) {
    Log subclassLog = LogFactory.getLog(this.getClass());

    @SuppressWarnings("unchecked")
    Map<String, String[]> map = req.getParameterMap();

    for (String key : map.keySet()) {
        String[] values = map.get(key);
        subclassLog.debug("Parameter '" + key + "' = " + Arrays.deepToString(values));
    }
}

From source file:classes.Product.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w ww  .  j  av a 2 s .  co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occuresultSet
 * @throws IOException if an I/O error occuresultSet
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Set<String> keyValues = request.getParameterMap().keySet();

    try {
        PrintWriter printer = response.getWriter();

        //checking for valid table fields
        if (keyValues.contains("productId") && keyValues.contains("productName")
                && keyValues.contains("productDescription") && keyValues.contains("productQuantity")) {

            String productId = request.getParameter("productId");
            String productName = request.getParameter("productName");
            String productDescription = request.getParameter("productDescription");
            String productQuantity = request.getParameter("productQuantity");

            doUpdate(
                    "insert into products " + "(product_id,product_name,product_description,product_quantity)"
                            + " values (?, ?, ?, ?)",
                    productId, productName, productDescription, productQuantity);

        } else {

            printer.println("No match data found for this input");
        }

    } catch (IOException ex) {
        System.err.println("IO Exception " + ex.getMessage());
    }

}

From source file:com.data2semantics.yasgui.server.servlets.AppCacheServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String strongName = getPermutationFromCookies(request.getCookies());

    if (strongName != null && strongName.length() > 0) {
        boolean getCount = request.getParameterMap().keySet().contains("count");

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", new Date().getTime());

        String moduleDir = getServletContext().getRealPath("/Yasgui/");
        String appcacheFile = moduleDir + "/" + strongName;
        if (fetchManifestForDev(request)) {
            appcacheFile += ".dev";
        }//from ww  w  .  j  a  v a2 s  .  com
        appcacheFile += ".appcache";
        String manifestString = IOUtils.toString(new FileReader(appcacheFile));

        PrintWriter out = response.getWriter();
        if (getCount) {
            out.println(Integer.toString(getCacheCount(manifestString)));
        } else {
            response.setContentType("text/cache-manifest");
            out.println(manifestString);

        }
        out.close();
    }

}

From source file:alpha.portal.webapp.controller.CardVersionHistoryController.java

/**
 * Show form./*from   w w w  .ja  v a 2 s  .co m*/
 * 
 * @param m
 *            the m
 * @param request
 *            the request
 * @return the string
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@RequestMapping(method = RequestMethod.GET)
protected String showForm(final Model m, final HttpServletRequest request) throws IOException {

    final String caseId = request.getParameter("case");
    final String version = request.getParameter("version");

    String paging = "";
    for (final Object e : request.getParameterMap().keySet()) {
        if ((e.toString().length() > 2) && e.toString().substring(0, 2).equalsIgnoreCase("d-")) {
            paging = e.toString() + "=" + request.getParameter(e.toString());
            break;
        }
    }
    m.addAttribute("paging", paging);

    Long versionL = null;
    if (StringUtils.isNotBlank(version)) {
        try {
            versionL = Long.parseLong(version);
        } catch (final NumberFormatException e) {
            this.saveError(request, "card.invalidVersion");
            return "redirect:/caseform?caseId=" + caseId;
        }
    }

    if (StringUtils.isBlank(caseId) || !this.caseManager.exists(caseId)) {
        this.saveError(request, "case.invalidId");
        return "redirect:/caseMenu";
    }

    final AlphaCase alphaCase = this.caseManager.get(caseId);
    final List<AlphaCard> versions = this.cardManager.getAllVersions(caseId);
    m.addAttribute("case", alphaCase);
    m.addAttribute("cards", versions);

    AlphaCard activeCard = null;
    final User user = this.getUserManager().getUserByUsername(request.getRemoteUser());
    for (final AlphaCard c : versions) {
        if (c.getAlphaCardIdentifier().getSequenceNumber() == versionL) {
            final Adornment contributor = c.getAlphaCardDescriptor()
                    .getAdornment(AdornmentType.Contributor.getName());
            if ((user == null)
                    || ((contributor != null) && !contributor.getValue().equals(user.getId().toString()))) {
                this.saveError(request, "card.invalidId");
                return "cardVersionHistory";
            }
            activeCard = c;
            break;
        }
    }
    m.addAttribute("activeCard", activeCard);

    return "cardVersionHistory";
}

From source file:io.mapzone.arena.geocode.GeocodeServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//  www.  j  a  v a 2  s.com

        EventManager.instance().publish(new ServletRequestEvent(getServletContext(), req));

        if (req.getParameterMap().isEmpty()) {
            resp.sendError(400, "No parameters found! Please specify at least 'text'.");
            return;
        }

        GeocodeQuery query = extractQuery(req);

        // perform search
        List<Address> addresses = service.geocode(query);

        resp.setStatus(HttpStatus.SC_OK);
        resp.setContentType("application/json;charset=utf-8");
        handleCors(req, resp);

        // convert addresses to result json
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(resp.getOutputStream());
        JSONWriter writer = new JSONWriter(outputStreamWriter);
        writer.object();
        writer.key("results");
        writer.array();
        for (Address address : addresses) {
            writer.value(toJSON(address));
        }
        writer.endArray();
        writer.endObject();
        outputStreamWriter.flush();
        outputStreamWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:de.hybris.platform.chinesepspalipaymockaddon.controllers.pages.AlipayMockController.java

@RequestMapping(value = "/refund", method = RequestMethod.GET)
public String view(final Model model, final HttpServletRequest request) {
    final Map<String, String[]> requestParamMap = request.getParameterMap();
    if (requestParamMap == null) {
        return AlipayMockControllerConstants.Pages.AlipayRefundTestPage;
    }/*  w  w  w .  j a  va 2s .  com*/
    final String baseGateWay = request.getRequestURL().toString();
    model.addAttribute("baseGateWay", baseGateWay);

    model.addAttribute("storefront", (StringUtils.substringBetween(request.getContextPath(), "/")));

    final Map<String, String> clearParams = removeUselessValue(requestParamMap);
    setCSRFToken(clearParams, request);
    return AlipayMockControllerConstants.Pages.AlipayRefundTestPage;
}

From source file:it.marcoberri.mbmeteo.action.chart.GetLastRDial.java

/**
 * Processes requests for both HTTP/*from   w w w . jav  a 2 s .co m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);

    Meteolog meteolog = ds.find(Meteolog.class).order("-time").limit(1).get();

    DefaultValueDataset dataset = new DefaultValueDataset(meteolog.getDayRainfall());

    // get data for diagrams
    DialPlot plot = new DialPlot();
    plot.setView(0.0, 0.0, 1.0, 1.0);
    plot.setDataset(0, dataset);

    GradientPaint gp = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(),
            new Color(170, 170, 220));

    DialBackground db = new DialBackground(gp);

    db.setGradientPaintTransformer(
            new StandardGradientPaintTransformer(GradientPaintTransformType.CENTER_HORIZONTAL));
    plot.setBackground(db);

    StandardDialScale scale = new StandardDialScale();
    scale.setLowerBound(0);
    scale.setUpperBound(50);
    scale.setTickLabelOffset(0.14);
    scale.setTickLabelFont(new Font("Dialog", Font.PLAIN, 10));
    plot.addScale(0, scale);

    DialPointer needle = new DialPointer.Pointer(0);

    plot.addLayer(needle);

    JFreeChart chart1 = new JFreeChart(plot);
    chart1.setTitle("Daily Rain mm");

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart1, dimx, dimy);

    response.setContentType("image/jpeg");
    response.setHeader("Content-Length", "" + f.length());
    response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
    final OutputStream out = response.getOutputStream();
    final FileInputStream in = new FileInputStream(f.toString());
    final int size = in.available();
    final byte[] content = new byte[size];
    in.read(content);
    out.write(content);
    in.close();
    out.close();
}

From source file:it.marcoberri.mbmeteo.action.chart.GetLastTDial.java

/**
 * Processes requests for both HTTP//  w w  w  .  j  a  v  a2s  . c om
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);

    Meteolog meteolog = ds.find(Meteolog.class).order("-time").limit(1).get();

    DefaultValueDataset dataset = new DefaultValueDataset(meteolog.getOutdoorTemperature());

    // get data for diagrams
    DialPlot plot = new DialPlot();
    plot.setView(0.0, 0.0, 1.0, 1.0);
    plot.setDataset(0, dataset);

    GradientPaint gp = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(),
            new Color(170, 170, 220));

    DialBackground db = new DialBackground(gp);

    db.setGradientPaintTransformer(
            new StandardGradientPaintTransformer(GradientPaintTransformType.CENTER_HORIZONTAL));
    plot.setBackground(db);

    StandardDialScale scale = new StandardDialScale();
    scale.setLowerBound(-20);
    scale.setUpperBound(40);
    scale.setTickLabelOffset(0.14);
    scale.setTickLabelFont(new Font("Dialog", Font.PLAIN, 10));
    plot.addScale(0, scale);

    DialPointer needle = new DialPointer.Pointer(0);

    plot.addLayer(needle);

    JFreeChart chart1 = new JFreeChart(plot);
    chart1.setTitle("Temperature C");

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart1, dimx, dimy);

    response.setContentType("image/jpeg");
    response.setHeader("Content-Length", "" + f.length());
    response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
    final OutputStream out = response.getOutputStream();
    final FileInputStream in = new FileInputStream(f.toString());
    final int size = in.available();
    final byte[] content = new byte[size];
    in.read(content);
    out.write(content);
    in.close();
    out.close();
}

From source file:od.lti.LTIController.java

@RequestMapping(value = { "/lti" }, method = RequestMethod.POST)
public String lti(HttpServletRequest request, Model model)
        throws ProviderException, ProviderDataConfigurationException {
    LaunchRequest launchRequest = new LaunchRequest(request.getParameterMap());

    String consumerKey = launchRequest.getOauth_consumer_key();
    String contextId = launchRequest.getContext_id();

    Tenant tenant = mongoTenantRepository.findByConsumersOauthConsumerKey(consumerKey);

    ContextMapping contextMapping = contextMappingRepository.findByTenantIdAndContext(tenant.getId(),
            contextId);/*from ww w  . ja v  a  2s.  c om*/

    if (contextMapping == null) {
        contextMapping = new ContextMapping();
        contextMapping.setContext(contextId);
        contextMapping.setTenantId(tenant.getId());
        contextMapping.setModified(new Date());

        Set<Dashboard> dashboards = tenant.getDashboards();
        if (dashboards != null && !dashboards.isEmpty()) {
            Set<Dashboard> dashboardSet = new HashSet<>();
            for (Dashboard db : dashboards) {
                db.setId(UUID.randomUUID().toString());
                List<Card> cards = db.getCards();
                if (cards != null && !cards.isEmpty()) {
                    for (Card c : cards) {
                        c.setId(UUID.randomUUID().toString());
                    }
                }
                dashboardSet.add(db);
            }
            contextMapping.setDashboards(dashboardSet);
        } else {
            //TODO make better
            throw new RuntimeException("no dashboards");
        }

        contextMapping = contextMappingRepository.save(contextMapping);
    }

    String uuid = UUID.randomUUID().toString();
    //    model.addAttribute("token", uuid);

    // Create a token using spring provided class : LTIAuthenticationToken
    String role;
    if (LTIController.hasInstructorRole(null, launchRequest.getRoles())) {
        role = "ROLE_INSTRUCTOR";
    } else {
        throw new UnauthorizedUserException("Does not have the instructor role");
        //role = "ROLE_STUDENT";
    }

    LTIAuthenticationToken token = new LTIAuthenticationToken(launchRequest,
            launchRequest.getOauth_consumer_key(), launchRequest.toJSON(), uuid,
            AuthorityUtils.commaSeparatedStringToAuthorityList(role));

    // generate session if one doesn't exist
    request.getSession();

    // save details as WebAuthenticationDetails records the remote address and
    // will also set the session Id if a session already exists (it won't create
    // one).
    token.setDetails(new WebAuthenticationDetails(request));

    // authenticationManager injected as spring bean, : LTIAuthenticationProvider
    Authentication authentication = authenticationManager.authenticate(token);

    // Need to set this as thread locale as available throughout
    SecurityContextHolder.getContext().setAuthentication(authentication);

    // Set SPRING_SECURITY_CONTEXT attribute in session as Spring identifies
    // context through this attribute
    request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());

    //return "index";
    String cmUrl = String.format("/cm/%s/dashboard/%s", contextMapping.getId(),
            (new ArrayList<>(contextMapping.getDashboards())).get(0).getId());
    return "redirect:" + cmUrl;
}

From source file:org.spee.sbweb.controller.UploadController.java

@RequestMapping(value = "/validate", method = { RequestMethod.POST,
        RequestMethod.OPTIONS }, produces = "application/json")
public @ResponseBody AlvisModel validate(HttpServletRequest request, String seq) throws Exception {
    AlvisModel alvisModel = requestToAlvisModel(request.getParameterMap());
    WebJSequenceBundle jsb = new WebJSequenceBundle(null, null, alvisModel);

    // process sequences
    if (seq.isEmpty()) {
        alvisModel.setErrorMessage("No sequences to render!");
        return alvisModel;
    }//from  w  ww  .  j  a  v  a 2 s  .co m

    alvisModel.setSequences(seq);
    AlvisDataModel.AlignmentType alignmentType = AlvisDataModel.AlignmentType.AminoAcid;
    ParseAlignmentTask alignmentParser = new ParseAlignmentTask(new StringReader(alvisModel.getSequences()),
            Alvis.AlignmentFormat.FASTA, alignmentType, null);
    ParseAlignmentTask.AlignmentParserResults alignmentResults;
    try {
        alignmentResults = alignmentParser.parse();
        jsb.setAlignment(alignmentResults.alignment);
    } catch (Exception ex) {
        alvisModel.appendErrorMessage(ex.getMessage());
        return alvisModel;
    }

    alvisModel.setSequenceBases(jsb.getAlignment().getLength());
    alvisModel.setSequenceCount(jsb.getAlignment().getSequenceCount());

    if (jsb.getAlignment().getLength() > MAX_SEQUENCE_BASES) {
        alvisModel.appendErrorMessage("Sequence must have less than " + MAX_SEQUENCE_BASES + " bases");
    }
    if (jsb.getAlignment().getSequenceCount() > MAX_SEQUENCE_COUNT) {
        alvisModel.appendErrorMessage("Sequence must have less than " + MAX_SEQUENCE_COUNT + " sequences");
    }
    if (alvisModel.getErrorMessage().length() > 0) {
        return alvisModel;
    } else {
        jsb.setBundleConfig(alvisModel);
        // -1 to fix GUI offset so 1 shows no offset
        Integer startIndex = Integer.valueOf(request.getParameter("startIndex")) - 1;
        // sanitize start index so that the start index the min of (seq
        // length - cols) and user input index
        startIndex = Math.min(startIndex,
                jsb.getAlignment().getLength() - alvisModel.getCellWidthType().getNumberOfColumns());
        // make sure the starting index is greater than 0
        startIndex = Math.max(0, startIndex);
        renderImage(alvisModel, jsb, startIndex);
        return alvisModel;
    }
}