Example usage for javax.servlet.http HttpServletRequest getUserPrincipal

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

Introduction

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

Prototype

public java.security.Principal getUserPrincipal();

Source Link

Document

Returns a java.security.Principal object containing the name of the current authenticated user.

Usage

From source file:src.servlets.ManagePropertys.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from w ww .ja  v a2s  . c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try (PrintWriter out = response.getWriter()) {
        String address = "";
        Map m = request.getParameterMap();

        Agents LoggedIn = null;
        try {
            LoggedIn = AgentsDB.getByUsername(request.getUserPrincipal().getName());
            //request.setAttribute("agent", agent);

        } //end try
        catch (Exception ex) {
            address = "/Error.jsp";
        }
        int agentId = 0;
        agentId = LoggedIn.getAgentId();

        if (request.getParameterMap().containsKey("del")) {

            Properties propertyDetails = PropertiesDB
                    .getPropertyByID(Integer.parseInt(request.getParameter("del")));
            if ((propertyDetails != null && propertyDetails.getAgentId().equals(agentId))
                    || request.isUserInRole("admin")) {
                PropertiesDB.deleteProperty(propertyDetails.getId());

                String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
                String filePath = uploadPath + File.separator + "large" + File.separator
                        + propertyDetails.getPhoto();
                String filePathThumbnail = uploadPath + File.separator + "thumbnails" + File.separator
                        + propertyDetails.getPhoto();

                File storeFileThumbnail = new File(filePathThumbnail);
                File storeFile = new File(filePath);

                storeFile.delete();
                storeFileThumbnail.delete();

                address = "ManagePropertys?GetProperties&Status=2";
            }
            response.sendRedirect("/RealtyWebsite/" + address);
            processRequest(request, response);
        } else {
            List<Styles> allStylesList = StylesDB.getAllStyles();
            List<Propertytypes> allPropertyTypesList = PropertytypeDB.getAllPropertytypes();
            List<Garagetypes> allGarageTypesList = GaragetypesDB.getAllGaragetypes();

            if (request.getParameterMap().containsKey("AddNewProperty"))//Add new property
            {
                address = "admin/addNewProperty.jsp";
                String status = "";
                if (request.isUserInRole("admin")) {
                    List<Agents> allAgents = null;
                    try {
                        allAgents = AgentsDB.getAllAgents();
                    } //end try
                    catch (Exception ex) {
                        address = "/Error.jsp";
                    } //end catch
                    address = "admin/addNewProperty.jsp";
                    request.setAttribute("allAgents", allAgents);
                } else {
                    address = "agent/addNewProperty.jsp";
                }
                request.setAttribute("Styles", allStylesList);
                request.setAttribute("Propertytypes", allPropertyTypesList);
                request.setAttribute("Garagetypes", allGarageTypesList);
            } else { //View properties by agent
                if (request.getParameterMap().containsKey("Status")) {
                    int status = Integer.parseInt(request.getParameter("Status"));
                    //String status=request.getParameter("Status");
                    if (status == 1) {
                        request.setAttribute("Status", "This Property Has Been Saved/Updated successfully!");
                    }
                    if (status == 2) {
                        request.setAttribute("Status", "The Property Has Been successfully Removed!");
                    }
                }

                List<Properties> propertyList = null;
                if (request.isUserInRole("admin")) {
                    propertyList = PropertiesDB.getAllProperties();
                    address = "admin/managePropertyList.jsp";
                } else {
                    propertyList = PropertiesDB.getAllPropertiesByAgent(agentId);

                    address = "/agent/managePropertyList.jsp";
                }
                request.setAttribute("propertyList", propertyList);
            }
            if (m.containsKey("propID") && (m.containsKey("agentId") || (request.isUserInRole("admin")))) {
                String StyleType = "";
                String PropType = "";
                String GarageType = "";

                try {
                    Properties propertyDetails = PropertiesDB
                            .getPropertyByID(Integer.parseInt(request.getParameter("propID")));

                    if (propertyDetails == null) {
                        address = "/propertyDetailssss.jsp";
                        request.setAttribute("NoProperties", null);
                    } else {
                        try {
                            PropType = PropertiesDB.getPropType(propertyDetails.getTypeId());
                        } //end try
                        catch (Exception ex) {
                            address = "/Error.jsp";
                        } //end catch
                        try {
                            StyleType = PropertiesDB.getStyleType(propertyDetails.getStyleId());
                        } //end try
                        catch (Exception ex) {
                            address = "/Error.jsp";
                        } //end catch
                        try {
                            GarageType = PropertiesDB.getGarageType(propertyDetails.getGarageId());
                        } //end try
                        catch (Exception ex) {
                            address = "/Error.jsp";
                        } //end catch
                        List<Agents> allAgents = null;
                        try {
                            allAgents = AgentsDB.getAllAgents();
                        } //end try
                        catch (Exception ex) {
                            address = "/Error.jsp";
                        } //end catch

                        //                                List<Styles> allStylesList  = StylesDB.getAllStyles();
                        //                                List<Propertytypes> allPropertyTypesList  = PropertytypeDB.getAllPropertytypes();
                        //                                List<Garagetypes> allGarageTypesList  = GaragetypesDB.getAllGaragetypes();
                        request.setAttribute("propertyDetails", propertyDetails);
                        request.setAttribute("Styles", allStylesList);
                        request.setAttribute("Propertytypes", allPropertyTypesList);
                        request.setAttribute("Garagetypes", allGarageTypesList);

                        if (request.isUserInRole("admin")) {
                            address = "admin/managePropertyDetails.jsp";
                            request.setAttribute("allAgents", allAgents);
                        } else {
                            address = "agent/managePropertyDetails.jsp";
                        }

                    }

                } //end try
                catch (Exception ex) {
                    address = "/Error.jsp";
                } //end catch

            }
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        }
        //            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        //                dispatcher.forward(request, response);
        //        response.sendRedirect("/RealtyWebsite/"+address);
        ////            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        ////            dispatcher.forward(request, response);
        //         
        processRequest(request, response);
    }
    //processRequest(request, response);
}

From source file:dk.dma.msinm.user.security.SecurityServletFilter.java

/**
 * Checks if the request is an attempt to perform user-password or Auth token authentication.
 * <p></p>//w  w w .j av a 2s .c o m
 * For user-password login attempts, the request payload will be a JSON credential object.
 * <p></p>
 * For auth token login attempts, the request payload will be the token itself. The token
 * must have an "auth_" prefix, and the associated JWT token must be found in the AuthCache.
 *
 * @param request the servlet request
 * @param response the servlet response
 * @return the request
 */
