Example usage for javax.servlet.http HttpServletRequest getScheme

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

Introduction

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

Prototype

public String getScheme();

Source Link

Document

Returns the name of the scheme used to make this request, for example, <code>http</code>, <code>https</code>, or <code>ftp</code>.

Usage

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Show HTTP header information./* w w w.  j av  a2s.c om*/
 *
 * @param req Description of the Parameter
 */
protected void showRequestInfo(HttpServletRequest req) {

    System.out.println();
    System.out.println("SlideDAV Request Info");
    System.out.println();

    // Show generic info
    System.out.println("Encoding : " + req.getCharacterEncoding());
    System.out.println("Length : " + req.getContentLength());
    System.out.println("Type : " + req.getContentType());

    System.out.println();
    System.out.println("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
        System.out.println();
    }

    System.out.println();

    System.out.println("Protocol : " + req.getProtocol());
    System.out.println("Address : " + req.getRemoteAddr());
    System.out.println("Host : " + req.getRemoteHost());
    System.out.println("Scheme : " + req.getScheme());
    System.out.println("Server Name : " + req.getServerName());
    System.out.println("Server Port : " + req.getServerPort());

    System.out.println();
    System.out.println("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        System.out.println(req.getAttribute(attributeName).toString());
    }

    System.out.println();

    // Show HTTP info
    System.out.println();
    System.out.println("HTTP Header Info");
    System.out.println();

    System.out.println("Authentication Type : " + req.getAuthType());
    System.out.println("HTTP Method : " + req.getMethod());
    System.out.println("Path Info : " + req.getPathInfo());
    System.out.println("Path translated : " + req.getPathTranslated());
    System.out.println("Query string : " + req.getQueryString());
    System.out.println("Remote user : " + req.getRemoteUser());
    System.out.println("Requested session id : " + req.getRequestedSessionId());
    System.out.println("Request URI : " + req.getRequestURI());
    System.out.println("Context path : " + req.getContextPath());
    System.out.println("Servlet path : " + req.getServletPath());
    System.out.println("User principal : " + req.getUserPrincipal());

    System.out.println();
    System.out.println("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        System.out.println(req.getHeader(headerName));
    }

    System.out.println();
    System.out.println();

}

From source file:org.apache.hadoop.hdfs.server.datanode.DatanodeJspHelper.java

static void generateFileChunks(JspWriter out, HttpServletRequest req, Configuration conf)
        throws IOException, InterruptedException {
    long startOffset = 0;
    int datanodePort = 0;

    final String namenodeInfoPortStr = req.getParameter("namenodeInfoPort");
    final String nnAddr = req.getParameter(JspHelper.NAMENODE_ADDRESS);
    if (nnAddr == null) {
        out.print(JspHelper.NAMENODE_ADDRESS + " url param is null");
        return;//  w ww.  j a va2  s  .  co  m
    }
    final String tokenString = req.getParameter(JspHelper.DELEGATION_PARAMETER_NAME);
    UserGroupInformation ugi = JspHelper.getUGI(req, conf);
    int namenodeInfoPort = -1;
    if (namenodeInfoPortStr != null)
        namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr);

    final String filename = JspHelper
            .validatePath(StringEscapeUtils.unescapeHtml(req.getParameter("filename")));
    if (filename == null) {
        out.print("Invalid input (filename absent)");
        return;
    }

    final Long blockId = JspHelper.validateLong(req.getParameter("blockId"));
    if (blockId == null) {
        out.print("Invalid input (blockId absent)");
        return;
    }

    final DFSClient dfs = getDFSClient(ugi, nnAddr, conf);

    String bpid = null;
    Token<BlockTokenIdentifier> blockToken = BlockTokenSecretManager.DUMMY_TOKEN;
    List<LocatedBlock> blks = dfs.getNamenode().getBlockLocations(filename, 0, Long.MAX_VALUE)
            .getLocatedBlocks();
    if (blks == null || blks.size() == 0) {
        out.print("Can't locate file blocks");
        dfs.close();
        return;
    }

    boolean needBlockToken = conf.getBoolean(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY,
            DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_DEFAULT);

    for (int i = 0; i < blks.size(); i++) {
        if (blks.get(i).getBlock().getBlockId() == blockId) {
            bpid = blks.get(i).getBlock().getBlockPoolId();
            if (needBlockToken) {
                blockToken = blks.get(i).getBlockToken();
            }
            break;
        }
    }

    final Long genStamp = JspHelper.validateLong(req.getParameter("genstamp"));
    if (genStamp == null) {
        out.print("Invalid input (genstamp absent)");
        return;
    }

    long blockSize = 0;
    final String blockSizeStr = req.getParameter("blockSize");
    if (blockSizeStr == null) {
        out.print("Invalid input (blockSize absent)");
        return;
    }
    blockSize = Long.parseLong(blockSizeStr);

    final int chunkSizeToView = JspHelper.string2ChunkSizeToView(req.getParameter("chunkSizeToView"),
            getDefaultChunkSize(conf));

    String startOffsetStr = req.getParameter("startOffset");
    if (startOffsetStr == null || Long.parseLong(startOffsetStr) < 0)
        startOffset = 0;
    else
        startOffset = Long.parseLong(startOffsetStr);

    String datanodePortStr = req.getParameter("datanodePort");
    if (datanodePortStr == null) {
        out.print("Invalid input (datanodePort absent)");
        return;
    }
    datanodePort = Integer.parseInt(datanodePortStr);
    out.print("<h3>File: ");
    JspHelper.printPathWithLinks(filename, out, namenodeInfoPort, tokenString, nnAddr);
    out.print("</h3><hr>");
    String parent = new File(filename).getParent();
    JspHelper.printGotoForm(out, namenodeInfoPort, tokenString, parent, nnAddr);
    out.print("<hr>");
    out.print("<a href=\"/browseDirectory.jsp?dir=" + URLEncoder.encode(parent, "UTF-8") + "&namenodeInfoPort="
            + namenodeInfoPort + JspHelper.getDelegationTokenUrlParam(tokenString)
            + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr)
            + "\"><i>Go back to dir listing</i></a><br>");
    out.print("<a href=\"#viewOptions\">Advanced view/download options</a><br>");
    out.print("<hr>");

    String authority = req.getServerName() + ":" + req.getServerPort();
    String nextUrl = generateLinksForAdjacentBlock(NEXT_BLOCK, authority, datanodePort, startOffset,
            chunkSizeToView, blockSize, blockId, genStamp, dfs, filename, conf, req.getScheme(), tokenString,
            namenodeInfoPort, nnAddr);
    if (nextUrl != null) {
        out.print("<a href=\"" + nextUrl + "\">View Next chunk</a>&nbsp;&nbsp;");
    }

    String prevUrl = generateLinksForAdjacentBlock(PREV_BLOCK, authority, datanodePort, startOffset,
            chunkSizeToView, blockSize, blockId, genStamp, dfs, filename, conf, req.getScheme(), tokenString,
            namenodeInfoPort, nnAddr);
    if (prevUrl != null) {
        out.print("<a href=\"" + prevUrl + "\">View Prev chunk</a>&nbsp;&nbsp;");
    }

    out.print("<hr>");
    out.print("<textarea cols=\"100\" rows=\"25\" wrap=\"virtual\" style=\"width:100%\" READONLY>");
    try {
        JspHelper.streamBlockInAscii(new InetSocketAddress(req.getServerName(), datanodePort), bpid, blockId,
                blockToken, genStamp, blockSize, startOffset, chunkSizeToView, out, conf, dfs.getConf(), dfs,
                getSaslDataTransferClient(req));
    } catch (Exception e) {
        out.print(e);
    }
    out.print("</textarea>");
    dfs.close();
}

