List of usage examples for javax.servlet.http HttpSession setMaxInactiveInterval
public void setMaxInactiveInterval(int interval);
From source file:org.sakaiproject.tool.assessment.ui.servlet.delivery.LoginServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String alias = req.getParameter("id"); if ((alias == null) || ("").equals(alias)) { log.warn(// w w w .j a va2s. com "The published URL you have entered is incorrect. id is missing. Please check in Published Settings."); return; } HttpSession httpSession = req.getSession(true); httpSession.setMaxInactiveInterval(3600); // one hour PersonBean person = (PersonBean) ContextUtil.lookupBeanFromExternalServlet("person", req, res); // we are going to use the delivery bean to flag that this access is via url // this is the flag that we will use in deliverAssessment.jsp to decide what // button to display - daisyf DeliveryBean delivery = (DeliveryBean) ContextUtil.lookupBeanFromExternalServlet("delivery", req, res); // For SAK-7132. // As this class is only used for taking assessment via URL, // there should not be any assessment grading data at this point delivery.setAssessmentGrading(null); delivery.setActionString("takeAssessmentViaUrl"); // reset timer in case this is a timed assessment delivery.setTimeElapse("0"); delivery.setLastTimer(0); delivery.setTimeLimit("0"); delivery.setBeginAssessment(true); delivery.setNumberRetake(-1); delivery.setActualNumberRetake(-1); // set path delivery.setContextPath(req.getContextPath()); // 1. get publishedAssessment and check if anonymous is allowed // 2. If so, goto welcome.faces // 3. If not, goto login.faces // both pages will set agentId and then direct user to BeginAssessment PublishedAssessmentService service = new PublishedAssessmentService(); PublishedAssessmentFacade pub = service.getPublishedAssessmentIdByAlias(alias); if (pub == null) { log.warn("The published URL you have entered is incorrect. Please check in Published Settings."); return; } delivery.setAssessmentId(pub.getPublishedAssessmentId().toString()); delivery.setAssessmentTitle(pub.getTitle()); delivery.setHonorPledge(pub.getAssessmentMetaDataByLabel("honorpledge_isInstructorEditable") != null && pub .getAssessmentMetaDataByLabel("honorpledge_isInstructorEditable").toLowerCase().equals("true")); delivery.setPublishedAssessment(pub); BeginDeliveryActionListener listener = new BeginDeliveryActionListener(); listener.populateBeanFromPub(delivery, pub); RequestDispatcher dispatcher = null; String path = "/jsf/delivery/invalidAssessment.faces"; boolean relativePath = true; String agentIdString = ""; boolean isAuthorized = false; boolean isAuthenticated = false; // Determine if assessment accept Anonymous Users. If so, starting in version 2.0.1 // all users will be authenticated as anonymous for the assessment in this case. //boolean anonymousAllowed = false; String releaseTo = pub.getAssessmentAccessControl().getReleaseTo(); if (releaseTo != null && releaseTo.indexOf("Anonymous Users") > -1) { //anonymousAllowed = true; agentIdString = AgentFacade.createAnonymous(); isAuthenticated = true; isAuthorized = true; delivery.setAnonymousLogin(true); person.setAnonymousId(agentIdString); } else { // check membership agentIdString = req.getRemoteUser(); isAuthenticated = (agentIdString != null && !("").equals(agentIdString)); if (isAuthenticated) { if (releaseTo.indexOf(AssessmentAccessControl.RELEASE_TO_SELECTED_GROUPS) > -1) { isAuthorized = checkMembershipForGroupRelease(pub, req, res); } else { isAuthorized = checkMembership(pub, req, res); } // in 2.2, agentId is differnt from req.getRemoteUser() agentIdString = AgentFacade.getAgentString(); } } log.debug("*** agentIdString: " + agentIdString); String nextAction = delivery.checkFromViaUrlLogin(); log.debug("nextAction=" + nextAction); if (isAuthorized) { // Assessment has been permanently removed if ("isRemoved".equals(nextAction)) { path = "/jsf/delivery/isRemoved.faces"; } // Assessment is available for taking else if ("safeToProceed".equals(nextAction)) { // if assessment is available, set it in delivery bean for display in deliverAssessment.jsp listener.processAction(null); path = "/jsf/delivery/beginTakingAssessment_viaurl.faces"; } // Assessment is currently not available (eg., retracted for edit, due date has passed, submission limit has been reached, etc) else if ("assessmentNotAvailable".equals(nextAction)) { path = "/jsf/delivery/assessmentNotAvailable.faces"; } else if ("isRetracted".equals(nextAction)) { path = "/jsf/delivery/isRetracted.faces"; } else if ("isRetractedForEdit".equals(nextAction)) { path = "/jsf/delivery/isRetractedForEdit.faces"; } else if ("discrepancyInData".equals(nextAction)) { path = "/jsf/delivery/discrepancyInData.faces"; } else if ("assessmentHasBeenSubmitted".equals(nextAction)) { path = "/jsf/delivery/assessmentHasBeenSubmitted.faces"; } else if ("noSubmissionLeft".equals(nextAction)) { path = "/jsf/delivery/noSubmissionLeft.faces"; } else if ("noLateSubmission".equals(nextAction)) { path = "/jsf/delivery/noLateSubmission.faces"; } else if ("timeExpired".equals(nextAction)) { path = "/jsf/delivery/timeExpired.faces"; } else { path = "/jsf/delivery/assessmentNotAvailable.faces"; } } else { // notAuthorized if (!isAuthenticated) { relativePath = false; delivery.setActionString(null); path = "/authn/login?url=" + URLEncoder.encode(req.getRequestURL().toString() + "?id=" + alias, "UTF-8"); } else { //isAuthenticated but not authorized path = "/jsf/delivery/accessDenied.faces"; } } if ("true".equals(req.getParameter("fromDirect"))) { // send the user directly into taking the assessment... they already clicked start from the direct servlet if (delivery.getNavigation().trim() != null && "1".equals(delivery.getNavigation().trim())) { LinearAccessDeliveryActionListener linearDeliveryListener = new LinearAccessDeliveryActionListener(); linearDeliveryListener.processAction(null); } else { DeliveryActionListener deliveryListener = new DeliveryActionListener(); //This has to be setup if it's coming from direct otherwise it doesn't start right UIComponent uic = new UICommand(); uic.setId("beginAssessment"); ActionEvent ae = new ActionEvent(uic); deliveryListener.processAction(ae); } //TODO: Should be something a bit more robust as validate() can retun a lot of things... if ("takeAssessment".equals(delivery.validate())) { path = "/jsf/delivery/deliverAssessment.faces"; } } log.debug("***path" + path); if (relativePath) { dispatcher = req.getRequestDispatcher(path); dispatcher.forward(req, res); } else { log.info("** servlet path=" + req.getRequestURL().toString()); String url = req.getRequestURL().toString(); String context = req.getContextPath(); String finalUrl = url.substring(0, url.lastIndexOf(context)) + path; log.info("**** finalUrl = " + finalUrl); res.sendRedirect(finalUrl); } }
From source file:org.sakaiproject.tool.assessment.rsf.producers.BeginAssessmentProducer.java
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { BeginAssessmentViewParameters params = null; String alias = ""; if (viewparams != null) { params = (BeginAssessmentViewParameters) viewparams; alias = params.pubReference;/*from w ww. j a v a 2s . c om*/ } else { log.warn("Something bad... we have no viewparams"); return; } //Begin cut and past (with small deviations) from existing LoginServlet that currently does //the job of url aliased assessment delivery in Samigo, some of this could possibly be removed //unless this just replaces the LoginServlet someday. HttpSession httpSession = httpServletRequest.getSession(true); httpSession.setMaxInactiveInterval(3600); // one hour PersonBean person = (PersonBean) ContextUtil.lookupBeanFromExternalServlet("person", httpServletRequest, httpServletResponse); // we are going to use the delivery bean to flag that this access is via url // this is the flag that we will use in deliverAssessment.jsp to decide what // button to display - daisyf DeliveryBean delivery = (DeliveryBean) ContextUtil.lookupBeanFromExternalServlet("delivery", httpServletRequest, httpServletResponse); // For SAK-7132. // As this class is only used for taking assessment via URL, // there should not be any assessment grading data at this point delivery.setAssessmentGrading(null); delivery.setActionString("takeAssessmentViaUrl"); // reset timer in case this is a timed assessment delivery.setTimeElapse("0"); delivery.setLastTimer(0); delivery.setTimeLimit("0"); delivery.setBeginAssessment(true); delivery.setNumberRetake(-1); delivery.setActualNumberRetake(-1); // set path delivery.setContextPath(httpServletRequest.getContextPath()); // 1. get publishedAssessment and check if anonymous is allowed // 2. If so, goto welcome.faces // 3. If not, goto login.faces // both pages will set agentId and then direct user to BeginAssessment PublishedAssessmentService service = new PublishedAssessmentService(); PublishedAssessmentFacade pub = null; try { pub = service.getPublishedAssessment(alias); } catch (Exception e) { log.warn("Something bad... can't find publisehd assessment " + e); return; } delivery.setAssessmentId(pub.getPublishedAssessmentId().toString()); delivery.setAssessmentTitle(pub.getTitle()); delivery.setHonorPledge(pub.getAssessmentMetaDataByLabel("honorpledge_isInstructorEditable") != null && pub .getAssessmentMetaDataByLabel("honorpledge_isInstructorEditable").toLowerCase().equals("true")); delivery.setPublishedAssessment(pub); String path = null; String agentIdString = ""; boolean isAuthorized = false; boolean isAuthenticated = false; // Determine if assessment accept Anonymous Users. If so, starting in version 2.0.1 // all users will be authenticated as anonymous for the assessment in this case. //boolean anonymousAllowed = false; String releaseTo = pub.getAssessmentAccessControl().getReleaseTo(); if (releaseTo != null && releaseTo.indexOf("Anonymous Users") > -1) { //anonymousAllowed = true; agentIdString = AgentFacade.createAnonymous(); isAuthenticated = true; isAuthorized = true; delivery.setAnonymousLogin(true); person.setAnonymousId(agentIdString); } else { // check membership agentIdString = httpServletRequest.getRemoteUser(); isAuthenticated = (agentIdString != null && !("").equals(agentIdString)); if (isAuthenticated) { isAuthorized = checkMembership(pub); // in 2.2, agentId is differnt from httpServletRequest.getRemoteUser() agentIdString = AgentFacade.getAgentString(); } } log.debug("*** agentIdString: " + agentIdString); // check if assessment is available // We are getting the total no. of submission (for grade) per assessment // by the given agent at the same time boolean assessmentIsAvailable = assessmentIsAvailable(service, agentIdString, pub, delivery); if (isAuthorized) { if (!assessmentIsAvailable) { UIBranchContainer.make(tofill, "assessmentNotAvailable:"); // TODO added info on why } else { // if assessment is available, set it in delivery bean for display in deliverAssessment.jsp BeginDeliveryActionListener listener = new BeginDeliveryActionListener(); listener.processAction(null); UIForm form = UIForm.make(tofill, "takeAssessmentForm:"); String url = "/samigo-app/servlet/Login?id=" + pub.getAssessmentMetaDataByLabel(AssessmentMetaDataIfc.ALIAS) + "&fromDirect=true"; UICommand.make(form, "takeAssessment", messageLocator.getMessage("begin_assessment_"), null) .decorate(new UITooltipDecorator(messageLocator.getMessage("begin_assessment_"))) .decorate(new UIFreeAttributeDecorator("onclick", "window.location.href='" + url + "'")); //UILink.make(form, "takeAssessment", url); UIOutput.make(form, "assessmentTitle", delivery.getAssessmentTitle()); UIOutput.make(form, "courseName", delivery.getCourseName()); UIOutput.make(form, "creatorName", delivery.getCreatorName()); if (delivery.getHasTimeLimit()) { UIBranchContainer timeLimit = UIBranchContainer.make(form, "timeLimit:"); UIOutput.make(timeLimit, "timeLimit", delivery.getTimeLimit()); UIOutput.make(timeLimit, "timeLimitHour", delivery.getTimeLimit_hour() + ""); UIOutput.make(timeLimit, "timeLimitMin", delivery.getTimeLimit_minute() + ""); } else { UIBranchContainer noTimeLimit = UIBranchContainer.make(form, "noTimeLimit:"); UIOutput.make(noTimeLimit, "timeLimit", delivery.getTimeLimit()); } if (!delivery.getAnonymousLogin() && !delivery.getSettings().isUnlimitedAttempts()) { UIBranchContainer limited = UIBranchContainer.make(tofill, "limited:"); UIOutput.make(limited, "maxAttempts", delivery.getSettings().getMaxAttempts() + ""); UIOutput.make(limited, "remaining", delivery.getSubmissionsRemaining() + ""); } else if (!delivery.getAnonymousLogin() && delivery.getSettings().isUnlimitedAttempts()) { UIBranchContainer.make(tofill, "unlimited:"); } if (delivery.getDueDate() != null) { UIBranchContainer duedate = UIBranchContainer.make(tofill, "duedate:"); UIOutput.make(duedate, "duedate", delivery.getDueDateString()); } } } else { // notAuthorized if (!isAuthenticated) { delivery.setActionString(null); try { path = "/authn/login?url=" + URLEncoder .encode(httpServletRequest.getRequestURL().toString() + "?pubId=" + alias, "UTF-8"); } catch (UnsupportedEncodingException e) { log.error("Encoding not suppoorted, " + e.getMessage()); } log.info("** servlet path=" + httpServletRequest.getRequestURL().toString()); String url = httpServletRequest.getRequestURL().toString(); String context = httpServletRequest.getContextPath(); String finalUrl = url.substring(0, url.lastIndexOf(context)) + path; log.info("**** finalUrl = " + finalUrl); try { httpServletResponse.sendRedirect(finalUrl); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { //isAuthenticated but not authorized UIBranchContainer.make(tofill, "accessDenied:"); // TODO added info on why } } //End cut and paste from LoginServlet (with small deviations) }
From source file:telecom.sudparis.eu.paas.client.APIClient.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/* w ww.j av a2 s. com*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // use a session to save appName from manifest while creating // application and the different parameters selected in the form HttpSession session = request.getSession(true); // session timeout 20 minutes session.setMaxInactiveInterval(20 * 60); List items = null; // Parse the request try { // Check that we have a file upload request // boolean isMultipart = // ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); items = upload.parseRequest(request); } catch (FileUploadException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // the method name String method = null; // the method path String path = null; // the request body String body = null; // the file name String fileName = null; // the file Item FileItem file2upload = null; // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); if (name.equals("method")) method = item.getString(); else if (name.equals("path")) path = item.getString(); else if (name.equals("body")) body = item.getString(); else if (name.equals("apiLocation")) { apiLocation = item.getString(); // Format the api location apiLocation = apiLocation.trim(); } } else { try { fileName = item.getName(); file2upload = item; } catch (Exception e) { } } } if (!apiLocation.endsWith("/")) apiLocation = apiLocation + "/"; session.setAttribute("apiLocation", apiLocation); if (method == null || method.equals("") || path == null || path.equals("")) { request.setAttribute("status", 404); request.setAttribute("output", "Select an Action from the proposed list."); request.getRequestDispatcher("/index.jsp").forward(request, response); } else { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); client.setConnectTimeout(0); WebResource service = client.resource(getBaseURI()); // Get the type of the methods (i.e. GET, POST,...) String[] methodSplit = method.split("-"); method = methodSplit[0]; ClientResponse cr = null; if (method.equals("GET")) { cr = service.path(path).type(MediaType.APPLICATION_XML).get(ClientResponse.class); } else if (method.equals("POST")) { // the deploy is a particular case, since we have to upload the // deployable files if (path.contains("deploy") && !path.contains("undeploy")) { // the file to upload InputStream uploadedStream = null; uploadedStream = file2upload.getInputStream(); // String deployableName=(String) // session.getAttribute("deployableName"); if (uploadedStream == null) { request.setAttribute("status", 404); request.setAttribute("output", "The deployableName was not found! Possible cause: Application is not yet created."); request.getRequestDispatcher("/index.jsp").forward(request, response); } else { File f = null; if (!fileName.equals("") && !(fileName == null)) { // temp destination path fileName = localTempPath + '/' + fileName; // write the inputStream to a FileOutputStream f = new File(fileName); OutputStream out = new FileOutputStream(f); int read = 0; byte[] bytes = new byte[1024]; while ((read = uploadedStream.read(bytes)) != -1) { out.write(bytes, 0, read); } uploadedStream.close(); out.flush(); out.close(); } if (f == null) { f = new File(localTempPath + "/temp"); f.createNewFile(); FormDataMultiPart form = new FormDataMultiPart().field("file", f, MediaType.MULTIPART_FORM_DATA_TYPE); // form.bodyPart(new BodyPart()); cr = service.path(path).type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); } else { FormDataMultiPart form = new FormDataMultiPart().field("file", f, MediaType.MULTIPART_FORM_DATA_TYPE); // form.bodyPart(new BodyPart()); cr = service.path(path).type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); } } } // POST app is the creat app operation else if (path.equals("app")) { // parse the manifest to get the file location // String deployableName = getDeployableName(body); // session.setAttribute("deployableName", deployableName); cr = service.path(path).type(MediaType.APPLICATION_XML).entity(body).post(ClientResponse.class); } // other POST methods else cr = service.path(path).type(MediaType.APPLICATION_XML).entity(body).post(ClientResponse.class); } else if (method.equals("DELETE")) { cr = service.path(path).type(MediaType.APPLICATION_XML).delete(ClientResponse.class); } request.setAttribute("status", cr.getStatus()); if (cr.getStatus() == 200 || cr.getStatus() == 202)// if the // response will be an xml descriptor, format it request.setAttribute("output", prettyFormat(cr.getEntity(String.class), 2)); else request.setAttribute("output", cr.getEntity(String.class)); request.getRequestDispatcher("/index.jsp").forward(request, response); } }
From source file:MyServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); out.println("<html>"); out.println("<head>"); out.println("<title>Simple Session Tracker</title>"); out.println("</head>"); out.println("<body>"); out.println("<h2>Session Info</h2>"); out.println("session Id: " + session.getId() + "<br><br>"); out.println("The SESSION TIMEOUT period is " + session.getMaxInactiveInterval() + " seconds.<br><br>"); out.println("Now changing it to 20 minutes.<br><br>"); session.setMaxInactiveInterval(20 * 60); out.println("The SESSION TIMEOUT period is now " + session.getMaxInactiveInterval() + " seconds."); out.println("</body>"); out.println("</html>"); }
From source file:net.riezebos.thoth.servlets.ThothServlet.java
@Override public Identity getCurrentIdentity(HttpServletRequest request) { String ssoToken = request.getParameter(UserManager.SSO_TOKEN_NAME); if (ssoToken != null) { try {//from w w w.j a v a 2 s . c o m Identity identity = getThothEnvironment().getUserManager().getIdentityForToken(ssoToken); if (identity != null) { // We will start a new session here; but we mark it for a short life since this // is meant for a single render request only. HttpSession session = request.getSession(true); session.setAttribute(SESSION_USER_KEY, identity); session.setMaxInactiveInterval(30); return identity; } } catch (ContentManagerException e) { LOG.error(e.getMessage()); } } HttpSession session = request.getSession(false); Identity result = null; if (session != null) result = (Identity) session.getAttribute(SESSION_USER_KEY); if (result == null) result = getDefaultGroup(); return result; }
From source file:com.oic.net.Callback.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); String code = request.getParameter("code"); if (request.getParameter("code") == null) { //OAuth??code???? response.sendRedirect("/"); } else if (request.getParameter("register") != null) { //ID? session.setAttribute("alreadyId", true); return;/*www.j ava 2s . c o m*/ } if (session.isNew()) { session.setMaxInactiveInterval(300); } String email = ""; try { getToken(code); System.out.println(code); email = getEmailAddress(); } catch (Exception e) { e.printStackTrace(); } Pattern pattern = Pattern.compile("@oic.jp$"); Matcher matcher = pattern.matcher(email); if (matcher.find()) { Pattern numberPattern = Pattern.compile("^[a-zA-Z][0-9]{4}"); Matcher numberMatcher = numberPattern.matcher(email.toLowerCase()); if (!numberMatcher.find()) { response.getWriter().println("????????"); session.invalidate(); return; } String studentNumber = numberMatcher.group(); String key = DigestUtils.md5Hex(String.valueOf(new Date().getTime())); session.setAttribute("studentNumber", studentNumber); session.setAttribute("key", key); //md5?? registerData(studentNumber, key, session); response.sendRedirect("/"); } else { response.getWriter().println("????????"); session.invalidate(); } }
From source file:org.openmrs.module.cccgenerator.web.controller.CCCGeneratorFormController.java
@RequestMapping(value = "/module/cccgenerator/csvdownload") public void downloadCSV(HttpServletResponse response, HttpServletRequest request, @RequestParam(required = true, value = "sitelocationToDownload") String location, @RequestParam(required = true, value = "additionalNumbers") String additional) throws IOException { //get the location based on the location name Location cccLocation = Context.getLocationService().getLocation(location); //////////*from w ww.j ava 2 s. co m*/ //lengthen the session to make sure generation is complete HttpSession httpSession = request.getSession(); Integer httpSessionvalue = httpSession.getMaxInactiveInterval(); httpSession.setMaxInactiveInterval(-1); //create a temporary file that will be destroyed after completion File file = File.createTempFile(cccLocation.getName(), ".csv"); ///////find the patients to be added on the file LocationService locationService = Context.getLocationService(); PatientService patientService = Context.getPatientService(); // List<Location> siteLocation=locationService.getAllLocations(false); String glbccc = Context.getAdministrationService().getGlobalProperty("cccgenerator.CCC"); PatientIdentifierType patientIdentifier = patientService.getPatientIdentifierTypeByName(glbccc); //get all the location and related ones Set<Integer> setOfIdsLocsAndSubLocs = Context.getService(CCCGeneratorService.class) .getIdsOfLocationsParentAndChildren(cccLocation.getLocationId()); //log.info("This are all the locations and sub sites "+setOfIdsLocsAndSubLocs); //get patientIds based on patientIdentifiers and location //loop through all the locations as we pick all the patient ids Set<Integer> setOfPatientsWithIdentifierAndLocation = new HashSet<Integer>(); for (Integer j : setOfIdsLocsAndSubLocs) { Cohort listOfPatientsWithCCCandLocation = Context.getService(CCCGeneratorService.class) .getPatientByIdentifierAndLocation(patientIdentifier.getPatientIdentifierTypeId(), j); setOfPatientsWithIdentifierAndLocation.addAll(listOfPatientsWithCCCandLocation.getMemberIds()); } List<Patient> patientsFromSet = new ArrayList<Patient>(); //find all the patients using patient ids found for (Integer i : setOfPatientsWithIdentifierAndLocation) { patientsFromSet.add(Context.getPatientService().getPatient(i)); } Location l = Context.getLocationService().getLocation(location.trim()); Collections.sort(patientsFromSet, new SortCCC()); StringBuilder stringBuilderColumnsHeaders = new StringBuilder(); StringBuilder stringBuilderContents; StringBuilder additionalCCC; StringBuilder stringBuilderContentsAdditionals = new StringBuilder(); StringBuilder reportHeader = new StringBuilder(); reportHeader.append("\"" + l.getName() + "\"" + "," + "\"" + " and Other Related Sites" + "\"" + "," + "\"" + "CCC Number Registar" + "\"" + ","); stringBuilderColumnsHeaders.append("\"CCC Number\"").append(",").append("\"Names\"").append(",") .append("\"AMRS ID\"").append(",").append("\"D.O.B\"").append(","); FileWriter fstream = new FileWriter(file, true); BufferedWriter out = new BufferedWriter(fstream); out.write(reportHeader.toString() + "\n"); out.write(stringBuilderColumnsHeaders.toString() + "\n"); for (Patient p : patientsFromSet) { stringBuilderContents = new StringBuilder(); stringBuilderContents.append("\"" + p.getPatientIdentifier(patientIdentifier.getName()) + "\"") .append(",").append("\"" + namesFormated(p.getNames().toString()) + "\"").append(",") .append("\"" + p.getPatientIdentifier(getAMRSID(p)) + "\"").append(",") .append("\"" + formatDate(p.getBirthdate()) + "\"").append(","); out.write(stringBuilderContents.toString()); out.write("\n"); } //pick the last count of the ccc number location CCCGeneratorService service = Context.getService(CCCGeneratorService.class); CCCLocation ml = service.getCCCLocationByLocation(cccLocation); //we pick the unique number for every facility Integer CCC = ml.getCCC(); //using CCC above we check for the last count CCCCount mc = service.getCCCCountByCCC(CCC); Integer lastcount = mc.getLastCount(); Integer counttogetto = Integer.parseInt(additional) + lastcount; for (int h = lastcount; h < counttogetto; h++) { additionalCCC = new StringBuilder(); lastcount++; String lcount = lastcount.toString(); String cccNumber; if (lcount.length() < 5) { int x = 5 - lcount.length(); String y = ""; for (int k = 0; k < x; k++) y += "0"; lcount = y + lcount; } cccNumber = CCC + "-" + lcount; additionalCCC.append("\"" + cccNumber + "\"").append(",").append("\"" + "\"").append(",") .append("\"" + "\"").append(",").append("\"" + "\"").append(","); out.write(additionalCCC.toString()); out.write("\n"); } out.close(); ////////////////////////////////////////////////////////////////////// response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=" + file); response.setContentLength((int) file.length()); FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream()); file.delete(); httpSession.setMaxInactiveInterval(httpSessionvalue); }
From source file:net.naijatek.myalumni.modules.common.presentation.action.SecurityAction.java
private int setupSessionTimeout(HttpSession session) { int sessionTimeout = sysConfigService.getSessionTimeOut(); try {// www.ja v a 2 s .co m session.setMaxInactiveInterval(sessionTimeout); } catch (NumberFormatException nfe) { logger.fatal("Unable to parse session timeout information from system file."); sessionTimeout = 900; session.setMaxInactiveInterval(sessionTimeout); // default is 15 mins. 15*60 } return sessionTimeout; }
From source file:com.enonic.vertical.adminweb.AdminLogInServlet.java
private void handlerForgotPassword(HttpServletRequest request, HttpServletResponse response, ExtendedMap formItems) throws VerticalAdminException { final String uid = formItems.getString("uid", null); HttpSession session = request.getSession(true); if (uid == null || uid.length() == 0) { session.setAttribute("passworderrorcode", EC_400_MISSING_UID); session.setAttribute("passworderror", "No user id specified!"); session.setMaxInactiveInterval(SESSION_TIMEOUT_ERROR); redirectClientToAdminPath("forgotpassword", request, response); return;/*w w w.j a v a 2 s . com*/ } UserStoreKey userStoreKey = null; final String userStoreKeyStr = formItems.getString("userstorekey", null); if (userStoreKeyStr != null) { userStoreKey = new UserStoreKey(userStoreKeyStr); } final QualifiedUsername qualifiedUsername = new QualifiedUsername(userStoreKey, uid); final String password = PasswordGenerator.generateNewPassword(); try { securityService.changePassword(qualifiedUsername, password); } catch (Exception ex) { session.setAttribute("passworderrorcode", EC_401_ACCESS_DENIED); session.setAttribute("passworderror", ex.getMessage()); session.setMaxInactiveInterval(SESSION_TIMEOUT_ERROR); redirectClientToAdminPath("forgotpassword", request, response); } sendMailService.sendChangePasswordMail(qualifiedUsername, password); redirectClientToAdminPath("login", request, response); }