public HttpServletRequest handleJwtUserCredentialsOrAuthTokenLogin(HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    String requestBody = WebUtils.readRequestBody(request);

    // Check if this is a user credential login attempt
    Credentials credentials = Credentials.fromRequest(requestBody);
    if (credentials != null) {
        log.info("Logging in with email " + credentials.getEmail());

        // Successful login - create a JWT token
        try {
            request = SecurityUtils.login(userService, request, credentials.getEmail(),
                    credentials.getPassword());

            JWTToken jwt = jwtService.createSignedJWT(getJwtIssuer(request), (User) request.getUserPrincipal());
            WebUtils.nocache(response).setContentType("application/json");
            response.getWriter().write(jwt.toJson());
            auditor.info("User %s logged in. Issued token %s", credentials.getEmail(), jwt.getToken());
            return request;
        } catch (Exception ex) {
        }

    } else {
        // Check if this is an auth token login attempt
        try {
            String token = requestBody.trim();
            if (token.startsWith(AuthCache.AUTH_TOKEN_PREFIX) && authCache.getCache().containsKey(token)) {
                // The tokens are one-off. Remove it as we read it
                JWTToken jwt = authCache.getCache().remove(token);
                WebUtils.nocache(response).setContentType("application/json");
                response.getWriter().write(jwt.toJson());
                auditor.info("User %s logged in via auth token. Issued token %s", jwt.getEmail(),
                        jwt.getToken());
                return request;
            }
        } catch (Exception ex) {
        }
    }

    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    log.warn("Failed logging in using email and password");
    return request;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java

@RequestMapping({ "/login", "/portal", "/" })
public String login(HttpServletRequest request, ModelMap map, HttpSession session) {
    logger.debug("###Entering in login(req,map,session) method");

    boolean loginFailed = request.getParameter(LOGIN_FAILED_PARAM) != null;

    if (!loginFailed && request.getUserPrincipal() != null) {
        map.clear();/*from   ww  w  .  ja v a2s.  c om*/
        return "redirect:/portal/home";
    }

    if (session.getAttribute("email_verified") != null) {
        map.addAttribute("email_verified", session.getAttribute("email_verified"));
        session.removeAttribute("email_verified");
    }
    String showSuffixControl = "false";
    String suffixControlType = "textbox";
    List<String> suffixList = null;
    if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
        showSuffixControl = "true";
        if (config.getValue(Names.com_citrix_cpbm_login_screen_tenant_suffix_dropdown_enabled).equals("true")) {
            suffixControlType = "dropdown";
            suffixList = tenantService.getSuffixList();
        }
    }
    map.addAttribute("showSuffixControl", showSuffixControl);
    map.addAttribute("suffixControlType", suffixControlType);
    map.addAttribute("suffixList", suffixList);
    if (config.getBooleanValue(Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled)
            && config.getValue(Names.com_citrix_cpbm_directory_mode).equals("pull")) {
        map.addAttribute("directoryServiceAuthenticationEnabled", "true");
    }
    if (config.getValue(Names.com_citrix_cpbm_public_catalog_display).equals("true")
            && channelService.getDefaultServiceProviderChannel() != null) {
        map.addAttribute("showAnonymousCatalogBrowsing", "true");
    }
    map.addAttribute("showLanguageSelection", "true");
    map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
    map.addAttribute("selected_language", request.getParameter("lang"));
    String redirect = null;
    boolean loggedOut = request.getParameter(LOGOUT_PARAM) != null;
    final Throwable ex = (Throwable) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

    // capture previous CAPTCHA position
    Boolean captchaRequiredSessionObj = (Boolean) session
            .getAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED);

    // Get last user
    String username = (String) session
            .getAttribute(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY);

    // this as spring does a text-escape when it saves this attribute
    final String uUsername = HtmlUtils.htmlUnescape(username);

    if (loginFailed) {
        String error = " "
                + messageSource.getMessage("error.auth.username.password.invalid", null, request.getLocale());

        try {
            User user = privilegeService.runAsPortal(new PrivilegedAction<User>() {

                @Override
                public User run() {
                    User user = userService.getUserByParam("username", uUsername, false);

                    // All user writes here.
                    // Every time there is a login failure but not invalid CAPTCHA,
                    // we update failed login attempts for the user
                    if (!(ex instanceof CaptchaValidationException) && !(ex instanceof LockedException)
                            && !(ex instanceof IpRangeValidationException)) {
                        user.setFailedLoginAttempts(user.getFailedLoginAttempts() + 1);
                    }

                    int attempts = user.getFailedLoginAttempts();

                    // Also locking the root user and quite easily too. Clearly this
                    // needs an eye!
                    if (attempts >= config.getIntValue(
                            Names.com_citrix_cpbm_accountManagement_security_logins_lockThreshold)) {
                        user.setEnabled(false);
                    }

                    return user;
                }
            });

            int attempts = user.getFailedLoginAttempts();
            if (attempts >= config
                    .getIntValue(Names.com_citrix_cpbm_accountManagement_security_logins_captchaThreshold)) {
                session.setAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED, true);
            }
        } catch (NoSuchUserException e) {
            // map.addAttribute("showCaptcha", true);
        }

        captchaRequiredSessionObj = (Boolean) session
                .getAttribute(CaptchaAuthenticationFilter.CAPTCHA_REQUIRED);

        map.addAttribute("loginFailed", loginFailed);
        String lastUsername = uUsername;

        if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
            if (!lastUsername.equals("root") && !lastUsername.equals("")) {
                lastUsername = lastUsername.substring(0, lastUsername.lastIndexOf('@'));
            }
        }
        map.addAttribute("lastUser", lastUsername);

        // Compose error string
        if (ex instanceof DisabledException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else if (ex instanceof CaptchaValidationException) {
            error = " " + messageSource.getMessage("error.auth.captcha.invalid", null, request.getLocale());
        } else if (ex instanceof IpRangeValidationException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else if (ex instanceof LockedException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else if (ex instanceof BadCredentialsException) {
            if (ex.getMessage() != null && ex.getMessage().length() > 0) {
                // error = " " + ex.getMessage();
                error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                        request.getLocale());
            }
        } else if (ex instanceof AuthenticationException) {
            error = " " + messageSource.getMessage("error.auth.username.password.invalid", null,
                    request.getLocale());
        } else {
            logger.error("Error occurred in authentication", ex);
            error = " " + messageSource.getMessage("error.auth.unknown", null, request.getLocale());
        }

        if (captchaRequiredSessionObj != null && captchaRequiredSessionObj == true
                && !(ex instanceof CaptchaValidationException) && !(ex instanceof LockedException)) {
            error += " " + messageSource.getMessage("error.auth.account.may.locked", null, request.getLocale());
        }

        map.addAttribute("error", error);

    }

    if (loggedOut) {
        map.addAttribute("logout", loggedOut);
    }

    // This could come from session or from user
    if (captchaRequiredSessionObj != null && captchaRequiredSessionObj.booleanValue()
            && !Boolean.valueOf(config.getValue(Names.com_citrix_cpbm_use_intranet_only))) {
        map.addAttribute("showCaptcha", true);
        map.addAttribute("recaptchaPublicKey", config.getRecaptchaPublicKey());
    }

    map.addAttribute(TIME_OUT, request.getParameter(TIME_OUT) != null);
    map.addAttribute(VERIFY, request.getParameter(VERIFY) != null);
    logger.debug("###Exiting login(req,map,session) method");

    if (config.getAuthenticationService().compareToIgnoreCase(CAS) == 0) {
        try {
            redirect = StringUtils.isEmpty(config.getCasLoginUrl()) ? null
                    : config.getCasLoginUrl() + "?service="
                            + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("Exception encoding: " + redirect, e);
        }
        if (redirect == null) {
            throw new InternalError("CAS authentication required, but login url not set");
        }
    }
    return redirect == null ? "auth.login" : "redirect:" + redirect;
}