From source file:org.jahia.modules.userregistration.actions.NewReservation.java

public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, final Resource resource,
        JCRSessionWrapper session, final Map<String, List<String>> parameters, URLResolver urlResolver)
        throws Exception {
    final HttpServletRequest requ = req;
    final String nom = getParameter(parameters, "nom");
    final String prenom = getParameter(parameters, "prenom");
    final String adresse = getParameter(parameters, "adresse");
    final String codePostal = getParameter(parameters, "codePostal");
    final String ville = getParameter(parameters, "ville");
    final String telephone = getParameter(parameters, "telephone");
    final String email = getParameter(parameters, "email");
    final String places = getParameter(parameters, "places");

    if (StringUtils.isEmpty(nom) || StringUtils.isEmpty(prenom) || StringUtils.isEmpty(adresse)
            || StringUtils.isEmpty(email)) {
        return ActionResult.BAD_REQUEST;
    }//  w  w w .  ja  v  a2  s. c  o m
    /*
     * final Properties properties = new Properties();
     * properties.put("j:email",parameters.get("desired_email").get(0));
     * properties.put("j:firstName",parameters.get("desired_firstname").get(
     * 0));
     * properties.put("j:lastName",parameters.get("desired_lastname").get(0)
     * ); for (Map.Entry<String, List<String>> param :
     * parameters.entrySet()) { if (param.getKey().startsWith("j:")) {
     * String value = getParameter(parameters, param.getKey()); if (value !=
     * null) { properties.put(param.getKey(), value); } } }
     */
    JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Boolean>() {
        @Override
        public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException {

            // final JCRUserNode user =
            // userManagerService.createUser(username, password, properties,
            // session);
            // session.save();
            JCRNodeWrapper reservationFolder = session.getNode("/sites/LARBRE/contents/reservations");
            JCRNodeWrapper emailFolder;
            if (reservationFolder.hasNode(email))
                emailFolder = reservationFolder.getNode(email);
            else
                emailFolder = reservationFolder.addNode(email, "jnt:contentFolder");
            session.save();
            String key = generateKey(email);
            JCRNodeWrapper uneReservation = emailFolder.addNode(key, "jnt:uneReservation");
            uneReservation.setProperty("nom", nom);
            uneReservation.setProperty("prenom", prenom);
            uneReservation.setProperty("adresse", adresse);
            uneReservation.setProperty("codePostal", codePostal);
            uneReservation.setProperty("ville", ville);
            uneReservation.setProperty("telephone", telephone);
            uneReservation.setProperty("email", email);
            uneReservation.setProperty("places", places);
            session.save();
            if (mailService.isEnabled()) {
                // Prepare mail to be sent :
                boolean toAdministratorMail = Boolean
                        .valueOf(getParameter(parameters, "toAdministrator", "false"));
                String cc = toAdministratorMail ? mailService.getSettings().getTo()
                        : getParameter(parameters, "cc");
                String from = cc;
                logger.info("send copie to :" + cc);
                //String cc = parameters.get("cc") == null ? null : getParameter(parameters, "cc");
                String bcc = parameters.get("bcc") == null ? null : getParameter(parameters, "bcc");

                Map<String, Object> bindings = new HashMap<String, Object>();
                final JCRNodeWrapper node = resource.getNode();
                logger.info("********Node :" + node.getName());
                logger.info("Template path:" + templatePath);
                bindings.put("reservation", uneReservation);
                bindings.put("confirmationlink",
                        requ.getScheme() + "://" + requ.getServerName() + ":" + requ.getServerPort()
                                + Jahia.getContextPath() + Render.getRenderServletPath() + "/live/"
                                + node.getLanguage() + node.getPath() + ".confirmationReservation.do?email="
                                + email + "&key=" + key + "&copie=" + cc + "&confirmationPage="
                                + parameters.get("confirmationReservationPage").get(0));

                try {
                    mailService.sendMessageWithTemplate(templatePath, bindings, email, from, cc, bcc,
                            resource.getLocale(), "Jahia User Registration");
                } catch (ScriptException e) {
                    logger.error("Error sending e-mail notification for user creation", e);
                }
            }

            return true;
        }
    });

    return new ActionResult(HttpServletResponse.SC_ACCEPTED, parameters.get("newReservationPage").get(0),
            new JSONObject());
}

