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.wisc.my.redirect.TabSelectingUrlRedirectController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    final String serverName = request.getServerName();
    final PortalUrl portalUrl = this.portalUrlProvider.getPortalUrl(serverName);

    //If strict param matching only run if the request parameter keyset matches the mapped parameter keyset
    final Set<?> requestParameterKeys = request.getParameterMap().keySet();
    if (this.strictParameterMatching && !requestParameterKeys.equals(this.parameterMappings.keySet())) {
        if (this.logger.isInfoEnabled()) {
            this.logger.info("Sending not found error, requested parameter key set " + requestParameterKeys
                    + " does not match mapped parameter key set " + this.parameterMappings.keySet());
        }// w w  w  . j  a  v a  2 s . c  o  m

        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    //Map static parameters
    for (final Map.Entry<String, List<String>> parameterMappingEntry : this.staticParameters.entrySet()) {
        final String name = parameterMappingEntry.getKey();
        final List<String> values = parameterMappingEntry.getValue();

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Adding static parameter '" + name + "' with values: " + values);
        }

        portalUrl.setParameter(name, values.toArray(new String[values.size()]));
    }

    //Map request parameters
    for (final Map.Entry<String, Set<String>> parameterMappingEntry : this.parameterMappings.entrySet()) {
        final String name = parameterMappingEntry.getKey();
        final String[] values = request.getParameterValues(name);

        if (values != null) {
            for (final String mappedName : parameterMappingEntry.getValue()) {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Mapping parameter '" + name + "' to portal parameter '" + mappedName
                            + "' with values: " + Arrays.asList(values));
                }

                portalUrl.setParameter(mappedName, values);
            }
        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug(
                    "Skipping mapped parameter '" + name + "' since it was not specified on the original URL");
        }
    }

    //Set public based on if remoteUser is set
    final String remoteUser = request.getRemoteUser();
    final boolean isAuthenticated = StringUtils.isNotBlank(remoteUser);
    portalUrl.setPublic(!isAuthenticated);

    if (isAuthenticated) {
        portalUrl.setTabIndex(this.privateTabIndex);
    } else {
        portalUrl.setTabIndex(this.publicTabIndex);
    }

    portalUrl.setType(RequestType.ACTION);

    final String redirectUrl = portalUrl.toString();
    if (this.logger.isInfoEnabled()) {
        this.logger.info("Redirecting to: " + redirectUrl);
    }

    return new ModelAndView(new RedirectView(redirectUrl, false));
}

From source file:com.ethercis.vehr.parser.EhrScapeURIParserTest.java