From source file:org.rti.zcore.dar.report.CombinedReportAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.//from  w ww  .  jav  a2s .  c o m
 *
 * @param mapping  The ActionMapping used to select this instance
 * @param form     The optional ActionForm bean for this request (if any)
 * @param request  The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return Action to forward to
 * @throws Exception if an input/output error or servlet exception occurs
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ParameterActionForward fwd = null;
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    Connection conn = null;
    HttpSession session = request.getSession();
    /*boolean dynamicReport = false;
    boolean isFacilityReport = false;
    if (request.getParameter("dynamicReport") != null) {
       dynamicReport = true;
      }
    if (request.getParameter("isFacilityReport") != null) {
       isFacilityReport = true;
    }*/
    SessionUtil zeprs_session = null;
    Site site = null;
    String siteAbbrev = null;
    String reportName = null;
    Register report = null;
    Class clazz = null;
    String className = null;
    try {
        zeprs_session = (SessionUtil) session.getAttribute("zeprs_session");
    } catch (Exception e) {
        // unit testing - it's ok...
    }
    try {
        ClientSettings clientSettings = zeprs_session.getClientSettings();
        site = clientSettings.getSite();
        siteAbbrev = site.getAbbreviation();
    } catch (SessionUtil.AttributeNotFoundException e) {
        log.error(e);
    } catch (NullPointerException e) {
        // it's ok - unit testing
        siteAbbrev = "test";
    }

    DailyActivityReport aReport = null;
    MonthlyArtReport mReport = null;

    String template = DarConstants.COMBINED_REPORT_FILENAME;

    /*if (isFacilityReport) {
       template = "Monthly Facility Reports for ART and OI";
    } else {
       template = "ART_&_PMTCT_LMIS_Data_Aggregation_Tool";
    }*/

    int i = 1;
    //String reportFileName = "Monthly Reports for ARV and OI" + "-" + siteAbbrev + "-" + username + "-" + DateUtils.getNowPretty() + "-" + i;

    String reportFileName = template + "-" + siteAbbrev + "-" + username + "-" + DateUtils.getNowPretty() + "-"
            + i;
    String path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports"
            + Constants.pathSep + reportFileName + ".xls";
    // check if file exists
    File f = new File(path);
    while (f.exists()) {
        i++;
        //reportFileName = "Monthly Reports for ARV and OI" + "-" + siteAbbrev + "-" + username + "-" + DateUtils.getNowPretty() + "-" + i;
        reportFileName = template + "-" + siteAbbrev + "-" + username + "-" + DateUtils.getNowPretty() + "-"
                + i;
        path = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports"
                + Constants.pathSep + reportFileName + ".xls";
        f = new File(path);
    }
    //String reportFileName = report.getReportFileName();
    //String pathXml = Constants.ARCHIVE_PATH + site.getAbbreviation()  + Constants.pathSep + "reports" + Constants.pathSep + reportFileName + ".xml";
    //String pathExcel = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports" + Constants.pathSep + reportFileName + ".xls";
    //String combinedReport = Constants.ARCHIVE_PATH + site.getAbbreviation() + Constants.pathSep + "reports" + Constants.pathSep + "Monthly Reports for ARV and OI.xls";
    String pathExcelMaster = null;
    /*if (dynamicReport) {
       pathExcelMaster = Constants.ARCHIVE_PATH + Constants.pathSep + "Monthly Reports for ARV and OI-dynamic.xls";
    } else {*/
    //pathExcelMaster = Constants.ARCHIVE_PATH + Constants.pathSep + "Monthly Reports for ARV and OI.xls";
    pathExcelMaster = Constants.ARCHIVE_PATH + Constants.pathSep + template;
    //}

    String[] args = new String[] { pathExcelMaster };
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
            org.rti.zcore.Constants.DATE_FORMAT_EXCEL_LONG);
    sdf.setTimeZone(TimeZone.getDefault());

    try {
        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(pathExcelMaster));
        HSSFWorkbook wb = new HSSFWorkbook(fs);

        // CDRR-ART
        reportName = "CDRRArtReport"; //  may use CDRRArtReport, CDRROIReport, or MonthlyArtReport
        className = "org.rti.zcore.dar.report." + StringManipulation.fixClassname(reportName);

        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            log.error(e);
        }
        try {
            report = (Register) clazz.newInstance();
        } catch (InstantiationException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        }
        report = SessionUtil.getInstance(session).getReports().get(reportName);
        if (report != null) {
            aReport = (DailyActivityReport) report;
            HSSFSheet aSsheet = null;
            int sheetPos = 0;
            String rowNumStr = null;
            int rowNum = 0;
            String cellNumStr = null;
            int cellNum = 0;
            String districtName = null;
            String provinceName = null;
            // Must first pre-fill the header info in the Facilities spreadsheet - Office 2010 compatibility issue.
            String filename = org.rti.zcore.Constants.getPathToCatalinaHome() + "databases" + File.separator
                    + "facilities.txt";
            for (String line : new TextFile(filename)) {
                //System.out.println(line);
                String[] lineArray = line.split("\\|");
                String itemName = lineArray[0];
                if (itemName.equals("sheet")) {
                    String sheetPosStr = lineArray[1];
                    sheetPos = Integer.valueOf(sheetPosStr) - 1;
                    aSsheet = wb.getSheetAt(sheetPos);
                } else if (itemName.equals("siteName")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    HSSFRichTextString hssfRichTextString = new HSSFRichTextString(report.getSiteName());
                    HSSFCell cell = aSsheet.getRow(rowNum).getCell(cellNum);
                    cell.setCellValue(hssfRichTextString);
                } else if (itemName.equals("district")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    districtName = lineArray[3];
                    aSsheet.getRow(rowNum).getCell(cellNum).setCellValue(new HSSFRichTextString(districtName));
                } else if (itemName.equals("province")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    provinceName = lineArray[3];
                    aSsheet.getRow(rowNum).getCell(cellNum).setCellValue(new HSSFRichTextString(provinceName));
                } else if (itemName.equals("beginDate")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    aSsheet.getRow(rowNum).getCell(cellNum)
                            .setCellValue(new HSSFRichTextString(sdf.format(report.getBeginDate().getTime())));
                } else if (itemName.equals("endDate")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    aSsheet.getRow(rowNum).getCell(cellNum)
                            .setCellValue(new HSSFRichTextString(sdf.format(report.getEndDate().getTime())));
                }
            }
            filename = org.rti.zcore.Constants.getPathToCatalinaHome() + "databases" + File.separator
                    + "cdrr.txt";
            for (String line : new TextFile(filename)) {
                //System.out.println(line);
                String[] lineArray = line.split("\\|");
                String itemName = lineArray[0];
                if (itemName.equals("sheet")) {
                    String sheetPosStr = lineArray[1];
                    sheetPos = Integer.valueOf(sheetPosStr) - 1;
                    aSsheet = wb.getSheetAt(sheetPos);
                } else if (itemName.equals("siteName")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    HSSFRichTextString hssfRichTextString = new HSSFRichTextString(report.getSiteName());
                    HSSFCell cell = aSsheet.getRow(rowNum).getCell(cellNum);
                    cell.setCellValue(hssfRichTextString);
                } else if (itemName.equals("district")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    districtName = lineArray[3];
                    aSsheet.getRow(rowNum).getCell(cellNum).setCellValue(new HSSFRichTextString(districtName));
                } else if (itemName.equals("province")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    provinceName = lineArray[3];
                    aSsheet.getRow(rowNum).getCell(cellNum).setCellValue(new HSSFRichTextString(provinceName));
                } else if (itemName.equals("beginDate")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    aSsheet.getRow(rowNum).getCell(cellNum)
                            .setCellValue(new HSSFRichTextString(sdf.format(report.getBeginDate().getTime())));
                } else if (itemName.equals("endDate")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    aSsheet.getRow(rowNum).getCell(cellNum)
                            .setCellValue(new HSSFRichTextString(sdf.format(report.getEndDate().getTime())));
                }
            }

            /*aSsheet.getRow(3).getCell(1).setCellValue(new HSSFRichTextString(report.getSiteName()));
            aSsheet.getRow(3).getCell(7).setCellValue(new HSSFRichTextString("Nairobi"));
            aSsheet.getRow(3).getCell(13).setCellValue(new HSSFRichTextString("Nairobi"));
            aSsheet.getRow(4).getCell(1).setCellValue(new HSSFRichTextString(sdf.format(report.getBeginDate().getTime())));
            aSsheet.getRow(4).getCell(7).setCellValue(new HSSFRichTextString(sdf.format(report.getEndDate().getTime())));*/
            CDRRArtSheetPopulater.populateCDRRArtSheet(aReport, aSsheet, 12);
            //CDRRArtSheetPopulater.populateDynamicCDRRArtSheet(aReport, aSsheet, 43, wb, false);
        }

        // CDRR-OI no longer used.
        /*reportName = "CDRROIReport";   //  may use CDRRArtReport, CDRROIReport, or MonthlyArtReport
        className = "org.rti.zcore.dar.report." + StringManipulation.fixClassname(reportName);
        report = null;
        clazz = null;
        try {
           clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
           log.error(e);
        }
        try {
           report = (Register) clazz.newInstance();
        } catch (InstantiationException e) {
           log.error(e);
        } catch (IllegalAccessException e) {
           log.error(e);
        }
        report = SessionUtil.getInstance(session).getReports().get(reportName);
        if (report != null) {
           CDRROIReport oReport = (CDRROIReport) report;
           HSSFSheet oSsheet  = null;
           if (isFacilityReport) {
              oSsheet  = wb.getSheetAt(1);
           } else {
              oSsheet  = wb.getSheetAt(2);
           //}
           oSsheet.getRow(3).getCell(1).setCellValue(new HSSFRichTextString("KEMSA"));
           oSsheet.getRow(4).getCell(1).setCellValue(new HSSFRichTextString(report.getSiteName()));
           oSsheet.getRow(5).getCell(1).setCellValue(new HSSFRichTextString("Nairobi"));
           oSsheet.getRow(6).getCell(1).setCellValue(new HSSFRichTextString(sdf.format(report.getBeginDate().getTime())));
           oSsheet.getRow(6).getCell(11).setCellValue(new HSSFRichTextString(sdf.format(report.getEndDate().getTime())));
           // now fill in the report data
           if (dynamicReport) {
              CDRROiSheetPopulater.populateDynamicCDRRPOiSheet(oReport, oSsheet);
           } else {
              //CDRROiSheetPopulater.populateCDRRPOiSheet(oReport, oSsheet);
           //}
        }*/

        reportName = "MonthlyArtReport"; //  may use CDRRArtReport, CDRROIReport, or MonthlyArtReport
        className = "org.rti.zcore.dar.report." + StringManipulation.fixClassname(reportName);
        report = null;
        clazz = null;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            log.error(e);
        }
        try {
            report = (Register) clazz.newInstance();
        } catch (InstantiationException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        }
        report = SessionUtil.getInstance(session).getReports().get(reportName);

        if (report != null) {
            mReport = (MonthlyArtReport) report;
            // Monthly ART Report
            HSSFSheet mSsheet = null;

            // populate the statistics
            //SiteStatisticsReport register = new SiteStatisticsReport();
            /*int siteId = report.getSiteId();
            SiteStatistics stats = new SiteStatistics();
            try {
               conn = DatabaseUtils.getZEPRSConnection(org.rti.zcore.Constants.DATABASE_ADMIN_USERNAME);
               Integer newClients = SiteStatisticsDAO.getNewClients(conn, beginDate, endDate, siteId);
            stats.setNewClients(newClients);
               Integer femaleAdults = SiteStatisticsDAO.getFemaleAdults(conn, siteId);
               stats.setFemaleAdults(femaleAdults);
               Integer femaleChildren = SiteStatisticsDAO.getFemaleChildren(conn, siteId);
               stats.setFemaleChildren(femaleChildren);
               stats.setFemales(femaleAdults + femaleChildren);
               Integer maleAdults = SiteStatisticsDAO.getMaleAdults(conn, siteId);
               stats.setMaleAdults(maleAdults);
               Integer maleChildren = SiteStatisticsDAO.getMaleChildren(conn, siteId);
               stats.setMaleChildren(maleChildren);
               stats.setMales(maleAdults + maleChildren);
               stats.setAdults(maleAdults + femaleAdults);
               stats.setChildren(maleChildren + femaleChildren);
               stats.setAllClients(maleAdults + femaleAdults +maleChildren + femaleChildren);
            Integer statusDied = SiteStatisticsDAO.getStatusDied(conn, beginDate, endDate, siteId);
            stats.setStatusDied(statusDied);
            Integer statusTransferred = SiteStatisticsDAO.getStatusTransferred(conn, beginDate, endDate, siteId);
            stats.setStatusTransferred(statusTransferred);
            Integer statusDefaulters = SiteStatisticsDAO.getStatusDefaulters(conn, beginDate, endDate, siteId);
            stats.setStatusDefaulters(statusDefaulters);
            Integer statusOther = SiteStatisticsDAO.getStatusOther(conn, beginDate, endDate, siteId);
            stats.setStatusOther(statusOther);
            Integer activeArvClients = SiteStatisticsDAO.getActiveArvClients(conn, beginDate, endDate, siteId);
            stats.setActiveArvClients(activeArvClients);
            ArrayList<RegimenReport> regimens = SiteStatisticsDAO.getRegimens(conn, beginDate, endDate, siteId);
            stats.setRegimens(regimens);
               mSsheet.getRow(8).getCell(2).setCellValue(new HSSFRichTextString("Client totals include all clients in the database."));
               mSsheet.getRow(9).getCell(2).setCellValue(new HSSFRichTextString(stats.getAdults().toString()));
               mSsheet.getRow(9).getCell(6).setCellValue(new HSSFRichTextString(stats.getChildren().toString()));
               mSsheet.getRow(11).getCell(2).setCellValue(new HSSFRichTextString(stats.getMales().toString()));
               mSsheet.getRow(11).getCell(4).setCellValue(new HSSFRichTextString(stats.getFemales().toString()));
            } catch (Exception e) {
               e.printStackTrace();
            } finally {
               try {
                  conn.close();
               } catch (SQLException e) {
                  log.error(e);
               }
            }*/

            String filename = org.rti.zcore.Constants.getPathToCatalinaHome() + "databases" + File.separator
                    + "regimens.txt";
            int sheetPos = 0;
            String rowNumStr = null;
            int rowNum = 0;
            String cellNumStr = null;
            int cellNum = 0;
            String districtName = null;
            String provinceName = null;

            for (String line : new TextFile(filename)) {
                //System.out.println(line);
                String[] lineArray = line.split("\\|");
                String itemName = lineArray[0];
                if (itemName.equals("sheet")) {
                    String sheetPosStr = lineArray[1];
                    sheetPos = Integer.valueOf(sheetPosStr) - 1;
                    mSsheet = wb.getSheetAt(sheetPos);
                } else if (itemName.equals("siteName")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    mSsheet.getRow(rowNum).getCell(cellNum)
                            .setCellValue(new HSSFRichTextString(report.getSiteName()));
                } else if (itemName.equals("district")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    districtName = lineArray[3];
                    mSsheet.getRow(rowNum).getCell(cellNum).setCellValue(new HSSFRichTextString(districtName));
                } else if (itemName.equals("province")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    provinceName = lineArray[3];
                    mSsheet.getRow(rowNum).getCell(cellNum).setCellValue(new HSSFRichTextString(provinceName));
                } else if (itemName.equals("beginDate")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    mSsheet.getRow(rowNum).getCell(cellNum)
                            .setCellValue(new HSSFRichTextString(sdf.format(report.getBeginDate().getTime())));
                } else if (itemName.equals("endDate")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    mSsheet.getRow(rowNum).getCell(cellNum)
                            .setCellValue(new HSSFRichTextString(sdf.format(report.getEndDate().getTime())));
                } else if (itemName.equals("adultsTotal")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    //${register.artRegimenReport.totalAdultsDispensed}
                    HSSFCell cell = mSsheet.getRow(rowNum).getCell(cellNum);
                    cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(aReport.getArtRegimenReport().getTotalAdultsDispensed());
                } else if (itemName.equals("childrenTotal")) {
                    rowNumStr = lineArray[1];
                    rowNum = Integer.valueOf(rowNumStr) - 1;
                    cellNumStr = lineArray[2];
                    cellNum = Integer.valueOf(cellNumStr) - 1;
                    //${register.artRegimenReport.totalAdultsDispensed}
                    HSSFCell cell = mSsheet.getRow(rowNum).getCell(cellNum);
                    cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(aReport.getArtRegimenReport().getTotalChildrenDispensed());
                }
                /*else if (itemName.equals("totalMalesNew")) {
                   rowNumStr = lineArray[1];
                   rowNum = Integer.valueOf(rowNumStr)-1;
                   cellNumStr = lineArray[2];
                   cellNum = Integer.valueOf(cellNumStr)-1;
                   //${register.artRegimenReport.totalAdultsDispensed}
                   mSsheet.getRow(rowNum).getCell(cellNum).setCellValue(aReport.getArtRegimenReport().getTotalChildrenDispensed());
                } else if (itemName.equals("totalMalesRevisit")) {
                   rowNumStr = lineArray[1];
                   rowNum = Integer.valueOf(rowNumStr)-1;
                   cellNumStr = lineArray[2];
                   cellNum = Integer.valueOf(cellNumStr)-1;
                   //${register.artRegimenReport.totalAdultsDispensed}
                   mSsheet.getRow(rowNum).getCell(cellNum).setCellValue(aReport.getArtRegimenReport().getTotalChildrenDispensed());
                } else if (itemName.equals("totalFemalesNew")) {
                   rowNumStr = lineArray[1];
                   rowNum = Integer.valueOf(rowNumStr)-1;
                   cellNumStr = lineArray[2];
                   cellNum = Integer.valueOf(cellNumStr)-1;
                   //${register.artRegimenReport.totalAdultsDispensed}
                   mSsheet.getRow(rowNum).getCell(cellNum).setCellValue(aReport.getArtRegimenReport().getTotalChildrenDispensed());
                } else if (itemName.equals("totalFemalesRevisit")) {
                   rowNumStr = lineArray[1];
                   rowNum = Integer.valueOf(rowNumStr)-1;
                   cellNumStr = lineArray[2];
                   cellNum = Integer.valueOf(cellNumStr)-1;
                   //${register.artRegimenReport.totalAdultsDispensed}
                   mSsheet.getRow(rowNum).getCell(cellNum).setCellValue(aReport.getArtRegimenReport().getTotalChildrenDispensed());
                }*/
            }
            MonthlyArtSheetPopulater.populateMonthlyArtSheet(mReport, mSsheet, 8);
            //MonthlyArtSheetPopulater.populateDynamicMonthlyArtSheet(mReport, mSsheet, 100);

        }
        FileOutputStream stream = new FileOutputStream(path);
        wb.write(stream);
        stream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    fwd = new ParameterActionForward(mapping.findForward(SUCCESS_FORWARD));
    String url = path.replace("&", "%26");
    fwd.addParameter("path", url);
    //return mapping.findForward("success");
    return fwd;
}