From source file:com.iisigroup.cap.base.handler.CheckTimeoutHandler.java

@SuppressWarnings({ "unchecked", "unused" })
public Result checkTO(Request request) throws CapException {
    AjaxFormResult result = new AjaxFormResult();
    HttpServletRequest sreq = (HttpServletRequest) request.getServletRequest();

    String refPath = sreq.getHeader("referer");
    refPath = StringEscapeUtils.unescapeHtml(refPath);
    String path = sreq.getPathInfo();
    boolean isNewSes = sreq.getSession(false).isNew();
    String isFresh = request.get("REFSH_TO", "");

    HttpSession session = sreq.getSession(false);
    Map<String, String> map = (Map<String, String>) session.getAttribute(TOCM);

    String curPage = request.get(CCPAGE_NO);

    if (curPage.lastIndexOf("ap") >= 0) {
        if (map != null && map.containsKey(curPage)) {
            // DO NOT THING
        } else {/*w w  w  .ja  va2s . c  om*/
            map = new HashMap<String, String>();
            session.setAttribute(TOCM, map);
        }
    }
    if (map == null) {
        map = new HashMap<String, String>();
    }
    if (!CapString.isEmpty(curPage)) {
        if (map.containsKey(curPage) && !"Y".equals(isFresh)) {
            String openTime = map.get(curPage);

            // ??db??
            sysProp.remove(TIME_OUT);
            String stout = sysProp.get(TIME_OUT);
            if (CapString.isEmpty(stout)) {
                stout = "10"; // default 10mins
            }

            // ??
            String lastPageNo = getLastRcordTOMC(map);
            if (lastPageNo.compareTo(curPage) != 0) {
                /*
                 * ??timeout? ???
                 */
                if (map.get(lastPageNo) != null) {
                    long lastOpenTime = Long.parseLong(map.get(lastPageNo));
                    // Calculate difference in milliseconds
                    long curTime = CapDate.getCurrentTimestamp().getTime();
                    long diff = curTime - lastOpenTime;
                    // Difference in seconds
                    long diffSec = diff / 1000;
                    long propTimeout = (Long.parseLong(stout) + 1) * 60;
                    if (diffSec > propTimeout) {
                        map.remove(lastPageNo);
                        session.setAttribute(TOCM, map);
                    }
                }
                // ??????
                return result;
            }

            long time = Long.parseLong(openTime);
            Timestamp ts1 = new Timestamp(time);
            String d12str = CapDate.convertTimestampToString(ts1, "HH:mm:ss.sss");
            long curTime = CapDate.getCurrentTimestamp().getTime();
            long propTimeOut = sreq.getSession(false).getMaxInactiveInterval();
            if (!CapString.isEmpty(stout)) {
                propTimeOut = Long.parseLong(stout);
                long remindTime = (propTimeOut - 1) * 60;
                propTimeOut = propTimeOut * 60;
                // Calculate difference in milliseconds
                long diff = curTime - time;
                // Difference in seconds
                long diffSec = diff / 1000;
                String isContinues = request.get("isCntnu");
                if ("true".equals(isContinues)) {
                    map.put(curPage, String.valueOf(curTime));
                    session.setAttribute(TOCM, map);
                } else if (CapString.isEmpty(isContinues) && diffSec >= remindTime) {
                    result.set("SHOW_REMIND", "true");
                }
                // ?falsetimeout(user??,1??)
                else if ("false".equals(isContinues) || diffSec > propTimeOut) {
                    String webApUrl = sysProp.get("WEB_AP_URL");
                    String st1 = sreq.getScheme();
                    String st2 = sreq.getServerName();
                    int port = sreq.getServerPort();
                    String st4 = sreq.getContextPath();
                    webApUrl = st1 + "://" + st2 + ":" + port + st4;
                    result.set("errorPage", st4 + "/page/timeout");
                    map.remove(curPage);
                    session.setAttribute(TOCM, map);
                }
            }
        } else {
            long curTime = CapDate.getCurrentTimestamp().getTime();
            map.put(curPage, String.valueOf(curTime));
            session.setAttribute(TOCM, map);
        }
    }
    return result;
}

