Example usage for javax.servlet.http HttpSession getId

List of usage examples for javax.servlet.http HttpSession getId

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getId.

Prototype

public String getId();

Source Link

Document

Returns a string containing the unique identifier assigned to this session.

Usage

From source file:Controller.ProviderController.java

@RequestMapping(value = "/AccountInfo")
public String accountInfo(ModelMap map, HttpSession session) {
    try {/*w w w .  java  2s . co  m*/
        AccountSession account = (AccountSession) session.getAttribute("account");
        ProviderDTO result = providerService.getAccountInfo(account.getId());
        Gson gson = new Gson();
        map.addAttribute("AccountInfo", gson.toJson(result));
        map.addAttribute("page", "Info");
        //get Notification           
        //            List<ProviderNotification> providerNoti = providerService.getProviderNotification();
        //            List<ProviderNotificationSetting> providerSetting = providerService.getProviderNotificationSetting(account.getId());
        //            List<Integer> providerSettingList = new ArrayList<Integer>();
        //            for (int i = 0; i < providerSetting.size(); i++) {
        //                providerSettingList.add(providerSetting.get(i).getProviderNotificationID());
        //            }
        //            map.addAttribute("providerSetting", gson.toJson(providerSettingList));
        //            map.addAttribute("providerNotification", gson.toJson(providerNoti));
        return accountInfoUrl;
    } catch (Exception e) {
        String content = "Function: ProviderController - accountInfo\n" + "****Error****\n" + e.getMessage()
                + "\n" + "**********";
        map.addAttribute("errorID", session.getId());
        map.addAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:Controller.ProviderController.java

@RequestMapping(value = "/Verify")
public String verifyPhone(ModelMap model, HttpSession session, HttpServletRequest request) {
    try {/*from  www  .  j av a  2s. c o  m*/
        AccountSession account = (AccountSession) session.getAttribute("account");
        boolean isVerify = providerService.isVerifyPhoneNumber(account.getId());
        if (account != null) {
            if (!isVerify) {
                List<CountryDTO> countryList = commonService.getAllCountry();
                Gson gson = new Gson();
                model.addAttribute("countryList", gson.toJson(countryList));
                ProviderDTO provider = providerService.getPhoneNumber(account.getId());
                model.addAttribute("phoneNumber", gson.toJson(provider));
                return "provider/verifyPhoneNumber";
            } else if (request.getParameter("language") != null) {
                return "redirect:/Provider/AccountInfo" + "?language=" + request.getParameter("language");
            } else {
                return "redirect:/Provider/AccountInfo";
            }
        }
        if (request.getParameter("language") != null) {
            return "redirect:/Common" + "?language=" + request.getParameter("language");
        } else {
            return "redirect:/Common";
        }

    } catch (Exception e) {
        String content = "Function: ProviderController - verifyPhone\n" + "****Error****\n" + e.getMessage()
                + "\n" + "**********";
        model.addAttribute("errorID", session.getId());
        model.addAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:Controller.UserController.java

@RequestMapping(value = "/PaywithPaypal")
String payWithPaypal(HttpServletRequest request) {
    try {//from  w w  w. j a v a2 s .c  om
        String redirectURL;
        HttpSession session = request.getSession(true);
        AccountSession account = (AccountSession) session.getAttribute("account");
        int packageID = Integer.parseInt(request.getParameter("packageID"));
        PackageDTO packgeDTO = tripperService.getPackageForPayment(packageID);
        int numberOfChilds = 0;
        int numberOfAdults = 0;
        String selectedDate = request.getParameter("selectedDate");
        List<Double> price = (List<Double>) request.getAttribute("prices");
        try {
            numberOfChilds = Integer.parseInt(request.getAttribute("numberOfChilds").toString());
            numberOfAdults = Integer.parseInt(request.getAttribute("numberOfAdults").toString());
        } catch (Exception e) {
        }

        String total = request.getAttribute("totalPrice").toString();
        List<Item> itemList = new ArrayList<Item>();
        int noOfPackages = 0;
        if (packgeDTO.isIsPrivateTour()) {
            noOfPackages = (int) Math
                    .round(Math.ceil((float) (numberOfAdults + numberOfChilds) / packgeDTO.getMinTripper()));
            Item item = new Item(String.valueOf(noOfPackages), String.valueOf(noOfPackages) + "Packages",
                    String.format(Locale.US, "%.2f",
                            (price.get(0) * (100 - packgeDTO.getYoutripperPercentage())) / 100),
                    "USD");
            itemList.add(item);
        } else {
            Item item = new Item(String.valueOf(numberOfAdults), "Number of Adults", String.format(Locale.US,
                    "%.2f", (price.get(0) * (100 - packgeDTO.getYoutripperPercentage())) / 100), "USD");
            itemList.add(item);
            if (price.get(1) > 0) {
                Item item2 = new Item(String.valueOf(numberOfChilds), "Number of Childs",
                        String.format(Locale.US, "%.2f",
                                (price.get(1) * (100 - packgeDTO.getYoutripperPercentage())) / 100),
                        "USD");
                itemList.add(item2);
            }
        }

        redirectURL = tripperService.paywithPaypal(account, packageID, numberOfChilds, numberOfAdults,
                selectedDate, request, "USD", total, "Paying with Paypal", itemList);
        return "redirect:" + redirectURL;
    } catch (PayPalRESTException e) {
        HttpSession session = request.getSession(true);
        String content = "Function: UserController - payWithPaypal\n" + "***Input***\n" + "packageID: "
                + request.getParameter("packageID") + "\n" + "selectedDate: "
                + request.getParameter("selectedDate") + "\n" + "prices: " + request.getAttribute("prices")
                + "\n" + "numberOfChilds: " + request.getAttribute("numberOfChilds") + "\n" + "numberOfAdults: "
                + request.getAttribute("numberOfAdults") + "\n" + "totalPrice: "
                + request.getParameter("totalPrice") + "\n" + "**********\n" + "****Error****\n"
                + e.getMessage() + "\n" + "**********";
        request.setAttribute("errorID", session.getId());
        request.setAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";

    }

}

From source file:Controller.ProviderController.java

@RequestMapping(value = "/Package/Creation", method = RequestMethod.GET)
public String createPackage(ModelMap model, HttpSession session) {
    try {//from  w  w  w  .  j  a  v a2 s.c om
        AccountSession account = (AccountSession) session.getAttribute("account");
        boolean checkPhone = providerService.checkValidatePhoneNumber(account.getId());
        if (checkPhone) {
            TemporaryPackageDTO temporaryPackage = providerService.getTemporaryPackage(account.getId());
            if (!temporaryPackage.isIsFinshed()) {
                // get content of creation form
                String packageFormJSON = providerService.getPackageForm(account.getId());

                // change to json
                Gson gson = new Gson();
                String temporaryPackageJSON = gson.toJson(temporaryPackage);
                // set attribute
                String mac = commonService.getGeolocation();

                model.addAttribute("temporaryPackage", temporaryPackageJSON);
                model.addAttribute("packageForm", packageFormJSON);
                model.addAttribute("macAddress", mac);

                //                    return "provider/createForm";
                return "provider/packageCreation";
            } else {
                return "provider/apply";
            }
        } else {
            model.addAttribute("error", "You need verify your Phone number before create package!");
            return "forward:/Provider/Verify";
        }
    } catch (Exception e) {
        String content = "Function: ProviderController - createPackage\n" + "****Error****\n" + e.getMessage()
                + "\n" + "**********";
        model.addAttribute("errorID", session.getId());
        model.addAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java

private void handlerPreviewPageTemplate(HttpServletRequest request, HttpServletResponse response,
        HttpSession session, AdminService admin, ExtendedMap formItems, User oldUser)
        throws VerticalAdminException, VerticalEngineException {
    try {/*  ww w  .  j av  a 2s . co  m*/
        final int contentKeyInt = formItems.getInt("contentkey", -1);
        final ContentKey contentKey;
        if (contentKeyInt > -1) {
            contentKey = new ContentKey(contentKeyInt);
        } else {
            contentKey = null;
        }

        SiteKey siteKey = new SiteKey(formItems.getInt("menukey"));
        SiteEntity site = siteDao.findByKey(siteKey);
        PageTemplateKey pageTemplateKey = new PageTemplateKey(formItems.getInt("pagetemplatekey"));
        PageTemplateEntity pageTemplate = pageTemplateDao.findByKey(pageTemplateKey.toInt());

        UserEntity previewer = securityService.getUser(oldUser);

        PreviewContentHandler previewContentHandler = new PreviewContentHandler(contentKey);
        previewContentHandler.setSite(site);
        previewContentHandler.setTimeService(timeService);
        previewContentHandler.setPreviewService(previewService);
        previewContentHandler.setPageTemplate(pageTemplate);
        previewContentHandler.setFormItems(formItems);
        previewContentHandler.setPreviewer(previewer);
        previewContentHandler.setSessionId(session.getId());
        previewContentHandler.setRequest(request);
        previewContentHandler.setSession(session);
        previewContentHandler.setContentDao(contentDao);
        previewContentHandler.setContentVersionDao(contentVersionDao);
        previewContentHandler.setPageRendererFactory(pageRendererFactory);
        previewContentHandler.setDeviceClassResolverService(deviceClassResolverService);
        previewContentHandler.setLocaleResolverService(localeResolverService);

        RenderedPageResult result = previewContentHandler.renderPreview();

        PrintWriter writer = response.getWriter();
        writer.write(result.getContent());
    } catch (VerticalRenderException vre) {
        String message = "Failed to render page: %t";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, vre);
    } catch (IOException ioe) {
        String message = "Failed to redirect user client: %t";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, ioe);
    }
}

From source file:Controller.ProviderController.java

@RequestMapping(value = "/Package/Registration", method = RequestMethod.GET)
public String registerPackage(ModelMap model, HttpSession session) {
    try {//from   w  w w  . j  a  v  a  2s  .  c  o m
        AccountSession account = (AccountSession) session.getAttribute("account");
        boolean checkPhone = providerService.checkValidatePhoneNumber(account.getId());
        if (checkPhone) {
            TemporaryPackageDTO temporaryPackage = providerService.getTemporaryPackage(account.getId());
            if (!temporaryPackage.isIsFinshed()) {
                // get content of creation form
                String packageFormJSON = providerService.getPackageForm(account.getId());

                // change to json
                Gson gson = new Gson();
                String temporaryPackageJSON = gson.toJson(temporaryPackage);
                // set attribute
                String mac = commonService.getGeolocation();

                model.addAttribute("temporaryPackage", temporaryPackageJSON);
                model.addAttribute("packageForm", packageFormJSON);
                model.addAttribute("macAddress", mac);

                String timeNow = new DateTime().toString("MM/dd/yyyy");
                model.addAttribute("timeNow", timeNow);
                //                    return "provider/createForm";
                return "provider/PackageRegistration";
            } else {
                return "provider/apply";
            }
        } else {
            model.addAttribute("error", "You need verify your Phone number before create package!");
            return "forward:/Provider/Verify";
        }
    } catch (Exception e) {
        String content = "Function: ProviderController - registerPackage\n" + "****Error****\n" + e.getMessage()
                + "\n" + "**********";
        model.addAttribute("errorID", session.getId());
        model.addAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:Controller.ProviderController.java

@RequestMapping(value = "/Package/Registration", method = RequestMethod.POST)
public String CloneRegisterPackage(ModelMap model, HttpSession session) {
    try {/*from ww w .  j av  a2s . c om*/
        AccountSession account = (AccountSession) session.getAttribute("account");
        boolean checkPhone = providerService.checkValidatePhoneNumber(account.getId());
        if (checkPhone) {
            TemporaryPackageDTO temporaryPackage = providerService.getTemporaryPackage(account.getId());
            if (!temporaryPackage.isIsFinshed()) {
                // get content of creation form
                String packageFormJSON = providerService.getPackageForm(account.getId());

                // change to json
                Gson gson = new Gson();
                String temporaryPackageJSON = gson.toJson(temporaryPackage);
                // set attribute
                String mac = commonService.getGeolocation();

                model.addAttribute("temporaryPackage", temporaryPackageJSON);
                model.addAttribute("packageForm", packageFormJSON);
                model.addAttribute("macAddress", mac);

                String timeNow = new DateTime().toString("MM/dd/yyyy");
                model.addAttribute("timeNow", timeNow);
                //                    return "provider/createForm";
                return "provider/PackageRegistration";
            } else {
                return "provider/apply";
            }
        } else {
            model.addAttribute("error", "You need verify your Phone number before create package!");
            return "forward:/Provider/Verify";
        }
    } catch (Exception e) {
        String content = "Function: ProviderController - registerPackage\n" + "****Error****\n" + e.getMessage()
                + "\n" + "**********";
        model.addAttribute("errorID", session.getId());
        model.addAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:com.sun.faban.harness.webclient.XFormServlet.java

/**
 * A get request starts a new form.//from w  w  w.  j  a va2s.  co m
 *
 * @param request The servlet request
 * @param response The servlet response
 * @throws ServletException Error in request handling
 * @throws IOException Error doing other IO
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession(true);
    Adapter adapter = null;

    String templateFile = (String) session.getAttribute("faban.submit.template");
    String styleSheet = (String) session.getAttribute("faban.submit.stylesheet");

    String srcURL = new File(templateFile).toURI().toString();

    logger.finer("benchmark.template: " + srcURL);
    session.removeAttribute("faban.submit.template");
    session.removeAttribute("faban.submit.stylesheet");

    try {
        String requestURI = request.getRequestURI();
        String formURI = null;
        String contextPath = request.getContextPath();
        String benchPath = contextPath + "/bm_submit/";
        if (requestURI.startsWith(benchPath)) {
            int idx = requestURI.indexOf('/', benchPath.length());
            String benchName = requestURI.substring(benchPath.length(), idx);
            String formName = requestURI.substring(idx + 1);
            formURI = com.sun.faban.harness.common.Config.FABAN_HOME + "benchmarks/" + benchName + "/META-INF/"
                    + formName;
        } else {
            StringBuffer buffer = new StringBuffer(request.getScheme());
            buffer.append("://");
            buffer.append(request.getServerName());
            buffer.append(":");
            buffer.append(request.getServerPort());
            buffer.append(request.getContextPath());
            buffer.append(request.getParameter("form"));
            formURI = buffer.toString();
        }

        if (formURI == null) {
            throw new IOException("Resource not found: " + formURI);
        }
        logger.finer("Form URI: " + formURI);

        String css = request.getParameter("css");
        String actionURL = response.encodeURL(request.getRequestURI());
        logger.finer("actionURL: " + actionURL);

        // Find the base URL used by Faban. We do not use Config.FABAN_URL
        // because this base URL can vary by the interface name the Faban
        // master is accessed in this session. Otherwise it is identical.
        StringBuffer baseURL = request.getRequestURL();
        int uriLength = baseURL.length() - requestURI.length() + contextPath.length();
        baseURL.setLength(++uriLength); // Add the ending slash

        adapter = new Adapter();
        if (configFile != null && configFile.length() > 0)
            adapter.setConfigPath(configFile);

        File xsl = null;
        if (styleSheet != null)
            xsl = new File(styleSheet);

        if (xsl != null && xsl.exists()) {
            adapter.xslPath = xsl.getParent();
            adapter.stylesheet = xsl.getName();
        } else {
            adapter.xslPath = xsltDir;
            adapter.stylesheet = "faban.xsl";
        }

        adapter.baseURI = baseURL.toString();
        adapter.formURI = formURI;
        adapter.actionURL = actionURL;
        adapter.beanCtx.put("chiba.web.uploadDir", uploadDir);
        adapter.beanCtx.put("chiba.useragent", request.getHeader("User-Agent"));
        adapter.beanCtx.put("chiba.web.request", request);
        adapter.beanCtx.put("chiba.web.session", session);
        adapter.beanCtx.put("benchmark.template", srcURL);

        if (css != null) {
            adapter.CSSFile = css;
            logger.fine("using css stylesheet: " + css);
        }

        Map servletMap = new HashMap();
        servletMap.put(ChibaAdapter.SESSION_ID, session.getId());
        adapter.beanCtx.put(ChibaAdapter.SUBMISSION_RESPONSE, servletMap);

        Enumeration params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String s = (String) params.nextElement();
            //store all request-params we don't use in the beanCtx map
            if (!(s.equals("form") || s.equals("xslt") || s.equals("css") || s.equals("action_url"))) {
                String value = request.getParameter(s);
                adapter.beanCtx.put(s, value);
                logger.finer("added request param '" + s + "' to beanCtx");
            }
        }
        adapter.init();
        adapter.execute();

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        adapter.generator.setOutput(out);
        adapter.buildUI();
        session.setAttribute("chiba.adapter", adapter);
        out.close();
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception processing XForms", e);
        shutdown(adapter, session, e, request, response);
    }
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/portfolios/portfolio/{portfolio-id}")
@GET/*from   www .j a va  2  s . c o  m*/
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/zip",
        MediaType.APPLICATION_OCTET_STREAM })
public Object getPortfolio(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @PathParam("portfolio-id") String portfolioUuid,
        @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest,
        @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId,
        @QueryParam("group") Integer group, @QueryParam("resources") String resource,
        @QueryParam("files") String files, @QueryParam("export") String export,
        @QueryParam("lang") String lang) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    Response response = null;
    try {
        String portfolio = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId, 0,
                this.label, resource, "", ui.subId).toString();

        if ("faux".equals(portfolio)) {
            response = Response.status(403).build();
        }

        if (response == null) {
            Date time = new Date();
            Document doc = DomUtils.xmlString2Document(portfolio, new StringBuffer());
            NodeList codes = doc.getDocumentElement().getElementsByTagName("code");
            // Le premier c'est celui du root
            Node codenode = codes.item(0);
            String code = "";
            if (codenode != null)
                code = codenode.getTextContent();

            if (export != null) {
                response = Response.ok(portfolio).header("content-disposition",
                        "attachment; filename = \"" + code + "-" + time + ".xml\"").build();
            } else if (resource != null && files != null) {
                //// Cas du renvoi d'un ZIP

                /// Temp file in temp directory
                File tempDir = new File(System.getProperty("java.io.tmpdir", null));
                File tempZip = File.createTempFile(portfolioUuid, ".zip", tempDir);

                FileOutputStream fos = new FileOutputStream(tempZip);
                ZipOutputStream zos = new ZipOutputStream(fos);
                //               BufferedOutputStream bos = new BufferedOutputStream(zos);

                /// zos.setComment("Some comment");

                /// Write xml file to zip
                ZipEntry ze = new ZipEntry(portfolioUuid + ".xml");
                zos.putNextEntry(ze);

                byte[] bytes = portfolio.getBytes("UTF-8");
                zos.write(bytes);

                zos.closeEntry();

                /// Find all fileid/filename
                XPath xPath = XPathFactory.newInstance().newXPath();
                String filterRes = "//asmResource/fileid";
                NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

                /// Direct link to data
                // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

                /*
                String langatt = "";
                if( lang != null )
                   langatt = "?lang="+lang;
                else
                   langatt = "?lang=fr";
                //*/

                /// Fetch all files
                for (int i = 0; i < nodelist.getLength(); ++i) {
                    Node res = nodelist.item(i);
                    Node p = res.getParentNode(); // resource -> container
                    Node gp = p.getParentNode(); // container -> context
                    Node uuidNode = gp.getAttributes().getNamedItem("id");
                    String uuid = uuidNode.getTextContent();

                    String filterName = "./filename[@lang and text()]";
                    NodeList textList = (NodeList) xPath.compile(filterName).evaluate(p,
                            XPathConstants.NODESET);
                    String filename = "";
                    if (textList.getLength() != 0) {
                        Element fileNode = (Element) textList.item(0);
                        filename = fileNode.getTextContent();
                        lang = fileNode.getAttribute("lang");
                        if ("".equals(lang))
                            lang = "fr";
                    }

                    String servlet = httpServletRequest.getRequestURI();
                    servlet = servlet.substring(0, servlet.indexOf("/", 7));
                    String server = httpServletRequest.getServerName();
                    int port = httpServletRequest.getServerPort();
                    //                  "http://"+ server + /resources/resource/file/ uuid ? lang= size=
                    // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";
                    String url = "http://" + server + ":" + port + servlet + "/resources/resource/file/" + uuid
                            + "?lang=" + lang;
                    HttpGet get = new HttpGet(url);

                    // Transfer sessionid so that local request still get security checked
                    HttpSession session = httpServletRequest.getSession(true);
                    get.addHeader("Cookie", "JSESSIONID=" + session.getId());

                    // Send request
                    CloseableHttpClient client = HttpClients.createDefault();
                    CloseableHttpResponse ret = client.execute(get);
                    HttpEntity entity = ret.getEntity();

                    // Put specific name for later recovery
                    if ("".equals(filename))
                        continue;
                    int lastDot = filename.lastIndexOf(".");
                    if (lastDot < 0)
                        lastDot = 0;
                    String filenameext = filename.substring(0); /// find extension
                    int extindex = filenameext.lastIndexOf(".");
                    filenameext = uuid + "_" + lang + filenameext.substring(extindex);

                    // Save it to zip file
                    //                  int length = (int) entity.getContentLength();
                    InputStream content = entity.getContent();

                    //                  BufferedInputStream bis = new BufferedInputStream(entity.getContent());

                    ze = new ZipEntry(filenameext);
                    try {
                        int totalread = 0;
                        zos.putNextEntry(ze);
                        int inByte;
                        byte[] buf = new byte[4096];
                        //                     zos.write(bytes,0,inByte);
                        while ((inByte = content.read(buf)) != -1) {
                            totalread += inByte;
                            zos.write(buf, 0, inByte);
                        }
                        System.out.println("FILE: " + filenameext + " -> " + totalread);
                        content.close();
                        //                     bis.close();
                        zos.closeEntry();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    EntityUtils.consume(entity);
                    ret.close();
                    client.close();
                }

                zos.close();
                fos.close();

                /// Return zip file
                RandomAccessFile f = new RandomAccessFile(tempZip.getAbsoluteFile(), "r");
                byte[] b = new byte[(int) f.length()];
                f.read(b);
                f.close();

                response = Response.ok(b, MediaType.APPLICATION_OCTET_STREAM)
                        .header("content-disposition", "attachment; filename = \"" + code + "-" + time + ".zip")
                        .build();

                // Temp file cleanup
                tempZip.delete();
            } else {
                //try { this.userId = userId; } catch(Exception ex) { this.userId = -1; };
                //              String returnValue = dataProvider.getPortfolio(new MimeType("text/xml"),portfolioUuid,this.userId, this.groupId, this.label, resource, files).toString();
                if (portfolio.equals("faux")) {

                    throw new RestWebApplicationException(Status.FORBIDDEN,
                            "Vous n'avez pas les droits necessaires");
                }

                if (accept.equals(MediaType.APPLICATION_JSON)) {
                    portfolio = XML.toJSONObject(portfolio).toString();
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_JSON).build();
                } else
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_XML).build();

                logRestRequest(httpServletRequest, null, portfolio, Status.OK.getStatusCode());
            }
        }
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString());
    } catch (SQLException ex) {
        logRestRequest(httpServletRequest, null, "Portfolio " + portfolioUuid + " not found",
                Status.NOT_FOUND.getStatusCode());

        throw new RestWebApplicationException(Status.NOT_FOUND, "Portfolio " + portfolioUuid + " not found");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + ex.getStackTrace(),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        if (dataProvider != null)
            dataProvider.disconnect();
    }

    return response;
}

From source file:Controller.UserController.java

@RequestMapping(value = "/Book")
public String book(HttpServletRequest request) {
    boolean errorFlag = false;
    boolean loginFlag = false;

    if (request.getAttribute("message") != null) {
        errorFlag = true;/*from   ww  w .  j  a  v a  2  s.  c om*/
    }
    if (request.getAttribute("login") != null) {
        loginFlag = true;
    }
    HttpSession session = request.getSession();
    String url = "redirect:/Common";
    if (request.getParameter("language") != null) {
        url = "redirect:/Common" + "?language=" + request.getParameter("language");
    }
    String selectedDate = "";
    SimpleDateFormat fortmatMMddyyyy = new SimpleDateFormat("MM/dd/yyyy");
    try {
        if (errorFlag || loginFlag) {
            selectedDate = (request.getAttribute("selectedDate").toString());
        } else {
            selectedDate = request.getParameter("selectedDate");
        }
        Date chosenDate = fortmatMMddyyyy.parse(selectedDate);
        Date toDay = new Date();
        if (chosenDate.before(toDay)) {
            selectedDate = fortmatMMddyyyy.format(toDay);
        }
        int numberOfAdults, numberOfChilds, packageID;
        try {
            if (errorFlag || loginFlag) {
                numberOfAdults = Integer.parseInt(request.getAttribute("numberOfAdults").toString());
            } else {
                numberOfAdults = Integer.parseInt(request.getParameter("numberOfAdults"));
            }
        } catch (NumberFormatException e) {
            numberOfAdults = 1;
        }
        try {
            if (errorFlag || loginFlag) {
                numberOfChilds = Integer.parseInt(request.getAttribute("numberOfChilds").toString());
            } else {
                numberOfChilds = Integer.parseInt(request.getParameter("numberOfChilds"));
            }
        } catch (NumberFormatException e) {
            numberOfChilds = 1;
        }
        try {
            if (errorFlag || loginFlag) {
                packageID = Integer.parseInt(request.getAttribute("packageID").toString());
            } else {
                packageID = Integer.parseInt(request.getParameter("packageID"));
            }
        } catch (NumberFormatException e) {
            packageID = 0;
        }
        if (packageID > 0 && numberOfAdults > 0) {
            PackageDTO packgeDTO = tripperService.getPackageForPayment(packageID);
            List<Double> prices = tripperService.getPriceOfSelectedDate(selectedDate, packgeDTO);
            if (prices.get(0) > 0) {
                if (prices.get(1) <= 0 || (prices.get(1) > 0 && numberOfChilds > 0)) {
                    request.setAttribute("selectedDate", selectedDate);
                    request.setAttribute("numberOfAdults", numberOfAdults);
                    request.setAttribute("numberOfChilds", numberOfChilds);
                    request.setAttribute("priceForAdult", prices.get(0));
                    request.setAttribute("priceForChild", prices.get(1));
                    request.setAttribute("packageDTO", packgeDTO);
                    if (request.getAttribute("message") != null) {
                        request.setAttribute("message", request.getAttribute("message"));
                    }
                    url = "/tripper/payment";
                }
            }
        }
        return url;
    } catch (Exception e) {

        String content = "Function: UserController - book\n" + "***Input***\n" + "message: "
                + request.getParameter("message") + " || " + request.getAttribute("message") + "\n"
                + "selectedDate: " + request.getParameter("selectedDate") + " || "
                + request.getAttribute("selectedDate") + "\n" + "numberOfAdults: "
                + request.getParameter("numberOfAdults") + " || " + request.getAttribute("numberOfAdults")
                + "\n" + "numberOfChilds: " + request.getParameter("numberOfChilds") + " || "
                + request.getAttribute("numberOfChilds") + "\n" + "packageID: "
                + request.getParameter("packageID") + " || " + request.getAttribute("packageID") + "\n"
                + "**********\n" + "****Error****\n" + e.getMessage() + "\n" + "**********";
        request.setAttribute("errorID", session.getId());
        request.setAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}