From source file:org.jets3t.servlets.gatekeeper.GatekeeperServlet.java

/**
 * Handles POST requests that contain Gatekeeper messages encoded as POST form properties, and
 * sends a plain text response document containing the Gatekeeper response message encoded as
 * a properties file.//from   w  ww .  j a  v a2 s  . c  o  m
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (log.isDebugEnabled()) {
        log.debug("Handling POST request");
    }
    try {
        // Build Gatekeeper request from POST form parameters.
        GatekeeperMessage gatekeeperMessage = GatekeeperMessage.decodeFromProperties(request.getParameterMap());

        // Obtain client information
        ClientInformation clientInformation = new ClientInformation(request.getRemoteAddr(),
                request.getRemoteHost(), request.getRemoteUser(), request.getRemotePort(),
                request.getSession(false), request.getUserPrincipal(), request.getHeader("User-Agent"),
                request);

        // Generate Transaction ID, and store it in the message.
        String transactionId = transactionIdProvider.getTransactionId(gatekeeperMessage, clientInformation);
        if (transactionId != null) {
            gatekeeperMessage.addMessageProperty(GatekeeperMessage.PROPERTY_TRANSACTION_ID, transactionId);
        }

        if (!isInitCompleted) {
            if (log.isWarnEnabled()) {
                log.warn("Cannot process POST request as Gatekeeper servlet did not initialize correctly");
            }
            gatekeeperMessage.addApplicationProperty(GatekeeperMessage.APP_PROPERTY_GATEKEEPER_ERROR_CODE,
                    "GatekeeperInitializationError");
        } else if (gatekeeperMessage.getApplicationProperties()
                .containsKey(GatekeeperMessage.LIST_OBJECTS_IN_BUCKET_FLAG)) {
            // Handle "limited listing" requests.
            if (log.isDebugEnabled()) {
                log.debug("Listing objects");
            }
            boolean allowed = authorizer.allowBucketListingRequest(gatekeeperMessage, clientInformation);
            if (allowed) {
                bucketLister.listObjects(gatekeeperMessage, clientInformation);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Processing " + gatekeeperMessage.getSignatureRequests().length
                        + " object signature requests");
            }
            // Process each signature request.
            for (int i = 0; i < gatekeeperMessage.getSignatureRequests().length; i++) {
                SignatureRequest signatureRequest = gatekeeperMessage.getSignatureRequests()[i];

                // Determine whether the request will be allowed. If the request is not allowed, the
                // reason will be made available in the signature request object (with signatureRequest.declineRequest())
                boolean allowed = authorizer.allowSignatureRequest(gatekeeperMessage, clientInformation,
                        signatureRequest);

                // Sign requests when they are allowed. When a request is signed, the signed URL is made available
                // in the SignatureRequest object.
                if (allowed) {
                    String signedUrl = null;
                    if (SignatureRequest.SIGNATURE_TYPE_GET.equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signGet(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_HEAD
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signHead(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_PUT
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signPut(gatekeeperMessage, clientInformation, signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_DELETE
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signDelete(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_ACL_LOOKUP
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signGetAcl(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    } else if (SignatureRequest.SIGNATURE_TYPE_ACL_UPDATE
                            .equals(signatureRequest.getSignatureType())) {
                        signedUrl = urlSigner.signPutAcl(gatekeeperMessage, clientInformation,
                                signatureRequest);
                    }
                    signatureRequest.signRequest(signedUrl);
                }
            }
        }

        // Build response as a set of properties, and return this document.
        Properties responseProperties = gatekeeperMessage.encodeToProperties();
        if (log.isDebugEnabled()) {
            log.debug("Sending response message as properties: " + responseProperties);
        }

        // Serialize properties to bytes.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        responseProperties.store(baos, "");

        // Send successful response.
        response.setStatus(200);
        response.setContentType("text/plain");
        response.getOutputStream().write(baos.toByteArray());
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Gatekeeper failed to send valid response", e);
        }
        response.setStatus(500);
        response.setContentType("text/plain");
        response.getWriter().println(e.toString());
    }
}

From source file:com.egt.core.util.Utils.java

public void trace(String objeto, String metodo, String contexto) {
    System.out.println(objeto + "." + metodo + "(" + contexto + ")");
    FacesContext facesContext = FacesContext.getCurrentInstance();
    System.out.println(objeto + "." + metodo + "(" + facesContext + ")");
    if (facesContext == null) {
        return;/*  ww w . j  av  a2 s.  c o m*/
    }
    traceContext();
    HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
    System.out.println("request ..................... " + request);
    System.out.println("request.getAuthType ......... " + request.getAuthType());
    System.out.println("request.getUserPrincipal .... " + request.getUserPrincipal());
    Principal principal = facesContext.getExternalContext().getUserPrincipal();
    System.out.println("principal ................... " + principal);
    if (principal != null) {
        System.out.println("principal.getName ........... " + principal.getName());
        System.out.println("isSuperUsuario .............. " + request.isUserInRole("SuperUsuario"));
        System.out.println("isUsuarioEstandar ........... " + request.isUserInRole("UsuarioEstandar"));
        System.out.println("isUsuarioBasico.. ........... " + request.isUserInRole("UsuarioBasico"));
    }
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    HttpSession session = request.getSession(false);
    System.out.println("session ..................... " + facesContext.getExternalContext().getSession(false));
    System.out.println("session.getId ............... " + session.getId());
    String key;
    Object object;
    Set sessionKeys = facesContext.getExternalContext().getSessionMap().keySet();
    if (sessionKeys.isEmpty()) {
    } else {
        Iterator iterator = sessionKeys.iterator();
        while (iterator.hasNext()) {
            object = iterator.next();
            if (object instanceof String) {
                key = (String) object;
                object = facesContext.getExternalContext().getSessionMap().get(key);
                if (object != null) {
                    System.out.println(key + " = (" + object.getClass().getName() + ") " + object);
                }
            }
        }
    }
    System.out.println("request.getContextPath ...... " + request.getContextPath());
    System.out.println("request.getServletPath ...... " + request.getServletPath());
    System.out.println("request.getPathInfo ......... " + request.getPathInfo());
    System.out.println("request.getRequestURI ....... " + request.getRequestURI());
    System.out.println("request.getContextPathURL ... " + request.getRequestURL().toString());
    String clave;
    System.out.println("*** parametros ***");
    Iterator iterator = request.getParameterMap().keySet().iterator();
    while (iterator.hasNext()) {
        clave = (String) iterator.next();
        System.out.println(clave + " = " + request.getParameter(clave));
    }
    String cookieName;
    System.out.println("**** cookies  ****");
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookieName = cookies[i].getName();
            System.out.println(cookieName + " = " + cookies[i].getValue());
        }
    }
}