From source file:com.greenline.guahao.web.module.home.controllers.mobile.reservation.MobilePaymentController.java

/**
 * html5?//  ww w . j a va2s  . co m
 * 
 * @param model
 * @param request
 * @param orderId
 * @param subject
 * @param desc
 * @return String
 * @throws Exception
 */
@MethodRemark(value = "remark=html5?,method=GET")
@RequestMapping(value = MobileConstants.M_JUMP_TO_PAYMENT_PATH)
public String jumpToPayment(ModelMap model, HttpServletRequest request,
        @ModelAttribute("orderId") String orderId, @ModelAttribute("subject") String subject,
        @ModelAttribute("desc") String desc) throws Exception {
    log.info("??????");
    String errorMsg = "";
    // ?????
    Integer feeFen = 0;
    Long newdiff = 0L;
    OrderDO orderBrief = null;
    if (StringUtils.isBlank(orderId)) {
        log.error("???");
        model.put("error_message", "???");
        return MobileConstants.M_ERROR;
    } else {
        orderBrief = orderManager.getOrder(orderId);
        if (orderBrief == null) {
            log.error("?????,??:" + orderId);
            errorMsg = "?????,??:" + orderId;
            model.put("error_message", errorMsg);
            return MobileConstants.M_ERROR;
        } else {
            ShiftCaseVO shiftVO = reservationDOBuilder.setLeftPageValue(orderBrief);
            ExpertDO expert = expertManager.getExpert(orderBrief.getExpertId());
            if (null == expert) {
                log.error(ReservationMsgConstants.ERR_MSG_EXPERT_NOT_EXIST);
            } else {
                shiftVO.setExpertPhoto(expert.getPhoto());
                shiftVO.setExpertSex(expert.getSex());
            }
            model.put("shiftCaseVO", shiftVO);
            feeFen = orderBrief.getClinicFee();
            if (feeFen <= 0) {
                log.error("??0?");
                errorMsg = "??0?";
                model.put("error_message", errorMsg);
                return MobileConstants.M_RESERVATION_FAI;
            }
            // ??
            if (orderBrief.getStatus() != 0) {
                // ???0??
                // 15??
                log.error("?????" + orderBrief.getStatus());
                errorMsg = "?????";
                model.put("error_message", errorMsg);
                model.put("hid", orderBrief.getHospitalId());
                model.put("hdid", orderBrief.getHospDepartmentId());
                return MobileConstants.M_RESERVATION_FAI;
            }
            // ??????
            java.util.Date nowtime = new Date();
            Date orderCreateTime = orderBrief.getCreatedTime();
            // ??
            Long diff = (nowtime.getTime() - orderCreateTime.getTime()) / 1000;
            if (diff > 60 * 15) {
                // 15??
                log.error("??15?");
                errorMsg = "??15?";
                model.put("error_message", errorMsg);
                return MobileConstants.M_RESERVATION_FAI;
            } else {
                // ?
                newdiff = 60 * 15 - diff;
            }
        }
    }
    // 
    FenToYuan ps = new FenToYuan();
    String fee = ps.formatFenToYuanString(String.valueOf(feeFen));
    log.info("" + newdiff / 60 + "");
    // ???
    String servername = (String) request.getAttribute("servername");
    String domainservername = "";
    if (servername != null) {
        domainservername = request.getScheme() + "://" + servername + CommonUtils.getServerPort(request);
    } else {
        // ????
        domainservername = (String) request.getAttribute("guahaourl");
    }
    MobilePayMentDO mpm = new MobilePayMentDO();
    mpm = mobilePaymentProcess.replaceDomain(mpm, domainservername, MobileConstants.M_PAYMENT_RETURN_PATH,
            MobileConstants.M_PAYMENT_NOTIFY_PATH, MobileConstants.M_PAYMENT_EROOR_NOTIFY_PATH);
    String hospitalId = orderBrief.getHospitalId();
    mpm = mobilePaymentProcess.getDirectPaymentInfo(orderBrief.getUserId(), orderId, fee, subject, desc,
            newdiff / 60, mpm.getCall_back_url(), mpm.getNotify_url(), mpm.getMerchant_url(), hospitalId);
    // 
    ResponseDTO<ConfirmResultDTO> rd = paymentManager.payPrepare(orderId, subject, 1, 0, feeFen, desc);
    if (rd != null) {
        if (ResponseCode.isSuccess(rd.getCode())) {
            log.info("?");
        } else {
            log.error("" + rd.getMessage());
            errorMsg = "" + rd.getMessage();
            model.put("error_message", errorMsg);
            return MobileConstants.M_RESERVATION_FAI;
        }
    } else {
        log.error("?null");
        errorMsg = "?null";
        model.put("error_message", errorMsg);
        return MobileConstants.M_RESERVATION_FAI;
    }
    // ??
    Map<String, String> sParaTempToken = new HashMap<String, String>();
    sParaTempToken.put("service", mpm.getService());
    log.info("service:" + mpm.getService());
    sParaTempToken.put("partner", mpm.partner);
    log.info("partner:" + mpm.partner);
    sParaTempToken.put("_input_charset", MobileAlipayConstant.input_charset);
    log.info("_input_charset:" + MobileAlipayConstant.input_charset);
    sParaTempToken.put("sec_id", mpm.sec_id);
    log.info("sec_id:" + mpm.sec_id);
    sParaTempToken.put("format", mpm.format);
    log.info("format:" + mpm.format);
    sParaTempToken.put("v", mpm.v);
    log.info("v:" + mpm.v);
    sParaTempToken.put("req_id", mpm.req_id);
    log.info("req_id:" + mpm.req_id);
    sParaTempToken.put("req_data", mpm.req_data);
    log.info("req_data:" + mpm.req_data);
    sParaTempToken.put("sign", mpm.getSign());
    log.info("sign:" + mpm.getSign());
    // ???????
    String sHtmlTextToken = mobilePaymentProcess.buildRequest(sParaTempToken);
    // URLDECODE?
    sHtmlTextToken = URLDecoder.decode(sHtmlTextToken, MobileAlipayConstant.input_charset);
    log.info("html5???????:" + sHtmlTextToken);
    String request_token = AlipayCore.getRequestToken(sHtmlTextToken);
    log.info("html5?request_token:" + request_token);
    if (StringUtils.isBlank(request_token)) {
        model.put("error_message", "???");
        return MobileConstants.M_ERROR;
    }
    MobilePayMentDO mp = mobilePaymentProcess.getAuthMobilePaymentInfo(request_token, hospitalId);

    model.put("mpm", mp);
    return MobileConstants.M_AUTH_EXECUTE_PAYMENT;
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

protected Map systemInfo(HttpServletRequest req) {
    String baseURL = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath();//w  ww  .j  av a  2 s . c o  m

    Map info = new LinkedHashMap();
    info.put("sampleObject", sampleObject);
    info.put("adminEmail", adminEmail);
    info.put("fedoraCompat", fedoraCompat);
    info.put("baseURL", baseURL);
    return info;
}

From source file:com.devnexus.ting.web.controller.RegisterController.java

@RequestMapping(value = "/s/registerPageTwo", method = RequestMethod.POST)
public String validateDetailsForm(HttpServletRequest request, Model model,
        @Valid RegistrationDetails registerForm, BindingResult result) {

    Event currentEvent = businessService.getCurrentEvent();
    EventSignup eventSignup = businessService.getEventSignup();
    PaymentMethod paymentMethod = PaymentMethod.PAYPAL;
    prepareHeader(currentEvent, model);/* www . jav  a  2 s  . c o  m*/
    model.addAttribute("signupRegisterView", new SignupRegisterView(eventSignup));
    model.addAttribute("registrationDetails", registerForm);
    registerForm.setFinalCost(getTotal(registerForm));
    registerForm.setEvent(currentEvent);

    if (result.hasErrors()) {
        return "register2";
    }

    for (int index = 0; index < registerForm.getOrderDetails().size(); index++) {
        TicketOrderDetail orderDetails = registerForm.getOrderDetails().get(index);

        TicketGroup ticketGroup = businessService.getTicketGroup(orderDetails.getTicketGroup());

        if (!com.google.common.base.Strings.isNullOrEmpty(orderDetails.getCouponCode())
                && ticketGroup.getCouponCodes() != null && ticketGroup.getCouponCodes().size() > 0) {
            if (!hasCode(ticketGroup.getCouponCodes(), orderDetails.getCouponCode())) {
                result.addError(new FieldError("registrationDetails", "orderDetails[" + index + "].couponCode",
                        "Invalid Coupon Code."));
            }
        }

        if (StringUtils.isEmpty(orderDetails.getFirstName())) {
            result.rejectValue("orderDetails[" + index + "].firstName", "firstName.isRequired",
                    "First Name is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getLastName())) {
            result.rejectValue("orderDetails[" + index + "].lastName", "lastName.isRequired",
                    "Last Name is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getEmailAddress())) {
            result.rejectValue("orderDetails[" + index + "].emailAddress", "emailAddress.isReq uired",
                    "Email Address is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getCity())) {
            result.rejectValue("orderDetails[" + index + "].city", "city.isRequired", "City is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getState())) {
            result.rejectValue("orderDetails[" + index + "].state", "state.isRequired", "State is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getCountry())) {
            result.rejectValue("orderDetails[" + index + "].country", "country.isRequired",
                    "Country is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getJobTitle())) {
            result.rejectValue("orderDetails[" + index + "].jobTitle", "jobTitle.isRequired",
                    "Job Title is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getCompany())) {
            result.rejectValue("orderDetails[" + index + "].company", "company.isRequired",
                    "Company is required.");
        }

    }

    if (result.hasErrors()) {

        return "register2";
    }

    for (TicketOrderDetail detail : registerForm.getOrderDetails()) {
        detail.setRegistration(registerForm);
    }

    switch (paymentMethod) {

    case INVOICE:
        registerForm.setPaymentState(RegistrationDetails.PaymentState.REQUIRES_INVOICE);
        registerForm.setFinalCost(getTotal(registerForm));
        businessService.createPendingRegistrationForm(registerForm);
        return "index";
    case PAYPAL:
        registerForm.setPaymentState(RegistrationDetails.PaymentState.PAYPAL_CREATED);
        registerForm.setFinalCost(getTotal(registerForm));
        registerForm = businessService.createPendingRegistrationForm(registerForm);
        String baseUrl = String.format("%s://%s:%d/", request.getScheme(), request.getServerName(),
                request.getServerPort());
        Payment createdPayment = runPayPal(registerForm, baseUrl);
        return "redirect:" + createdPayment.getLinks().stream().filter(link -> {
            return link.getRel().equals("approval_url");
        }).findFirst().get().getHref();
    default:
        throw new IllegalStateException("The system did not understand the payment type.");

    }

}

From source file:com.nec.harvest.controller.SuihController.java

/**
 * Render page with path variables mapping
 * /{unitLevel}/{unitDept}/{deptCode}/{year:\\d{4}}/{quarter:[1-4]}
 * //  w  ww .j  a  va 2 s . c o m
 * @param userOrgCode
 *            Logged-in user's code
 * @param businessDay
 *            Actual business day
 * @param proGNo
 *            A path variable user's group code
 * @param unitLevel
 *            A path variable classify's code
 * @param unitDept
 *            A path variable department level2's code
 * @param deptCode
 *            A path variable department selected on page view
 * @param year
 *            A path variable year
 * @param quarter
 *            A path variable quarter
 * @param model
 *            Spring's model that can be used to render a view
 * @return A redirect URL
 */
@RequestMapping(value = "/{unitLevel}/{unitDept}/{deptCode}/{year:\\d{4}}/{quarter:[1-4]}", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
        @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo,
        @PathVariable String unitLevel, @PathVariable String unitDept, @PathVariable String deptCode,
        @PathVariable String year, @PathVariable String quarter, final HttpServletRequest request,
        final Model model) {
    logger.info(
            "Loading profit and loss manager in a quarter data by full path [/suih/{unitLevel}/{unitDept}/{deptCode}/{year}/{quarter}]");

    Date currentYear = null;
    int currentQuarter = 0;

    // cast year, quarter
    try {
        currentYear = DateFormatUtil.parse(year, DateFormat.DATE_YEAR);
        currentQuarter = Integer.parseInt(quarter);
    } catch (NullPointerException | IllegalArgumentException | ParseException ex) {
        logger.warn(ex.getMessage());
    }

    try {
        /* Get classify list */
        List<Division> divisions;
        try {
            divisions = divisionService.findByKbnId(DEFAULT_KBN_ID);
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());

            // Set divisions is empty
            divisions = Collections.emptyList();
        }

        // set list classifies first drop down list
        final String CLASSIFIES = "classifies";
        model.addAttribute(CLASSIFIES, divisions);

        // set value selected first drop down list
        final String UNIT_LEVEL = "unitLevel";
        model.addAttribute(UNIT_LEVEL, selectedClassify(divisions, unitLevel));

        List<Organization> departments = null;
        try {
            // Get the list of organizations level 2
            departments = organizationService.findByKaisoBango(unitLevel);
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());
        }

        // set attribute list departments for drop down list level2
        final String DEPARTMENTS = "departments";
        model.addAttribute(DEPARTMENTS, departments);

        // set attribute name selected for drop down list level2
        final String UNIT_DEPT = "unitDeptName";
        model.addAttribute(UNIT_DEPT, selectedDepartment(departments, unitDept));

        final String UNIT_DEPT_CODE = "unitDeptCode";
        model.addAttribute(UNIT_DEPT_CODE, unitDept);

        // set attribute department code
        final String DEPT_CODE = "deptCode";
        boolean isTotalCalculation = unitDept.equals(deptCode);
        model.addAttribute(DEPT_CODE, isTotalCalculation ? unitDept : deptCode);

        // set attribute current quarter of business
        final String CURRENT_QUARTER = "currentQuarter";
        model.addAttribute(CURRENT_QUARTER, year.concat("/").concat(quarter));

        InputStreamReader in = null;
        try {
            UriComponents uriComponents = UriComponentsBuilder.fromUriString(
                    request.getContextPath() + Constants.PAGINATION_PATH + "/{unitDept}/{deptCode}/{pageindex}")
                    .build();
            URI uri = uriComponents.expand(proGNo, unitDept, deptCode, 0).encode().toUri();

            // initial HttpHost, HttpGet
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpHost httpHost = new HttpHost(request.getServerName(), request.getLocalPort(),
                    request.getScheme());
            HttpGet httpGet = new HttpGet(uri.toString());
            HttpResponse httpResp = httpClient.execute(httpHost, httpGet);
            if (httpResp.getStatusLine().getStatusCode() != 200) {
                // Release the connection
                httpClient.close();
                httpClient = null;

                // call rest paging error
                throw new RuntimeException(
                        "Failed : HTTP error code : " + httpResp.getStatusLine().getStatusCode());
            }

            // read pagination 
            in = new InputStreamReader(httpResp.getEntity().getContent(),
                    HttpServletContentType.DEFAULT_ENCODING);
            BufferedReader rd = new BufferedReader(in);
            StringBuilder textView = new StringBuilder();

            String line = "";
            while ((line = rd.readLine()) != null) {
                textView.append(line);
            }

            // set attribute pagination
            final String HTML_PAGINATION = "pagination";
            model.addAttribute(HTML_PAGINATION, textView);

            // Release the connection
            httpClient.close();
            httpClient = null;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    logger.warn(ex.getMessage());
                }
            }
        }
    } catch (ServiceException ex) {
        logger.error(ex.getMessage(), ex);

        // ???????????
        model.addAttribute(ERROR, true);
        model.addAttribute(ERROR_MESSAGE, getSystemError());
    }

    // 
    return processingSuih(userOrgCode, businessDay, unitDept, deptCode, currentYear, currentQuarter, model);
}

From source file:org.openmrs.module.feedback.web.AddFeedbackFormController.java

@Override
protected Boolean formBackingObject(HttpServletRequest request) throws Exception {

    /* To check wheather or not the subject , severity and feedback is empty or not */
    Boolean feedbackMessage = false;
    String text = "";
    String subject = request.getParameter("subject");
    String severity = request.getParameter("severity");
    String feedback = request.getParameter("feedback");

    if (StringUtils.hasLength(subject) && StringUtils.hasLength(severity) && StringUtils.hasLength(severity)) {
        Object o = Context.getService(FeedbackService.class);
        FeedbackService service = (FeedbackService) o;
        Feedback s = new Feedback();

        s.setSubject(request.getParameter("subject"));
        s.setSeverity(request.getParameter("severity"));

        /* To get the Stacktrace of the page from which the feedback is submitted */
        StackTraceElement[] c = Thread.currentThread().getStackTrace();

        if ("Yes".equals(request.getParameter("pagecontext"))) {
            for (int i = 0; i < c.length; i++) {
                feedback = feedback + System.getProperty("line.separator") + c[i].getFileName()
                        + c[i].getMethodName() + c[i].getClass() + c[i].getLineNumber();
            }//from   www.  j av a2  s.  c  o m
        }

        s.setContent(feedback);

        /* file upload in multiplerequest */
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = (MultipartFile) multipartRequest.getFile("file");

            if (!file.isEmpty()) {
                if (file.getSize() <= 5242880) {
                    if (file.getOriginalFilename().endsWith(".jpeg")
                            || file.getOriginalFilename().endsWith(".jpg")
                            || file.getOriginalFilename().endsWith(".gif")
                            || file.getOriginalFilename().endsWith(".png")) {
                        s.setMessage(file.getBytes());
                    } else {
                        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                                "feedback.notification.feedback.error");

                        return false;
                    }
                } else {
                    request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "feedback.notification.feedback.error");

                    return false;
                }
            }
        }

        /* Save the Feedback */
        service.saveFeedback(s);
        request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getAdministrationService().getGlobalProperty("feedback.ui.notification"));

        if ("Yes".equals(Context.getUserContext().getAuthenticatedUser()
                .getUserProperty("feedback_notificationReceipt"))) {
            try {

                // Create Message
                Message message = new Message();

                message.setSender(
                        Context.getAdministrationService().getGlobalProperty("feedback.notification.email"));
                message.setRecipients(
                        Context.getUserContext().getAuthenticatedUser().getUserProperty("feedback_email"));
                message.setSubject("Feedback submission confirmation mail");
                message.setContent(Context.getAdministrationService().getGlobalProperty("feedback.notification")
                        + "Ticket Number: " + s.getFeedbackId() + " Subject :" + s.getSubject());
                message.setSentDate(new Date());

                // Send message
                Context.getMessageService().send(message);
            } catch (Exception e) {
                log.error("Unable to sent the email to the Email : "
                        + Context.getUserContext().getAuthenticatedUser().getUserProperty("feedback_email"));
            }
        }

        try {

            // Create Message
            Message message = new Message();

            message.setSender(
                    Context.getAdministrationService().getGlobalProperty("feedback.notification.email"));
            message.setRecipients(
                    Context.getAdministrationService().getGlobalProperty("feedback.admin.notification.email"));
            message.setSubject("New feedback submitted");
            message.setContent(
                    Context.getAdministrationService().getGlobalProperty("feedback.admin.notification")
                            + "Ticket Number: " + s.getFeedbackId() + " Subject : " + s.getSubject()
                            + " Take Action :" + request.getScheme() + "://" + request.getServerName() + ":"
                            + request.getServerPort() + request.getContextPath()
                            + "/module/feedback/feedback.form?feedbackId=" + s.getFeedbackId() + "#command");
            message.setSentDate(new Date());

            // Send message
            Context.getMessageService().send(message);
        } catch (Exception e) {
            log.error("Unable to sent the email to the Email : " + Context.getUserContext()
                    .getAuthenticatedUser().getUserProperty("feedback.admin.notification.email"));
        }

        feedbackMessage = true;
    }

    /* Reserved for future use for showing that the data is saved and the feedback is submitted */
    log.debug("Returning hello world text: " + text);

    return feedbackMessage;
}