@Test
public void testCompositionQueryParser() throws ServiceManagerException {
    //        Request request = client.newRequest("http://" + hostname + ":8080/rest/v1/ehr?subjectId=1234&subjectNamespace=ABCDEF");
    //        request.method(HttpMethod.POST);
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getRequestURI()).thenReturn("/rest/v1/composition");
    Map<String, String[]> parameters = new HashMap<String, String[]>();
    parameters.put("format", new String[] { "RAW" });
    when(request.getParameterMap()).thenReturn(parameters);
    Map<String, String[]> headers = new HashMap<String, String[]>();
    headers.put("Content-Type", new String[] { "application/xml" });
    when(request.getHeaderNames()).thenReturn(new IteratorEnumeration<String>(headers.keySet().iterator()));
    when(request.getHeader("Content-Type")).thenReturn("application/xml");
    when(request.getMethod()).thenReturn("POST");
    uriParser.parse(request);//from ww  w  .  j  av a2 s  .  c o m
    assertEquals("POST", uriParser.identifyMethod().toUpperCase());
    assertEquals("XML", uriParser.identifyParametersAsProperties().getClientProperty("format").toString());

    request = mock(HttpServletRequest.class);
    when(request.getRequestURI()).thenReturn("/rest/v1/composition/123456?format=FLAT");
    parameters = new HashMap<>();
    parameters.put("format", new String[] { "FLAT" });
    //        parameters.put("templateId", new String[]{"test%20test"});
    when(request.getParameterMap()).thenReturn(parameters);
    headers = new HashMap<>();
    headers.put("Accept", new String[] { "application/json" });
    when(request.getHeaderNames()).thenReturn(new IteratorEnumeration<String>(headers.keySet().iterator()));
    when(request.getHeader("Accept")).thenReturn("application/json");
    when(request.getMethod()).thenReturn("GET");
    uriParser.parse(request);
    assertEquals("GET", uriParser.identifyMethod().toUpperCase());
    assertEquals("FLAT", uriParser.identifyParametersAsProperties().getClientProperty("format").toString());
    //        assertEquals("test%20test", uriParser.identifyParametersAsProperties().getClientProperty("templateId").toString());
    assertEquals("123456", uriParser.identifyParametersAsProperties().getClientProperty("uid").toString());

    request = mock(HttpServletRequest.class);
    when(request.getRequestURI()).thenReturn("/rest/v1/composition/123456?format=FLAT");
    parameters = new HashMap<>();
    parameters.put("format", new String[] { "FLAT" });
    when(request.getParameterMap()).thenReturn(parameters);
    headers = new HashMap<>();
    headers.put("Content-Type", new String[] { "application/json" });
    when(request.getHeaderNames()).thenReturn(new IteratorEnumeration<String>(headers.keySet().iterator()));
    when(request.getHeader("Content-Type")).thenReturn("application/json");
    when(request.getMethod()).thenReturn("PUT");
    uriParser.parse(request);
    assertEquals("PUT", uriParser.identifyMethod().toUpperCase());
    assertEquals("FLAT", uriParser.identifyParametersAsProperties().getClientProperty("format").toString());
    assertEquals("123456", uriParser.identifyParametersAsProperties().getClientProperty("uid").toString());

    request = mock(HttpServletRequest.class);
    when(request.getRequestURI()).thenReturn("/rest/v1/composition/8fd2bea0-9e0e-11e5-8994-feff819cdc9f");
    parameters = new HashMap<>();
    parameters.put("format", new String[] { "RAW" });
    when(request.getParameterMap()).thenReturn(parameters);
    headers = new HashMap<>();
    headers.put("Accept", new String[] { "application/xml" });
    when(request.getHeaderNames()).thenReturn(new IteratorEnumeration<String>(headers.keySet().iterator()));
    when(request.getHeader("Accept")).thenReturn("application/xml");
    when(request.getMethod()).thenReturn("GET");
    uriParser.parse(request);
    assertEquals("GET", uriParser.identifyMethod().toUpperCase());
    assertEquals("8fd2bea0-9e0e-11e5-8994-feff819cdc9f",
            uriParser.identifyParametersAsProperties().getClientProperty("uid").toString());
    assertEquals("XML", uriParser.identifyParametersAsProperties().getClientProperty("format").toString());

    request = mock(HttpServletRequest.class);
    when(request.getRequestURI()).thenReturn("/rest/v1/composition/8fd2bea0-9e0e-11e5-8994-feff819cdc9f");
    parameters = new HashMap<>();
    when(request.getParameterMap()).thenReturn(parameters);
    headers = new HashMap<>();
    headers.put("Content-Type", new String[] { "application/json" });
    when(request.getHeaderNames()).thenReturn(new IteratorEnumeration<String>(headers.keySet().iterator()));
    when(request.getHeader("Content-Type")).thenReturn("application/xml");
    when(request.getMethod()).thenReturn("DELETE");
    uriParser.parse(request);
    assertEquals("DELETE", uriParser.identifyMethod().toUpperCase());
    assertEquals("rest/v1/composition", uriParser.identifyPath());
    assertEquals("8fd2bea0-9e0e-11e5-8994-feff819cdc9f",
            uriParser.identifyParametersAsProperties().getClientProperty("uid").toString());
}

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