From source file:org.springframework.faces.mvc.annotation.support.AnnotatedMethodInvoker.java

/**
 * Resolve a standard argument type. This method can be overridden by subclasses to extend supported argument types.
 * @param parameterType The paramter type to resolve
 * @param webRequest The web request/*from w  w w  .  ja va2  s. co m*/
 * @return The resolved argument (can be <tt>null</tt>) or {@link WebArgumentResolver#UNRESOLVED} if the argument
 * @throws Exception on error
 */
protected Object resolveStandardArgument(Class parameterType, NativeWebRequest webRequest) throws Exception {
    if ((webRequest.getNativeRequest() instanceof HttpServletRequest)
            && (webRequest.getNativeResponse() instanceof HttpServletResponse)) {

        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        HttpServletResponse response = (HttpServletResponse) webRequest.getNativeResponse();

        if (ServletRequest.class.isAssignableFrom(parameterType)) {
            return request;
        } else if (ServletResponse.class.isAssignableFrom(parameterType)) {
            return response;
        } else if (HttpSession.class.isAssignableFrom(parameterType)) {
            return request.getSession();
        } else if (Principal.class.isAssignableFrom(parameterType)) {
            return request.getUserPrincipal();
        } else if (Locale.class.equals(parameterType)) {
            return RequestContextUtils.getLocale(request);
        } else if (InputStream.class.isAssignableFrom(parameterType)) {
            return request.getInputStream();
        } else if (Reader.class.isAssignableFrom(parameterType)) {
            return request.getReader();
        } else if (OutputStream.class.isAssignableFrom(parameterType)) {
            return response.getOutputStream();
        } else if (Writer.class.isAssignableFrom(parameterType)) {
            return response.getWriter();
        } else if (WebRequest.class.isAssignableFrom(parameterType)) {
            return webRequest;
        }
    }
    return WebArgumentResolver.UNRESOLVED;
}

From source file:org.nuxeo.ecm.webengine.DefaultWebContext.java

public CoreSession getCoreSession(HttpServletRequest request) throws Exception {
    CoreSession session = null;//from w  w  w. java  2s .com

    HttpSession httpSession = request.getSession(true);

    // FIXME: session is alway null here, there is no need to check ?
    if (session == null) {
        session = (CoreSession) httpSession.getAttribute(CORESESSION_KEY);
        if (session != null) {
            return session;
        }
    }
    Principal principal = request.getUserPrincipal();
    if (principal instanceof NuxeoPrincipal) {
        if (((NuxeoPrincipal) principal).isAnonymous()) { // use the anonymous session
            session = getAnonymousSession();
        } else {
            session = openSession();
        }
    } else {
        session = openSession();
    }
    if (httpSession != null) {
        httpSession.setAttribute(CORESESSION_KEY, session);
    }
    return session;
}

From source file:org.rti.zcore.dar.struts.action.FormAction.java

/**
 * Check formId to see what is the next form to be served.
 *
 * @param request/*from www .  ja  v a 2 s .  com*/
 * @param mapping
 * @param patientId
 * @param eventUuid
 * @param dynaForm
 * @param session
 * @param formId
 * @param vo Useful when you need to pass the encounterId in the url parameters
 * @return the next page/form
 */
private ActionForward createForward(HttpServletRequest request, ActionMapping mapping, Long patientId,
        String eventUuid, DynaValidatorForm dynaForm, HttpSession session, int formId, EncounterData vo) {
    BaseSessionSubject sessionPatient = null;
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    String formName = mapping.getParameter().trim();
    Connection conn = null;
    Form nextForm = new Form();

    Integer maxRows = 0;
    if (request.getParameter("maxRows") != null) {
        maxRows = Integer.decode(request.getParameter("maxRows"));
    } else if (request.getAttribute("maxRows") != null) {
        maxRows = Integer.decode(request.getAttribute("maxRows").toString());
    } else {
        switch (formId) {
        case 128:
            maxRows = 0;
            break;
        case 129:
            maxRows = 0;
            break;
        case 130:
            maxRows = 0;
            break;
        case 131:
            maxRows = 0;
            break;
        case 181:
            maxRows = 0;
            break;

        default:
            maxRows = 20;
            break;
        }
    }

    try {
        conn = DatabaseUtils.getZEPRSConnection(username);
        try {
            sessionPatient = SessionUtil.getInstance(session).getSessionPatient();
        } catch (SessionUtil.AttributeNotFoundException e) {
            //log.error("Unable to get TimsSessionSubject");
        }

        Form form = (Form) DynaSiteObjects.getForms().get(Long.valueOf(formId));
        Long formTypeId = form.getFormTypeId();

        // part of reload prevention scheme:
        resetToken(request);
        dynaForm.reset(mapping, request);
        StrutsUtils.removeFormBean(mapping, request);

        ActionForward forwardForm = null;
        String forwardString = null;
        switch (formId) {
        case 1: // Patient Registration
            forwardString = "/ArtRegimen/new.do?patientId=" + patientId.toString();
            break;
        case 137: // ART Regimen
            forwardString = "/PatientItem/new.do?patientId=" + patientId.toString();
            break;
        case 132: // Dispensary
            //forwardString = "/patientTask.do?flowId=" + flowId.toString();
            forwardString = "/Appointment/new.do?patientId=" + patientId.toString();
            //forwardString = "/chart.do?patientId=" + patientId.toString() + "&formId=" + formId;
            break;
        /*case 136:
          forwardString = "/chart.do?patientId=" + patientId.toString() + "&formId=" + formId;
           break;*/
        case 136: // PatientCondition
            forwardString = "/PatientCondition/new.do?patientId=" + patientId.toString();
            break;
        case 179: // Appt
            if (Constants.APPOINTMENT_COUNT_THRESHOLD != null) {
                Appointment appt = (Appointment) vo;
                Date apptDate = appt.getAppointment_date();
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
                        org.rti.zcore.Constants.DATE_FORMAT_SHORT);
                sdf.setTimeZone(TimeZone.getDefault());
                String apptDateStr = sdf.format(appt.getAppointment_date().getTime());

                ResultSet rs = null;
                Integer countAppts = 0;
                String warningMessage = "";
                try {
                    String sql = "SELECT COUNT(encounter.id) AS countAppts " + "FROM encounter, appointment "
                            + "WHERE appointment.id=encounter.id " + "AND appointment_date = ? ";
                    PreparedStatement ps = conn.prepareStatement(sql);
                    ps.setDate(1, apptDate);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        countAppts = rs.getInt("countAppts");
                    }
                } catch (Exception ex) {
                    log.error(ex);
                }
                Integer apptCountThreshold = Integer.valueOf(Constants.APPOINTMENT_COUNT_THRESHOLD);
                if (countAppts != null && countAppts > 0) {
                    Integer warningThreshold = apptCountThreshold - 10;
                    if ((countAppts >= warningThreshold) && (countAppts < apptCountThreshold)) {
                        warningMessage = "Warning: Approaching Threshold of " + apptCountThreshold
                                + " Appointments";
                    } else if (countAppts >= apptCountThreshold) {
                        warningMessage = "Warning: Passed Threshold of " + apptCountThreshold
                                + " Appointments.";
                    }
                    forwardString = "/Appointment/new.do?patientId=" + patientId.toString() + "&warningMessage="
                            + warningMessage + "&countAppts=" + countAppts + "&apptDate=" + apptDateStr;
                } else {
                    forwardString = "/Appointment/new.do?patientId=" + patientId.toString() + "&countAppts="
                            + countAppts + "&apptDate=" + apptDateStr;
                }
            } else {
                forwardString = "/Appointment/new.do?patientId=" + patientId.toString();
            }
            break;
        case 180: // Appt
            forwardString = "/PatientStatus_changes/new.do?patientId=" + patientId.toString();
            break;

        default:
            switch (formTypeId.intValue()) {
            case 5: // admin
                forwardString = "/admin/records/list.do?formId=" + formId + "&maxRows=" + maxRows;
                break;
            case 7: // charts
                forwardString = "/chart.do?id=" + formId;
                break;
            case 8: // lists
                forwardString = "/recordList.do?formId=" + formId + "&patientId=" + patientId.toString();
                break;
            default:
                if (sessionPatient != null) {
                    Long flowId = sessionPatient.getCurrentFlowId();
                    forwardString = "/patientTask.do?flowId=" + flowId.toString();
                } else {
                    forwardString = "/home.do";
                }
                break;
            }
            break;
        }
        forwardForm = new ActionForward(forwardString);
        forwardForm.setRedirect(true);
        return forwardForm;
    } catch (ServletException e) {
        log.error(e);
    } finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            log.error(e);
        }
    }

    return (new ActionForward(mapping.getInput()));
}