From source file:com.groupdocs.ui.servlets.ViewDocument.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.addHeader("Content-Type", "application/json");
    ViewDocumentParameters params = new ObjectMapper().readValue(request.getInputStream(),
            ViewDocumentParameters.class);

    ViewDocumentResponse result = new ViewDocumentResponse();
    FileData fileData = ViewerUtils.factoryFileData(params.getPath());
    DocumentInfoContainer docInfo = null;

    try {/*from  w w w .j av  a  2  s  .c  om*/
        result.setDocumentDescription(
                (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
    } catch (ParseException x) {
        throw new ServletException(x);
    }

    if (params.getUseHtmlBasedEngine()) {
        try {
            docInfo = ViewerUtils.getViewerHtmlHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params));
        result.setPath(params.getPath());
        result.setName(params.getPath());
        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        HtmlOptions htmlOptions = new HtmlOptions();
        htmlOptions.setResourcesEmbedded(true);

        htmlOptions.setHtmlResourcePrefix("/GetResourceForHtml?documentPath=" + params.getPath()
                + "&pageNumber={page-number}&resourceName=");

        if (!DotNetToJavaStringHelper.isNullOrEmpty(params.getPreloadPagesCount().toString())
                && params.getPreloadPagesCount().intValue() > 0) {
            htmlOptions.setPageNumber(1);
            htmlOptions.setCountPagesToConvert(params.getPreloadPagesCount().intValue());
        }

        String[] cssList = null;

        RefObject<ArrayList<String>> tempRef_cssList = new RefObject<ArrayList<String>>(cssList);

        List<PageHtml> htmlPages = GetHtmlPages(params.getPath(), htmlOptions);
        cssList = tempRef_cssList.argValue;

        ArrayList<String> pagesContent = new ArrayList<String>();
        for (PageHtml page : htmlPages) {
            pagesContent.add(page.getHtmlContent());
        }
        String[] htmlContent = pagesContent.toArray(new String[0]);
        result.setPageHtml(htmlContent);
        result.setPageCss(new String[] { String.join(" ", temp_cssList) });

        for (int i = 0; i < result.getPageHtml().length; i++) {
            String html = result.getPageHtml()[i];
            int indexOfScript = html.indexOf("script");
            if (indexOfScript > 0) {
                result.getPageHtml()[i] = html.substring(0, indexOfScript);
            }
        }

    } else {

        try {
            docInfo = ViewerUtils.getViewerImageHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        int maxWidth = 0;
        int maxHeight = 0;
        for (PageData pageData : docInfo.getPages()) {
            if (pageData.getHeight() > maxHeight) {
                maxHeight = pageData.getHeight();
                maxWidth = pageData.getWidth();
            }
        }

        fileData.setDateCreated(new Date());
        fileData.setDateModified(docInfo.getLastModificationDate());
        fileData.setPageCount(docInfo.getPages().size());
        fileData.setPages(docInfo.getPages());
        fileData.setMaxWidth(maxWidth);
        fileData.setMaxHeight(maxHeight);

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params.getPath(), true, false, params.getFileDisplayName(),
                params.getWatermarkText(), params.getWatermarkColor(), params.getWatermarkPostion(),
                params.getWatermarkWidth(), params.getIgnoreDocumentAbsence(), params.getUseHtmlBasedEngine(),
                params.getSupportPageRotation()));
        result.setPath(params.getPath());
        result.setName(params.getPath());

        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        int[] pageNumbers = new int[docInfo.getPages().size()];
        int count = 0;
        for (PageData page : docInfo.getPages()) {

            pageNumbers[count] = page.getNumber();
            count++;
        }
        String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort();
        String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, params);

        result.setImageUrls(imageUrls);

    }

    new ObjectMapper().writeValue(response.getOutputStream(), result);

}