/**
 * Processes requests for both HTTP//from www  .j  a  v  a2  s. c o 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);
    final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00");
    final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00");
    final String field = Default.toString(params.get("field"), "outdoorTemperature");
    final String period = Default.toString(params.get("period"), "day");

    request.getSession().setAttribute("from", params.get("from"));
    request.getSession().setAttribute("to", params.get("to"));

    final String cacheKey = getCacheKey(params);

    if (cacheReadEnable) {

        final Query q = ds.find(Cache.class);
        q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName());

        final Cache c = (Cache) q.get();

        if (c == null) {
            log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found");
        }

        if (c != null) {
            final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS()
                    .findOne(new ObjectId(c.getGridId()));
            if (imageForOutput != null) {
                ds.save(c);

                try {
                    response.setHeader("Content-Length", "" + imageForOutput.getLength());
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + imageForOutput.getFilename() + "\"");
                    final OutputStream out = response.getOutputStream();
                    final InputStream in = imageForOutput.getInputStream();
                    final byte[] content = new byte[(int) imageForOutput.getLength()];
                    in.read(content);
                    out.write(content);
                    in.close();
                    out.close();
                    return;
                } catch (Exception e) {
                    log.error(e);
                }

            } else {
                log.error("file not in db");
            }
        }
    }

    final String formatIn = getFormatIn(period);
    final String formatOut = getFormatOut(period);

    final Query q = ds.createQuery(MapReduceMinMax.class).disableValidation();

    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    final List<Date> datesIn = getRangeDate(dFrom, dTo);
    final HashSet<String> datesInString = new HashSet<String>();

    for (Date d : datesIn) {
        datesInString.add(DateTimeUtil.dateFormat(formatIn, d));
    }

    if (datesIn != null && !datesIn.isEmpty()) {
        q.filter("_id in", datesInString);
    }
    q.order("_id");

    final List<MapReduceMinMax> mapReduceResult = q.asList();
    final TimeSeries serieMin = new TimeSeries("Min");
    final TimeSeries serieMax = new TimeSeries("Max");

    for (MapReduceMinMax m : mapReduceResult) {
        try {

            final Date tmpDate = DateTimeUtil.getDate(formatIn, m.getId().toString());
            if (tmpDate == null) {
                continue;
            }

            final Millisecond t = new Millisecond(tmpDate);

            ChartEnumMinMaxHelper chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, "min");
            Method method = m.getClass().getMethod(chartEnum.getMethod());
            Number n = (Number) method.invoke(m);
            serieMin.add(t, n);

            chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, "max");
            method = m.getClass().getMethod(chartEnum.getMethod());
            n = (Number) method.invoke(m);
            serieMax.add(t, n);

        } catch (IllegalAccessException ex) {
            log.error(ex);
        } catch (IllegalArgumentException ex) {
            log.error(ex);
        } catch (InvocationTargetException ex) {
            log.error(ex);
        } catch (NoSuchMethodException ex) {
            log.error(ex);
        } catch (SecurityException ex) {
            log.error(ex);
        }
    }

    final ChartEnumMinMaxHelper chartData = ChartEnumMinMaxHelper.getByFieldAndType(field, "min");

    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(serieMin);
    dataset.addSeries(serieMax);

    final JFreeChart chart = ChartFactory.createTimeSeriesChart("Max/Min", "", chartData.getUm(), dataset, true,
            false, false);
    final XYPlot plot = (XYPlot) chart.getPlot();
    final DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat(formatOut));

    axis.setVerticalTickLabels(true);

    if (field.toUpperCase().indexOf("PRESSURE") != -1) {
        plot.getRangeAxis().setRange(chartPressureMin, chartPressureMax);
    }

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

    try {

        if (cacheWriteEnable) {
            final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f);
            gfsFile.setFilename(f.getName());
            gfsFile.save();

            final Cache c = new Cache();
            c.setServletName(this.getClass().getName());
            c.setCacheKey(cacheKey);
            c.setGridId(gfsFile.getId().toString());

            ds.save(c);

        }

        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();
    } catch (Exception e) {
        log.error(e);
    } finally {
        f.delete();
    }

}

From source file:mx.edu.um.mateo.rh.web.EstudiosEmpleadoController.java

@Transactional
@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response,
        @Valid EstudiosEmpleado estudiosEmpleado, BindingResult bindingResult, Errors errors, Model modelo,
        RedirectAttributes redirectAttributes) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }// w  w w  .  ja  v  a2  s .  c  o m
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        return Constantes.PATH_ESTUDIOSEMPLEADO_NUEVO;
    }

    try {
        List nivelesEstudios = Arrays.asList(NivelEstudios.values());
        modelo.addAttribute(Constantes.CONTAINSKEY_ESTUDIOSEMPLEADO, nivelesEstudios);
        log.debug("estudiosEmpleado " + estudiosEmpleado.toString());
        estudiosEmpleado = estudiosEmpleadoDao.crea(estudiosEmpleado);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear estudiosEmpleado", e);
        return Constantes.PATH_ESTUDIOSEMPLEADO_NUEVO;
    }

    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "estudiosEmpleado.creado.message");
    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
            new String[] { estudiosEmpleado.getNombreEstudios().toString() });

    return "redirect:" + Constantes.PATH_ESTUDIOSEMPLEADO_VER + "/" + estudiosEmpleado.getId();
}

From source file:org.ktunaxa.referral.server.mvc.ProxyController.java

@SuppressWarnings("unchecked")
@RequestMapping(value = "/proxy")
public final void proxyAjaxCall(@RequestParam(required = true, value = "url") String url,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    // URL needs to be url decoded
    url = URLDecoder.decode(url, "utf-8");

    HttpClient client = new HttpClient();
    try {/*from www  .  j  a v a 2s  . co  m*/

        HttpMethod method = null;

        // Split this according to the type of request
        if ("GET".equals(request.getMethod())) {

            method = new GetMethod(url);
            NameValuePair[] pairs = new NameValuePair[request.getParameterMap().size()];
            int i = 0;
            for (Object name : request.getParameterMap().keySet()) {
                pairs[i++] = new NameValuePair((String) name, request.getParameter((String) name));
            }
            method.setQueryString(pairs);

        } else if ("POST".equals(request.getMethod())) {

            method = new PostMethod(url);

            // Set any eventual parameters that came with our original
            // request (POST params, for instance)
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {

                String paramName = (String) paramNames.nextElement();
                ((PostMethod) method).setParameter(paramName, request.getParameter(paramName));
            }

        } else {

            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Execute the method
        client.executeMethod(method);

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if (header.getName().equalsIgnoreCase("Content-Type")) {

                response.setContentType(header.getValue());
            }
        }

        // Write the body, flush and close
        response.getOutputStream().write(method.getResponseBody());

    } catch (HttpException e) {

        // log.error("Oops, something went wrong in the HTTP proxy", null, e);
        response.getOutputStream().write(e.toString().getBytes("UTF-8"));
        throw e;

    } catch (IOException e) {

        e.printStackTrace();
        response.getOutputStream().write(e.toString().getBytes("UTF-8"));
        throw e;
    }
}