From source file:org.sakaiproject.citation.impl.CitationListAccessServlet.java

protected void handleExportRequest(HttpServletRequest req, HttpServletResponse res, Reference ref,
        String format, String subtype)
        throws EntityNotDefinedException, EntityAccessOverloadException, EntityPermissionException {
    if (!ContentHostingService.allowGetResource(req.getParameter("resourceId"))) {
        String url = (req.getRequestURL()).toString();
        String user = "";
        if (req.getUserPrincipal() != null) {
            user = req.getUserPrincipal().getName();
        }//from w  w  w . j  a  v  a2s  .co  m
        throw new EntityPermissionException(user, ContentHostingService.EVENT_RESOURCE_READ,
                ref.getReference());
    }

    String fileName = req.getParameter("resourceDisplayName");
    if (fileName == null || fileName.trim().equals("")) {
        fileName = rb.getString("export.default.filename");
    }

    if (org.sakaiproject.citation.api.CitationService.RIS_FORMAT.equals(format)) {
        String citationCollectionId = req.getParameter("citationCollectionId");
        List<String> citationIds = new java.util.ArrayList<String>();
        CitationCollection collection = null;
        try {
            collection = CitationService.getCollection(citationCollectionId);
        } catch (IdUnusedException e) {
            throw new EntityNotDefinedException(ref.getReference());
        }

        // decide whether to export selected or entire list
        if (org.sakaiproject.citation.api.CitationService.REF_TYPE_EXPORT_RIS_SEL.equals(subtype)) {
            // export selected
            String[] paramCitationIds = req.getParameterValues("citationId");

            if (paramCitationIds == null || paramCitationIds.length < 1) {
                // none selected - do not continue
                try {
                    res.sendError(HttpServletResponse.SC_BAD_REQUEST, rb.getString("export.none_selected"));
                } catch (IOException e) {
                    m_log.warn(
                            "export-selected request received with not citations selected. citationCollectionId: "
                                    + citationCollectionId);
                }

                return;
            }
            citationIds.addAll(Arrays.asList(paramCitationIds));

            fileName = rb.getFormattedMessage("export.filename.selected.ris", fileName);
        } else {
            // export all

            // iterate through ids
            List<Citation> citations = collection.getCitations();

            if (citations == null || citations.size() < 1) {
                // no citations to export - do not continue 
                try {
                    res.sendError(HttpServletResponse.SC_NO_CONTENT, rb.getString("export.empty_collection"));
                } catch (IOException e) {
                    m_log.warn(
                            "export-all request received for empty citation collection. citationCollectionId: "
                                    + citationCollectionId);
                }

                return;
            }

            for (Citation citation : citations) {
                citationIds.add(citation.getId());
            }
            fileName = rb.getFormattedMessage("export.filename.all.ris", fileName);
        }

        // We need to write to a temporary stream for better speed, plus
        // so we can get a byte count. Internet Explorer has problems
        // if we don't make the setContentLength() call.
        StringBuilder buffer = new StringBuilder(4096);
        // StringBuilder contentType = new StringBuilder();

        try {
            collection.exportRis(buffer, citationIds);
        } catch (IOException e) {
            throw new EntityAccessOverloadException(ref.getReference());
        }

        // Set the mime type for a RIS file
        res.addHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
        //res.addHeader("Content-Disposition", "attachment; filename=\"citations.RIS\"");
        res.setContentType("application/x-Research-Info-Systems");
        res.setContentLength(buffer.length());

        if (buffer.length() > 0) {
            // Increase the buffer size for more speed.
            res.setBufferSize(buffer.length());
        }

        OutputStream out = null;
        try {
            out = res.getOutputStream();
            if (buffer.length() > 0) {
                out.write(buffer.toString().getBytes());
            }
            out.flush();
            out.close();
        } catch (Throwable ignore) {
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Throwable ignore) {
                }
            }
        }

    }

}