From source file:com.jsmartframework.web.manager.ExpressionHandler.java

Map<String, String> getRequestExpressions(HttpServletRequest request) {
    Map<String, String> expressions = new LinkedHashMap<>();
    for (String param : request.getParameterMap().keySet()) {
        String expr = extractExpression(request, param);
        if (expr != null) {
            expressions.put(param, expr);
        }// w ww  . ja  va  2s  . c o m
    }
    return expressions;
}

From source file:com.redhat.rhn.frontend.struts.StrutsDelegate.java

/**
 * Creates a date picker object with the given name and prepopulates the date
 * with values from the given request's parameters. Prepopulates the form with
 * these values as well./*from  w w w  . j a  va 2s . c om*/
 * Your dyna action picker must either be a struts datePickerForm, or
 * possess all of datePickerForm's fields.
 * @param request The request from which to get initial form field values.
 * @param form The datePickerForm
 * @param name The prefix for the date picker form fields, usually "date"
 * @param yearDirection One of DatePicker's year range static variables.
 * @return The created and prepopulated date picker object
 * @see com.redhat.rhn.common.util.DatePicker
 */
public DatePicker prepopulateDatePicker(HttpServletRequest request, DynaActionForm form, String name,
        int yearDirection) {
    //Create the date picker.
    DatePicker p = getDatePicker(name, yearDirection);

    //prepopulate the date for this picker
    p.readMap(request.getParameterMap());

    //prepopulate the form for this picker
    p.writeToForm(form);
    if (!StringUtils.isEmpty(request.getParameter(DatePicker.USE_DATE))) {
        Boolean preset = Boolean.valueOf(request.getParameter(DatePicker.USE_DATE));
        form.set(DatePicker.USE_DATE, preset);
    } else if (form.getMap().containsKey(DatePicker.USE_DATE)) {
        form.set(DatePicker.USE_DATE, Boolean.FALSE);
    }
    request.setAttribute(name, p);
    //give back the date picker
    return p;
}

From source file:co.propack.sample.vendor.nullPaymentGateway.web.controller.NullPaymentGatewayProcessorController.java

@RequestMapping(value = "/null-checkout/process", method = RequestMethod.POST)
public @ResponseBody String processTransparentRedirectForm(HttpServletRequest request) {
    Map<String, String[]> paramMap = request.getParameterMap();

    String transactionAmount = "";
    String orderId = "";
    String billingFirstName = "";
    String billingLastName = "";
    String billingAddressLine1 = "";
    String billingAddressLine2 = "";
    String billingCity = "";
    String billingState = "";
    String billingZip = "";
    String billingCountry = "";
    String shippingFirstName = "";
    String shippingLastName = "";
    String shippingAddressLine1 = "";
    String shippingAddressLine2 = "";
    String shippingCity = "";
    String shippingState = "";
    String shippingZip = "";
    String shippingCountry = "";
    String creditCardName = "";
    String creditCardNumber = "";
    String creditCardExpDate = "";
    String creditCardCVV = "";
    String cardType = "UNKNOWN";

    String resultMessage = "";
    String resultSuccess = "";
    String gatewayTransactionId = UUID.randomUUID().toString();

    if (paramMap.get(NullPaymentGatewayConstants.TRANSACTION_AMT) != null
            && paramMap.get(NullPaymentGatewayConstants.TRANSACTION_AMT).length > 0) {
        transactionAmount = paramMap.get(NullPaymentGatewayConstants.TRANSACTION_AMT)[0];
    }//from   w ww .j  a va  2  s .  c  o m

    if (paramMap.get(NullPaymentGatewayConstants.ORDER_ID) != null
            && paramMap.get(NullPaymentGatewayConstants.ORDER_ID).length > 0) {
        orderId = paramMap.get(NullPaymentGatewayConstants.ORDER_ID)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.BILLING_FIRST_NAME) != null
            && paramMap.get(NullPaymentGatewayConstants.BILLING_FIRST_NAME).length > 0) {
        billingFirstName = paramMap.get(NullPaymentGatewayConstants.BILLING_FIRST_NAME)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.BILLING_LAST_NAME) != null
            && paramMap.get(NullPaymentGatewayConstants.BILLING_LAST_NAME).length > 0) {
        billingLastName = paramMap.get(NullPaymentGatewayConstants.BILLING_LAST_NAME)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.BILLING_ADDRESS_LINE1) != null
            && paramMap.get(NullPaymentGatewayConstants.BILLING_ADDRESS_LINE1).length > 0) {
        billingAddressLine1 = paramMap.get(NullPaymentGatewayConstants.BILLING_ADDRESS_LINE1)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.BILLING_ADDRESS_LINE2) != null
            && paramMap.get(NullPaymentGatewayConstants.BILLING_ADDRESS_LINE2).length > 0) {
        billingAddressLine2 = paramMap.get(NullPaymentGatewayConstants.BILLING_ADDRESS_LINE2)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.BILLING_CITY) != null
            && paramMap.get(NullPaymentGatewayConstants.BILLING_CITY).length > 0) {
        billingCity = paramMap.get(NullPaymentGatewayConstants.BILLING_CITY)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.BILLING_STATE) != null
            && paramMap.get(NullPaymentGatewayConstants.BILLING_STATE).length > 0) {
        billingState = paramMap.get(NullPaymentGatewayConstants.BILLING_STATE)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.BILLING_ZIP) != null
            && paramMap.get(NullPaymentGatewayConstants.BILLING_ZIP).length > 0) {
        billingZip = paramMap.get(NullPaymentGatewayConstants.BILLING_ZIP)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.BILLING_COUNTRY) != null
            && paramMap.get(NullPaymentGatewayConstants.BILLING_COUNTRY).length > 0) {
        billingCountry = paramMap.get(NullPaymentGatewayConstants.BILLING_COUNTRY)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.SHIPPING_FIRST_NAME) != null
            && paramMap.get(NullPaymentGatewayConstants.SHIPPING_FIRST_NAME).length > 0) {
        shippingFirstName = paramMap.get(NullPaymentGatewayConstants.SHIPPING_FIRST_NAME)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.SHIPPING_LAST_NAME) != null
            && paramMap.get(NullPaymentGatewayConstants.SHIPPING_LAST_NAME).length > 0) {
        shippingLastName = paramMap.get(NullPaymentGatewayConstants.SHIPPING_LAST_NAME)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.SHIPPING_ADDRESS_LINE1) != null
            && paramMap.get(NullPaymentGatewayConstants.SHIPPING_ADDRESS_LINE1).length > 0) {
        shippingAddressLine1 = paramMap.get(NullPaymentGatewayConstants.SHIPPING_ADDRESS_LINE1)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.SHIPPING_ADDRESS_LINE2) != null
            && paramMap.get(NullPaymentGatewayConstants.SHIPPING_ADDRESS_LINE2).length > 0) {
        shippingAddressLine2 = paramMap.get(NullPaymentGatewayConstants.SHIPPING_ADDRESS_LINE2)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.SHIPPING_CITY) != null
            && paramMap.get(NullPaymentGatewayConstants.SHIPPING_CITY).length > 0) {
        shippingCity = paramMap.get(NullPaymentGatewayConstants.SHIPPING_CITY)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.SHIPPING_STATE) != null
            && paramMap.get(NullPaymentGatewayConstants.SHIPPING_STATE).length > 0) {
        shippingState = paramMap.get(NullPaymentGatewayConstants.SHIPPING_STATE)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.SHIPPING_ZIP) != null
            && paramMap.get(NullPaymentGatewayConstants.SHIPPING_ZIP).length > 0) {
        shippingZip = paramMap.get(NullPaymentGatewayConstants.SHIPPING_ZIP)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.SHIPPING_COUNTRY) != null
            && paramMap.get(NullPaymentGatewayConstants.SHIPPING_COUNTRY).length > 0) {
        shippingCountry = paramMap.get(NullPaymentGatewayConstants.SHIPPING_COUNTRY)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_NAME) != null
            && paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_NAME).length > 0) {
        creditCardName = paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_NAME)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_NUMBER) != null
            && paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_NUMBER).length > 0) {
        creditCardNumber = paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_NUMBER)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_EXP_DATE) != null
            && paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_EXP_DATE).length > 0) {
        creditCardExpDate = paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_EXP_DATE)[0];
    }

    if (paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_CVV) != null
            && paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_CVV).length > 0) {
        creditCardCVV = paramMap.get(NullPaymentGatewayConstants.CREDIT_CARD_CVV)[0];
    }

    CreditCardValidator visaValidator = new CreditCardValidator(CreditCardValidator.VISA);
    CreditCardValidator amexValidator = new CreditCardValidator(CreditCardValidator.AMEX);
    CreditCardValidator mcValidator = new CreditCardValidator(CreditCardValidator.MASTERCARD);
    CreditCardValidator discoverValidator = new CreditCardValidator(CreditCardValidator.DISCOVER);

    if (StringUtils.isNotBlank(transactionAmount) && StringUtils.isNotBlank(creditCardNumber)
            && StringUtils.isNotBlank(creditCardExpDate)) {

        boolean validCard = false;
        if (visaValidator.isValid(creditCardNumber)) {
            validCard = true;
            cardType = "VISA";
        } else if (amexValidator.isValid(creditCardNumber)) {
            validCard = true;
            cardType = "AMEX";
        } else if (mcValidator.isValid(creditCardNumber)) {
            validCard = true;
            cardType = "MASTERCARD";
        } else if (discoverValidator.isValid(creditCardNumber)) {
            validCard = true;
            cardType = "DISCOVER";
        }

        boolean validDateFormat = false;
        boolean validDate = false;
        String[] parsedDate = creditCardExpDate.split("/");
        if (parsedDate.length == 2) {
            String expMonth = parsedDate[0];
            String expYear = parsedDate[1];
            try {
                DateTime expirationDate = new DateTime(Integer.parseInt("20" + expYear),
                        Integer.parseInt(expMonth), 1, 0, 0);
                expirationDate = expirationDate.dayOfMonth().withMaximumValue();
                validDate = expirationDate.isAfterNow();
                validDateFormat = true;
            } catch (Exception e) {
                //invalid date format
            }
        }

        if (!validDate || !validDateFormat) {
            transactionAmount = "0";
            resultMessage = "cart.payment.expiration.invalid";
            resultSuccess = "false";
        } else if (!validCard) {
            transactionAmount = "0";
            resultMessage = "cart.payment.card.invalid";
            resultSuccess = "false";
        } else {
            resultMessage = "Success!";
            resultSuccess = "true";
        }

    } else {
        transactionAmount = "0";
        resultMessage = "cart.payment.invalid";
        resultSuccess = "false";
    }

    StringBuffer response = new StringBuffer();
    response.append("<!DOCTYPE HTML>");
    response.append("<!--[if lt IE 7]> <html class=\"no-js lt-ie9 lt-ie8 lt-ie7\" lang=\"en\"> <![endif]-->");
    response.append("<!--[if IE 7]> <html class=\"no-js lt-ie9 lt-ie8\" lang=\"en\"> <![endif]-->");
    response.append("<!--[if IE 8]> <html class=\"no-js lt-ie9\" lang=\"en\"> <![endif]-->");
    response.append("<!--[if gt IE 8]><!--> <html class=\"no-js\" lang=\"en\"> <!--<![endif]-->");
    response.append("<body>");
    response.append("<form action=\"" + paymentGatewayConfiguration.getTransparentRedirectReturnUrl()
            + "\" method=\"POST\" id=\"NullPaymentGatewayRedirectForm\" name=\"NullPaymentGatewayRedirectForm\">");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.TRANSACTION_AMT
            + "\" value=\"" + transactionAmount + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.ORDER_ID + "\" value=\""
            + orderId + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.GATEWAY_TRANSACTION_ID
            + "\" value=\"" + gatewayTransactionId + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.RESULT_MESSAGE
            + "\" value=\"" + resultMessage + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.RESULT_SUCCESS
            + "\" value=\"" + resultSuccess + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.BILLING_FIRST_NAME
            + "\" value=\"" + billingFirstName + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.BILLING_LAST_NAME
            + "\" value=\"" + billingLastName + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.BILLING_ADDRESS_LINE1
            + "\" value=\"" + billingAddressLine1 + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.BILLING_ADDRESS_LINE2
            + "\" value=\"" + billingAddressLine2 + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.BILLING_CITY + "\" value=\""
            + billingCity + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.BILLING_STATE + "\" value=\""
            + billingState + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.BILLING_ZIP + "\" value=\""
            + billingZip + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.BILLING_COUNTRY
            + "\" value=\"" + billingCountry + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.SHIPPING_FIRST_NAME
            + "\" value=\"" + shippingFirstName + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.SHIPPING_LAST_NAME
            + "\" value=\"" + shippingLastName + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.SHIPPING_ADDRESS_LINE1
            + "\" value=\"" + shippingAddressLine1 + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.SHIPPING_ADDRESS_LINE2
            + "\" value=\"" + shippingAddressLine2 + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.SHIPPING_CITY + "\" value=\""
            + shippingCity + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.SHIPPING_STATE
            + "\" value=\"" + shippingState + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.SHIPPING_ZIP + "\" value=\""
            + shippingZip + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.SHIPPING_COUNTRY
            + "\" value=\"" + shippingCountry + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.CREDIT_CARD_NAME
            + "\" value=\"" + creditCardName + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.CREDIT_CARD_LAST_FOUR
            + "\" value=\"" + StringUtils.right(creditCardNumber, 4) + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.CREDIT_CARD_TYPE
            + "\" value=\"" + cardType + "\"/>");
    response.append("<input type=\"hidden\" name=\"" + NullPaymentGatewayConstants.CREDIT_CARD_EXP_DATE
            + "\" value=\"" + creditCardExpDate + "\"/>");

    response.append("<input type=\"submit\" value=\"Please Click Here To Complete Checkout\"/>");
    response.append("</form>");
    response.append("<script type=\"text/javascript\">");
    response.append("document.getElementById('NullPaymentGatewayRedirectForm').submit();");
    response.append("</script>");
    response.append("</body>");
    response.append("</html>");

    return response.toString();
}