List of usage examples for javax.servlet.http HttpSession getServletContext
public ServletContext getServletContext();
From source file:uk.ac.bbsrc.tgac.miso.spring.ajax.PoolControllerHelperService.java
public JSONObject getPoolBarcode(HttpSession session, JSONObject json) { Long poolId = json.getLong("poolId"); File temploc = new File(session.getServletContext().getRealPath("/") + "temp/"); try {/*from www . j av a 2 s . c om*/ Pool pool = requestManager.getPoolById(poolId); barcodeFactory.setPointPixels(1.5f); barcodeFactory.setBitmapResolution(600); RenderedImage bi = null; if (json.has("barcodeGenerator")) { BarcodeDimension dim = new BarcodeDimension(100, 100); if (json.has("dimensionWidth") && json.has("dimensionHeight")) { dim = new BarcodeDimension(json.getDouble("dimensionWidth"), json.getDouble("dimensionHeight")); } BarcodeGenerator bg = BarcodeFactory.lookupGenerator(json.getString("barcodeGenerator")); if (bg != null) { bi = barcodeFactory.generateBarcode(pool, bg, dim); } else { return JSONUtils.SimpleJSONError( "'" + json.getString("barcodeGenerator") + "' is not a valid barcode generator type"); } } else { bi = barcodeFactory.generateSquareDataMatrix(pool, 400); } if (bi != null) { File tempimage = misoFileManager.generateTemporaryFile("barcode-", ".png", temploc); if (ImageIO.write(bi, "png", tempimage)) { return JSONUtils.JSONObjectResponse("img", tempimage.getName()); } return JSONUtils.SimpleJSONError("Writing temp image file failed."); } else { return JSONUtils.SimpleJSONError("Pool has no parseable barcode"); } } catch (IOException e) { e.printStackTrace(); return JSONUtils .SimpleJSONError(e.getMessage() + ": Cannot seem to access " + temploc.getAbsolutePath()); } }
From source file:org.intermine.web.struts.ReportController.java
/** * {@inheritDoc}/* w w w . ja v a2 s .c om*/ */ @SuppressWarnings("unused") @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { long startTime = System.currentTimeMillis(); HttpSession session = request.getSession(); InterMineAPI im = SessionMethods.getInterMineAPI(session); if (im.getBagManager().isAnyBagToUpgrade(SessionMethods.getProfile(session))) { recordError(new ActionMessage("login.upgradeListManually"), request); } // fetch & set requested object InterMineObject requestedObject = getRequestedObject(im, request); if (requestedObject != null) { ReportObjectFactory reportObjectFactory = SessionMethods.getReportObjects(session); ReportObject reportObject = reportObjectFactory.get(requestedObject); request.setAttribute("object", reportObject); request.setAttribute("reportObject", reportObject); request.setAttribute("requestedObject", requestedObject); // hell starts here TagManager tm = im.getTagManager(); ServletContext servletContext = session.getServletContext(); ObjectStore os = im.getObjectStore(); String superuser = im.getProfileManager().getSuperuser(); if (superuser.equals(SessionMethods.getProfile(session).getUsername())) { request.setAttribute("SHOW_TAGS", true); } // place InlineLists based on TagManager, reportObject is cached while Controller is not Map<String, List<InlineList>> placedInlineLists = new TreeMap<String, List<InlineList>>(); // traverse all unplaced (non-header) InlineLists for (InlineList list : reportObject.getNormalInlineLists()) { FieldDescriptor fd = list.getDescriptor(); String taggedType = getTaggedType(fd); // assign lists to any aspects they are tagged to or put in unplaced lists String fieldPath = fd.getClassDescriptor().getUnqualifiedName() + "." + fd.getName(); for (String tagName : tm.getObjectTagNames(fieldPath, taggedType, superuser)) { if (AspectTagUtil.isAspectTag(tagName)) { List<InlineList> listsForAspect = placedInlineLists.get(tagName); if (listsForAspect == null) { listsForAspect = new ArrayList<InlineList>(); placedInlineLists.put(tagName, listsForAspect); } listsForAspect.add(list); } else if (TagNames.IM_SUMMARY.equals(tagName)) { List<InlineList> summaryLists = placedInlineLists.get(tagName); if (summaryLists == null) { summaryLists = new ArrayList<InlineList>(); placedInlineLists.put(tagName, summaryLists); } summaryLists.add(list); } } } // any lists that aren't tagged will be 'unplaced' List<InlineList> unplacedInlineLists = new ArrayList<InlineList>(reportObject.getNormalInlineLists()); unplacedInlineLists.removeAll(placedInlineLists.values()); long now = System.currentTimeMillis(); LOG.info("TIME placed inline lists: " + (now - startTime) + "ms"); long stepTime = now; request.setAttribute("mapOfInlineLists", placedInlineLists); request.setAttribute("listOfUnplacedInlineLists", unplacedInlineLists); Map<String, Map<String, DisplayField>> placementRefsAndCollections = new TreeMap<String, Map<String, DisplayField>>(); Set<String> aspects = new LinkedHashSet<String>(SessionMethods.getCategories(servletContext)); Set<ClassDescriptor> cds = os.getModel().getClassDescriptorsForClass(requestedObject.getClass()); for (String aspect : aspects) { placementRefsAndCollections.put(TagNames.IM_ASPECT_PREFIX + aspect, new TreeMap<String, DisplayField>(String.CASE_INSENSITIVE_ORDER)); } Map<String, DisplayField> miscRefs = new TreeMap<String, DisplayField>( reportObject.getRefsAndCollections()); placementRefsAndCollections.put(TagNames.IM_ASPECT_MISC, miscRefs); // summary refs and colls Map<String, DisplayField> summaryRefsCols = new TreeMap<String, DisplayField>(); placementRefsAndCollections.put(TagNames.IM_SUMMARY, summaryRefsCols); for (Iterator<Entry<String, DisplayField>> iter = reportObject.getRefsAndCollections().entrySet() .iterator(); iter.hasNext();) { Map.Entry<String, DisplayField> entry = iter.next(); DisplayField df = entry.getValue(); if (df instanceof DisplayReference) { categoriseBasedOnTags(((DisplayReference) df).getDescriptor(), "reference", df, miscRefs, tm, superuser, placementRefsAndCollections, SessionMethods.isSuperUser(session)); } else if (df instanceof DisplayCollection) { categoriseBasedOnTags(((DisplayCollection) df).getDescriptor(), "collection", df, miscRefs, tm, superuser, placementRefsAndCollections, SessionMethods.isSuperUser(session)); } } // remove any fields overridden by displayers removeFieldsReplacedByReportDisplayers(reportObject, placementRefsAndCollections); request.setAttribute("placementRefsAndCollections", placementRefsAndCollections); String type = reportObject.getType(); request.setAttribute("objectType", type); String stableLink = PortalHelper.generatePortalLink(reportObject.getObject(), im, request); if (stableLink != null) { request.setAttribute("stableLink", stableLink); } stepTime = System.currentTimeMillis(); startTime = stepTime; // attach only non empty categories Set<String> allClasses = new HashSet<String>(); for (ClassDescriptor cld : cds) { allClasses.add(cld.getUnqualifiedName()); } TemplateManager templateManager = im.getTemplateManager(); Map<String, List<ReportDisplayer>> displayerMap = reportObject.getReportDisplayers(); stepTime = System.currentTimeMillis(); startTime = stepTime; List<String> categories = new LinkedList<String>(); for (String aspect : aspects) { // 1) Displayers // 2) Inline Lists if ((displayerMap != null && displayerMap.containsKey(aspect)) || placedInlineLists.containsKey(aspect)) { categories.add(aspect); } else { // 3) Templates if (!templateManager.getReportPageTemplatesForAspect(aspect, allClasses).isEmpty()) { categories.add(aspect); } else { // 4) References & Collections if (placementRefsAndCollections.containsKey("im:aspect:" + aspect) && placementRefsAndCollections.get("im:aspect:" + aspect) != null) { for (DisplayField df : placementRefsAndCollections.get("im:aspect:" + aspect) .values()) { categories.add(aspect); break; } } } } } if (!categories.isEmpty()) { request.setAttribute("categories", categories); } now = System.currentTimeMillis(); LOG.info("TIME made list of categories: " + (now - stepTime) + "ms"); } return null; }
From source file:net.ontopia.topicmaps.classify.WebChew.java
public void processForm() { HttpSession session = request.getSession(true); String tmckey = getClassificationKey(); // reclassify if (request.getParameter("reclassify") != null) { session.removeAttribute(tmckey); }// w ww. j a v a 2 s. c o m // black list selected terms String blacklisted = request.getParameter("blacklisted"); if (blacklisted != null && blacklisted.length() > 0) { BlackList bl = getBlackList(); bl.addStopWord(blacklisted); bl.save(); } // remove selected association String removeAssociation = request.getParameter("removeAssociation"); if (removeAssociation != null) { // process form data try { TopicMapStoreIF store = NavigatorUtils.getTopicMapRepository(session.getServletContext()) .getReferenceByKey(request.getParameter("tm")).createStore(false); try { TopicMapIF topicmap = store.getTopicMap(); AssociationIF assoc = (AssociationIF) topicmap.getObjectById(removeAssociation); if (assoc != null) assoc.remove(); store.commit(); } finally { store.close(); } } catch (Exception e) { throw new OntopiaRuntimeException(e); } } String[] selected = request.getParameterValues("selected"); if (request.getParameter("ok") != null || request.getParameter("cancel") != null) { try { // if ok pressed process form if (request.getParameter("ok") != null) { // create associations; look up existing classified document in session TopicMapClassification tmc = (TopicMapClassification) session.getAttribute(tmckey); if (tmc == null) return; // process form data TopicMapStoreIF store = NavigatorUtils.getTopicMapRepository(session.getServletContext()) .getReferenceByKey(request.getParameter("tm")).createStore(false); try { TopicMapIF topicmap = store.getTopicMap(); TopicMapBuilderIF builder = topicmap.getBuilder(); // get document topic TopicIF dtopic = (TopicIF) topicmap.getObjectById(request.getParameter("id")); if (selected != null && selected.length > 0) { for (int i = 0; i < selected.length; i++) { String termid = selected[i]; String at = request.getParameter("at-" + termid); if (at == null || "-".equals(at)) continue; String cn = request.getParameter("cn-" + termid); String ct = request.getParameter("ct-" + termid); if (ct == null || "-".equals(ct)) continue; // create new candidate topic TopicIF ctopic; if (ct.startsWith("new:")) { String ctoid = ct.substring("new:".length()); TopicIF ctype = (TopicIF) topicmap.getObjectById(ctoid); if (ctype == null) throw new OntopiaRuntimeException( "Cannot find topic type: " + ct + " " + ctoid); ctopic = builder.makeTopic(ctype); builder.makeTopicName(ctopic, cn); } else if ("-".equals(ct)) { continue; // ignore } else { ctopic = (TopicIF) topicmap.getObjectById(ct); } // create association String[] at_data = StringUtils.split(at, ":"); if (at_data.length != 3) continue; TopicIF atype = (TopicIF) topicmap.getObjectById(at_data[0]); if (atype == null) throw new OntopiaRuntimeException("Cannot find association type: " + at); TopicIF drtype = (TopicIF) topicmap.getObjectById(at_data[1]); if (drtype == null) throw new OntopiaRuntimeException( "Cannot find document roletype: " + at_data[1]); TopicIF crtype = (TopicIF) topicmap.getObjectById(at_data[2]); if (crtype == null) throw new OntopiaRuntimeException( "Cannot find concept roletype: " + at_data[2]); AssociationIF assoc = builder.makeAssociation(atype); builder.makeAssociationRole(assoc, drtype, dtopic); builder.makeAssociationRole(assoc, crtype, ctopic); } // remove duplicate associations DuplicateSuppressionUtils.removeDuplicateAssociations(dtopic); store.commit(); } } finally { store.close(); } } // clear classication session.removeAttribute(tmckey); // redirect back to instance page response.sendRedirect(redirectURI); } catch (Exception e) { throw new OntopiaRuntimeException(e); } } }
From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ArtifactProtocolServiceTest.java
@Test public void testHandleReturnResponse() throws Exception { // setup/*from w w w . j ava2 s .c o m*/ SAML2ProtocolServiceAuthIdent saml2ProtocolService = new SAML2ProtocolServiceAuthIdent(); String userId = UUID.randomUUID().toString(); String givenName = "test-given-name"; String surName = "test-sur-name"; Identity identity = new Identity(); identity.name = surName; identity.firstName = givenName; identity.gender = Gender.MALE; identity.dateOfBirth = new GregorianCalendar(); identity.nationality = "BELG"; identity.placeOfBirth = "Gent"; HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class); HttpServletRequest mockHttpServletRequest = EasyMock.createMock(HttpServletRequest.class); HttpServletResponse mockHttpServletResponse = EasyMock.createMock(HttpServletResponse.class); ServletContext mockServletContext = EasyMock.createMock(ServletContext.class); KeyPair keyPair = generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=Test", notBefore, notAfter); IdPIdentity idpIdentity = new IdPIdentity("test", new KeyStore.PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] { certificate })); IdentityProviderConfiguration mockConfiguration = EasyMock.createMock(IdentityProviderConfiguration.class); // expectations mockServletContext.setAttribute(AbstractSAML2ProtocolService.IDP_CONFIG_CONTEXT_ATTRIBUTE, mockConfiguration); EasyMock.expect(mockHttpSession.getServletContext()).andReturn(mockServletContext).times(3); EasyMock.expect(mockServletContext.getAttribute(AbstractSAML2ProtocolService.IDP_CONFIG_CONTEXT_ATTRIBUTE)) .andReturn(mockConfiguration).times(3); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.TARGET_URL_SESSION_ATTRIBUTE)) .andStubReturn("http://127.0.0.1"); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.RELAY_STATE_SESSION_ATTRIBUTE)) .andStubReturn("relay-state"); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.IN_RESPONSE_TO_SESSION_ATTRIBUTE)) .andStubReturn("a77a1c87-e590-47d7-a3e0-afea455ebc01"); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.ISSUER_SESSION_ATTRIBUTE)) .andStubReturn("Issuer"); EasyMock.expect(mockConfiguration.getResponseTokenValidity()).andStubReturn(5); EasyMock.expect(mockConfiguration.findIdentity()).andStubReturn(idpIdentity); EasyMock.expect(mockConfiguration.getIdentityCertificateChain()) .andStubReturn(Collections.singletonList(certificate)); EasyMock.expect(mockConfiguration.getDefaultIssuer()).andStubReturn("TestIssuer"); EasyMock.expect(mockHttpServletRequest.getSession()).andReturn(mockHttpSession).times(3); EasyMock.expect( mockServletContext.getAttribute(AbstractSAML2ArtifactProtocolService.ARTIFACT_MAP_ATTRIBUTE)) .andReturn(null); mockServletContext.setAttribute( EasyMock.matches(AbstractSAML2ArtifactProtocolService.ARTIFACT_MAP_ATTRIBUTE), EasyMock.anyObject()); EasyMock.expect(mockHttpServletRequest.getServerName()).andReturn("127.0.0.1").times(2); EasyMock.expect(mockHttpServletRequest.getServerPort()).andReturn(8443).times(3); EasyMock.expect(mockHttpServletRequest.getContextPath()).andReturn("/eid-idp").times(2); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ArtifactProtocolService.ISSUER_SESSION_ATTRIBUTE)) .andReturn("SPIssuer"); // prepare EasyMock.replay(mockHttpServletRequest, mockHttpSession, mockServletContext, mockConfiguration); // operate saml2ProtocolService.init(mockServletContext, mockConfiguration); ReturnResponse returnResponse = saml2ProtocolService.handleReturnResponse(mockHttpSession, userId, new HashMap<String, Attribute>(), null, null, null, mockHttpServletRequest, mockHttpServletResponse); // verify EasyMock.verify(mockHttpServletRequest, mockHttpSession, mockServletContext, mockConfiguration); assertNotNull(returnResponse); assertEquals("http://127.0.0.1", returnResponse.getActionUrl()); List<NameValuePair> attributes = returnResponse.getAttributes(); assertNotNull(attributes); NameValuePair relayStateAttribute = null; NameValuePair samlArtAttribute = null; for (NameValuePair attribute : attributes) { if ("RelayState".equals(attribute.getName())) { relayStateAttribute = attribute; continue; } if ("SAMLart".equals(attribute.getName())) { samlArtAttribute = attribute; continue; } } assertNotNull(relayStateAttribute); assertEquals("relay-state", relayStateAttribute.getValue()); assertNotNull("no SAMLArt attribute", samlArtAttribute); String encodedSamlArt = samlArtAttribute.getValue(); assertNotNull(encodedSamlArt); String samlArtifact = new String(Base64.decodeBase64(encodedSamlArt)); LOG.debug("SAML Artifact: " + samlArtifact); }
From source file:edu.stanford.muse.webapp.JSPHelper.java
public static void writeFileToResponse(HttpSession session, HttpServletResponse response, String filePath, boolean asAttachment) throws IOException { // Decode the file name (might contain spaces and on) and prepare file object. File file = new File(filePath); // Check if file actually exists in filesystem. if (!file.exists()) { log.warn("Returing 404, serveFile can't find file: " + filePath); // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. return;//from w w w . jav a2s . com } // Get content type by filename. String contentType = session.getServletContext().getMimeType(file.getName()); // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // Init servlet response. int DEFAULT_BUFFER_SIZE = 100000; response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setContentType(contentType); // not really sure why this is needed, but we have to ensure that these headers are not present when rendering e.g. xwordImage (directly rendered into web browser, instead of piclens) if (asAttachment) { response.setHeader("Content-Length", String.valueOf(file.length())); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } // Prepare streams. BufferedInputStream input = null; BufferedOutputStream output = null; try { // Open streams. input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE); output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE); // Write file contents to response. byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } } finally { // Gently close streams. Util.close(output); Util.close(input); } }
From source file:org.intermine.web.struts.ImportTagsAction.java
/** * Import user's tags./*from ww w . ja v a 2 s . co 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 an ActionForward object defining where control goes next * * @exception Exception if the application business logic throws * an exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { ImportTagsForm f = (ImportTagsForm) form; HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); Profile profile = SessionMethods.getProfile(session); ProfileManager pm = im.getProfileManager(); if (f.isOverwriting()) { TagManager tm = im.getTagManager(); tm.deleteTags(null, null, null, profile.getUsername()); } StringReader reader = new StringReader(f.getXml()); int count = 0; if (!StringUtils.isEmpty(f.getXml())) { try { count = new TagBinding().unmarshal(pm, profile.getUsername(), reader); } catch (Exception ex) { SessionMethods.recordError("Problems importing tags. Please check the XML structure.", session); return mapping.findForward("importTag"); } } recordMessage(new ActionMessage("history.importedTags", new Integer(count)), request); // We can't know what the tags were, or indeed what exactly what // was tagged, and thus be more fine grained about // this notification. if (count > 0) { ChangeEvent e = new MassTaggingEvent(); profile.getSearchRepository().receiveEvent(e); if (SessionMethods.isSuperUser(session)) { SessionMethods.getGlobalSearchRepository(session.getServletContext()).receiveEvent(e); } } f.reset(); return mapping.findForward("success"); }
From source file:org.opencron.server.controller.HomeController.java
@RequestMapping("/headpic/upload") public void upload(@RequestParam(value = "file", required = false) MultipartFile file, Long userId, Map data, HttpServletRequest request, HttpSession httpSession, HttpServletResponse response) throws Exception { String extensionName = null;//from w ww . j av a2 s.c om if (file != null) { extensionName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); extensionName = extensionName.replaceAll("\\?\\d+$", ""); } String successFormat = "{\"result\":\"%s\",\"state\":200}"; String errorFormat = "{\"message\":\"%s\",\"state\":500}"; Cropper cropper = JSON.parseObject((String) data.get("data"), Cropper.class); //? if (!".BMP,.JPG,.JPEG,.PNG,.GIF".contains(extensionName.toUpperCase())) { WebUtils.writeJson(response, String.format(errorFormat, "?,(bmp,jpg,jpeg,png,gif)?")); return; } User user = userService.getUserById(userId); if (user == null) { WebUtils.writeJson(response, String.format(errorFormat, "??")); return; } String path = httpSession.getServletContext().getRealPath("/") + "upload" + File.separator; String picName = user.getUserId() + extensionName.toLowerCase(); File picFile = new File(path, picName); if (!picFile.exists()) { picFile.mkdirs(); } try { file.transferTo(picFile); //? Image image = ImageIO.read(picFile); if (image == null) { WebUtils.writeJson(response, String.format(errorFormat, "?,")); picFile.delete(); return; } //? if (picFile.length() / 1024 / 1024 > 5) { WebUtils.writeJson(response, String.format(errorFormat, ",??5M")); picFile.delete(); return; } //? ImageUtils.instance(picFile).rotate(cropper.getRotate()) .clip(cropper.getX(), cropper.getY(), cropper.getWidth(), cropper.getHeight()).build(); //?..... userService.uploadimg(picFile, userId); userService.updateUser(user); String contextPath = WebUtils.getWebUrlPath(request); String imgPath = contextPath + "/upload/" + picName + "?" + System.currentTimeMillis(); user.setHeaderPath(imgPath); user.setHeaderpic(null); httpSession.setAttribute(OpencronTools.LOGIN_USER, user); WebUtils.writeJson(response, String.format(successFormat, imgPath)); logger.info(" upload file successful @ " + picName); } catch (Exception e) { e.printStackTrace(); logger.info("upload exception:" + e.getMessage()); } }
From source file:org.oscarehr.caseload.CaseloadContentAction.java
private JSONArray generateCaseloadDataForDemographics(HttpServletRequest request, HttpServletResponse response, String caseloadProv, List<Integer> demoSearchResult) { JSONArray entry;/* ww w .ja v a2 s. com*/ String buttons; JSONArray data = new JSONArray(); if (demoSearchResult == null || demoSearchResult.size() < 1) return data; CaseloadDao caseloadDao = (CaseloadDao) SpringUtils.getBean("caseloadDao"); HttpSession session = request.getSession(); WebApplicationContext webApplicationContext = WebApplicationContextUtils .getRequiredWebApplicationContext(session.getServletContext()); String roleName$ = (String) session.getAttribute("userrole") + "," + (String) session.getAttribute("user"); String curUser_no = (String) session.getAttribute("user"); String userfirstname = (String) session.getAttribute("userfirstname"); String userlastname = (String) session.getAttribute("userlastname"); GregorianCalendar cal = new GregorianCalendar(); int curYear = cal.get(Calendar.YEAR); int curMonth = (cal.get(Calendar.MONTH) + 1); int curDay = cal.get(Calendar.DAY_OF_MONTH); int year = Integer.parseInt(request.getParameter("year")); int month = Integer.parseInt(request.getParameter("month")); int day = Integer.parseInt(request.getParameter("day")); java.util.Date apptime = new java.util.Date(); OscarProperties oscarProperties = OscarProperties.getInstance(); boolean bShortcutForm = oscarProperties.getProperty("appt_formview", "").equalsIgnoreCase("on") ? true : false; String formName = bShortcutForm ? oscarProperties.getProperty("appt_formview_name") : ""; String formNameShort = formName.length() > 3 ? (formName.substring(0, 2) + ".") : formName; String formName2 = bShortcutForm ? oscarProperties.getProperty("appt_formview_name2", "") : ""; String formName2Short = formName2.length() > 3 ? (formName2.substring(0, 2) + ".") : formName2; boolean bShortcutForm2 = bShortcutForm && !formName2.equals(""); boolean bShortcutIntakeForm = oscarProperties.getProperty("appt_intake_form", "").equalsIgnoreCase("on") ? true : false; String monthDay = String.format("%02d", month) + "-" + String.format("%02d", day); String prov = oscarProperties.getProperty("billregion", "").trim().toUpperCase(); for (Integer result : demoSearchResult) { if (result == null) continue; String demographic_no = result.toString(); entry = new JSONArray(); // name String demographicQuery = "cl_demographic_query"; String[] demographicParam = new String[1]; demographicParam[0] = demographic_no; List<Map<String, Object>> demographicResult = caseloadDao.getCaseloadDemographicData(demographicQuery, demographicParam); String clLastName = demographicResult.get(0).get("last_name").toString(); String clFirstName = demographicResult.get(0).get("first_name").toString(); String clFullName = StringEscapeUtils.escapeJavaScript(clLastName + ", " + clFirstName).toUpperCase(); entry.add(clFullName); // add E button to string buttons = ""; if (hasPrivilege("_eChart", roleName$)) { String encType = ""; try { encType = URLEncoder.encode("face to face encounter with client", "UTF-8"); } catch (UnsupportedEncodingException e) { MiscUtils.getLogger().error("Couldn't encode string", e); } String eURL = "../oscarEncounter/IncomingEncounter.do?providerNo=" + curUser_no + "&appointmentNo=0&demographicNo=" + demographic_no + "&curProviderNo=" + caseloadProv + "&reason=&encType=" + encType + "&userName=" + URLEncoder.encode(userfirstname + " " + userlastname) + "&curDate=" + curYear + "-" + curMonth + "-" + curDay + "&appointmentDate=" + year + "-" + month + "-" + day + "&startTime=" + apptime.getHours() + ":" + apptime.getMinutes() + "&status=T" + "&apptProvider_no=" + caseloadProv + "&providerview=" + caseloadProv; buttons += "<a href='#' onClick=\"popupPage(710, 1024,'../oscarSurveillance/CheckSurveillance.do?demographicNo=" + demographic_no + "&proceed=" + URLEncoder.encode(eURL) + "');return false;\" title='Encounter'>E</a> "; } // add form links to string if (hasPrivilege("_billing", roleName$)) { buttons += bShortcutForm ? "| <a href=# onClick='popupPage2( \"../form/forwardshortcutname.jsp?formname=" + formName + "&demographic_no=" + demographic_no + "\")' title='form'>" + formNameShort + "</a> " : ""; buttons += bShortcutForm2 ? "| <a href=# onClick='popupPage2( \"../form/forwardshortcutname.jsp?formname=" + formName2 + "&demographic_no=" + demographic_no + "\")' title='form'>" + formName2Short + "</a> " : ""; buttons += (bShortcutIntakeForm) ? "| <a href='#' onClick='popupPage(700, 1024, \"formIntake.jsp?demographic_no=" + demographic_no + "\")'>In</a> " : ""; } // add B button to string if (hasPrivilege("_billing", roleName$)) { buttons += "| <a href='#' onClick=\"popupPage(700,1000,'../billing.do?skipReload=true&billRegion=" + URLEncoder.encode(prov) + "&billForm=" + URLEncoder.encode(oscarProperties.getProperty("default_view")) + "&hotclick=&appointment_no=0&demographic_name=" + URLEncoder.encode(clLastName) + "%2C" + URLEncoder.encode(clFirstName) + "&demographic_no=" + demographic_no + "&providerview=1&user_no=" + curUser_no + "&apptProvider_no=none&appointment_date=" + year + "-" + month + "-" + day + "&start_time=0:00&bNewForm=1&status=t');return false;\" title='Billing'>B</a> "; buttons += "| <a href='#' onClick=\"popupPage(700,1000,'../billing/CA/ON/billinghistory.jsp?demographic_no=" + demographic_no + "&last_name=" + URLEncoder.encode(clLastName) + "&first_name=" + URLEncoder.encode(clFirstName) + "&orderby=appointment_date&displaymode=appt_history&dboperation=appt_history&limit1=0&limit2=10');return false;\" title='Billing'>BHx</a> "; } // add M button to string if (hasPrivilege("_masterLink", roleName$)) { buttons += "| <a href='#' onClick=\"popupPage(700,1000,'../demographic/demographiccontrol.jsp?demographic_no=" + demographic_no + "&displaymode=edit&dboperation=search_detail');return false;\" title='Master File'>M</a> "; } // add Rx button to string if (isModuleLoaded(request, "TORONTO_RFQ", true) && hasPrivilege("_appointment.doctorLink", roleName$)) { buttons += "| <a href='#' onClick=\"popupOscarRx(700,1027,'../oscarRx/choosePatient.do?providerNo=" + curUser_no + "&demographicNo=" + demographic_no + "');return false;\">Rx</a> "; } // add Tickler button to string buttons += "| <a href='#' onclick=\"popupPage('700', '1000', '../tickler/ticklerAdd.jsp?name=" + URLEncoder.encode(clLastName) + "%2C" + URLEncoder.encode(clFirstName) + "&chart_no=&bFirstDisp=false&demographic_no=" + demographic_no + "&messageID=null&doctor_no=" + curUser_no + "'); return false;\">T</a> "; // add Msg button to string buttons += "| <a href='#' onclick=\"popupPage('700', '1000', '../oscarMessenger/SendDemoMessage.do?demographic_no=" + demographic_no + "'); return false;\">Msg</a> "; entry.add(buttons); // age String clAge = demographicResult.get(0).get("age") != null ? demographicResult.get(0).get("age").toString() : ""; String clBDay = demographicResult.get(0).get("month_of_birth").toString() + "-" + demographicResult.get(0).get("date_of_birth").toString(); if (isBirthday(monthDay, clBDay)) { clAge += " <img src='../images/cake.gif' height='20' />"; } entry.add(clAge); // sex String clSex = demographicResult.get(0).get("sex").toString(); entry.add(clSex); // last appt String lapptQuery = "cl_last_appt"; List<Map<String, Object>> lapptResult = caseloadDao.getCaseloadDemographicData(lapptQuery, demographicParam); if ((!lapptResult.isEmpty()) && lapptResult.get(0).get("max(appointment_date)") != null && !lapptResult.get(0).get("max(appointment_date)").toString().equals("")) { String clLappt = lapptResult.get(0).get("max(appointment_date)").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../demographic/demographiccontrol.jsp?demographic_no=" + demographic_no + "&last_name=" + URLEncoder.encode(clLastName) + "&first_name=" + URLEncoder.encode(clFirstName) + "&orderby=appttime&displaymode=appt_history&dboperation=appt_history&limit1=0&limit2=25'); return false;\">" + clLappt + "</a>"); } else { entry.add(" "); } // next appt String napptQuery = "cl_next_appt"; List<Map<String, Object>> napptResult = caseloadDao.getCaseloadDemographicData(napptQuery, demographicParam); if (!napptResult.isEmpty() && napptResult.get(0).get("min(appointment_date)") != null && !napptResult.get(0).get("min(appointment_date)").toString().equals("")) { String clNappt = napptResult.get(0).get("min(appointment_date)").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../demographic/demographiccontrol.jsp?demographic_no=" + demographic_no + "&last_name=" + URLEncoder.encode(clLastName) + "&first_name=" + URLEncoder.encode(clFirstName) + "&orderby=appttime&displaymode=appt_history&dboperation=appt_history&limit1=0&limit2=25'); return false;\">" + clNappt + "</a>"); } else { entry.add(" "); } // num appts in last year String numApptsQuery = "cl_num_appts"; List<Map<String, Object>> numApptsResult = caseloadDao.getCaseloadDemographicData(numApptsQuery, demographicParam); if (!numApptsResult.isEmpty() && numApptsResult.get(0).get("count(*)") != null && !numApptsResult.get(0).get("count(*)").toString().equals("") && !numApptsResult.get(0).get("count(*)").toString().equals("0")) { String clNumAppts = numApptsResult.get(0).get("count(*)").toString(); entry.add(clNumAppts); } else { entry.add(" "); } // new labs String[] userDemoParam = new String[2]; userDemoParam[0] = curUser_no; userDemoParam[1] = demographic_no; String newLabQuery = "cl_new_labs"; List<Map<String, Object>> newLabResult = caseloadDao.getCaseloadDemographicData(newLabQuery, userDemoParam); if (!newLabResult.isEmpty() && newLabResult.get(0).get("count(*)") != null && !newLabResult.get(0).get("count(*)").toString().equals("") && !newLabResult.get(0).get("count(*)").toString().equals("0")) { String clNewLab = newLabResult.get(0).get("count(*)").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../dms/inboxManage.do?method=prepareForIndexPage&providerNo=" + curUser_no + "&selectedCategory=CATEGORY_PATIENT_SUB&selectedCategoryPatient=" + demographic_no + "&selectedCategoryType=CATEGORY_TYPE_HL7'); return false;\">" + clNewLab + "</a>"); } else { entry.add(" "); } // new docs String newDocQuery = "cl_new_docs"; List<Map<String, Object>> newDocResult = caseloadDao.getCaseloadDemographicData(newDocQuery, userDemoParam); if (!newDocResult.isEmpty() && newDocResult.get(0).get("count(*)") != null && !newDocResult.get(0).get("count(*)").toString().equals("") && !newDocResult.get(0).get("count(*)").toString().equals("0")) { String clNewDoc = newDocResult.get(0).get("count(*)").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../dms/inboxManage.do?method=prepareForIndexPage&providerNo=" + curUser_no + "&selectedCategory=CATEGORY_PATIENT_SUB&selectedCategoryPatient=" + demographic_no + "&selectedCategoryType=CATEGORY_TYPE_DOC'); return false;\">" + clNewDoc + "</a>"); } else { entry.add(" "); } // new ticklers String newTicklerQuery = "cl_new_ticklers"; List<Map<String, Object>> newTicklerResult = caseloadDao.getCaseloadDemographicData(newTicklerQuery, demographicParam); if (!newTicklerResult.isEmpty() && newTicklerResult.get(0).get("count(*)") != null && !newTicklerResult.get(0).get("count(*)").toString().equals("") && !newTicklerResult.get(0).get("count(*)").toString().equals("0")) { String clNewTickler = newTicklerResult.get(0).get("count(*)").toString(); entry.add("<a href='#' onclick=\"popupPage('700', '1000', '../tickler/ticklerDemoMain.jsp?demoview=" + demographic_no + "'); return false;\">" + clNewTickler + "</a>"); } else { entry.add(" "); } // new messages String newMsgQuery = "cl_new_msgs"; List<Map<String, Object>> newMsgResult = caseloadDao.getCaseloadDemographicData(newMsgQuery, demographicParam); if (!newMsgResult.isEmpty() && newMsgResult.get(0).get("count(*)") != null && !newMsgResult.get(0).get("count(*)").toString().equals("") && !newMsgResult.get(0).get("count(*)").toString().equals("0")) { String clNewMsg = newMsgResult.get(0).get("count(*)").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarMessenger/DisplayDemographicMessages.do?orderby=date&boxType=3&demographic_no=" + demographic_no + "&providerNo=" + curUser_no + "&userName=" + URLEncoder.encode(userfirstname + " " + userlastname) + "'); return false;\">" + clNewMsg + "</a>"); } else { entry.add(" "); } // measurements String msmtQuery = "cl_measurement"; String[] msmtParam = new String[2]; msmtParam[1] = demographic_no; // BMI msmtParam[0] = "BMI"; List<Map<String, Object>> msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clBmi = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=BMI'); return false;\">" + clBmi + "</a>"); } else { entry.add(" "); } // BP msmtParam[0] = "BP"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clBp = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=BP'); return false;\">" + clBp + "</a>"); } else { entry.add(" "); } // WT msmtParam[0] = "WT"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clWt = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=WT'); return false;\">" + clWt + "</a>"); } else { entry.add(" "); } // SMK msmtParam[0] = "SMK"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clSmk = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=SMK'); return false;\">" + clSmk + "</a>"); } else { entry.add(" "); } // A1C msmtParam[0] = "A1C"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clA1c = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=A1C'); return false;\">" + clA1c + "</a>"); } else { entry.add(" "); } // ACR msmtParam[0] = "ACR"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clAcr = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=ACR'); return false;\">" + clAcr + "</a>"); } else { entry.add(" "); } // SCR msmtParam[0] = "SCR"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clScr = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=SCR'); return false;\">" + clScr + "</a>"); } else { entry.add(" "); } // LDL msmtParam[0] = "LDL"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clLdl = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=LDL'); return false;\">" + clLdl + "</a>"); } else { entry.add(" "); } // HDL msmtParam[0] = "HDL"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clHdl = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=HDL'); return false;\">" + clHdl + "</a>"); } else { entry.add(" "); } // TCHD msmtParam[0] = "TCHD"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clTchd = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=TCHD'); return false;\">" + clTchd + "</a>"); } else { entry.add(" "); } // EGFR msmtParam[0] = "EGFR"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clEgfr = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=EGFR'); return false;\">" + clEgfr + "</a>"); } else { entry.add(" "); } // EYEE msmtParam[0] = "EYEE"; msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam); if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null && !msmtResult.get(0).get("dataField").toString().equals("")) { String clEyee = msmtResult.get(0).get("dataField").toString(); entry.add( "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo=" + demographic_no + "&type=EYEE'); return false;\">" + clEyee + "</a>"); } else { entry.add(" "); } data.add(entry); } return data; }
From source file:uk.ac.ebi.ep.controller.SearchController.java
@RequestMapping(value = "/checkJob", method = RequestMethod.POST) public String checkJob(@RequestParam String jobId, Model model, SearchModel searchModel, HttpSession session) throws MultiThreadingException { String view = null;/*from ww w . j a v a2 s. c o m*/ try { EnzymeFinder enzymeFinder = new EnzymeFinder(enzymePortalService, ebeyeRestService); NcbiBlastClient.Status status = enzymeFinder.getBlastStatus(jobId); switch (status) { case ERROR: case FAILURE: case NOT_FOUND: LOGGER.error("Blast job returned status " + status); view = "error"; break; case FINISHED: LOGGER.debug("BLAST job finished"); SearchResults results = enzymeFinder.getBlastResult(jobId); SearchParams searchParams = searchModel.getSearchparams(); String resultKey = getSearchKey(searchParams); cacheSearch(session.getServletContext(), resultKey, results); searchParams.setSize(searchConfig.getResultsPerPage()); searchModel.setSearchresults(results); model.addAttribute("searchModel", searchModel); model.addAttribute("pagination", getPagination(searchModel)); view = "search"; break; case RUNNING: model.addAttribute("jobId", jobId); view = "running"; break; default: } } catch (NcbiBlastClientException t) { LOGGER.error("While checking BLAST job", t); view = "error"; } return view; }
From source file:org.alfresco.web.app.Application.java
/** * Return the language Locale for the current user Session. * /*from w w w . j a v a 2 s. c o m*/ * @param session * HttpSession for the current user * @param useInterfaceLanguage * If the session language hasn't been established yet, should we base it on user preferences? * @return Current language Locale set or the VM default if none set - never null */ public static Locale getLanguage(HttpSession session, boolean useInterfaceLanguage) { Boolean useSessionLocale = (Boolean) session.getAttribute(USE_SESSION_LOCALE); if (useSessionLocale == null) { useSessionLocale = useInterfaceLanguage; session.setAttribute(USE_SESSION_LOCALE, useSessionLocale); } Locale locale = (Locale) session.getAttribute(LOCALE); if (locale == null || (!locale.equals(I18NUtil.getLocale()) && !useInterfaceLanguage)) { if (useSessionLocale && useInterfaceLanguage) { // first check saved user preferences String strLocale = null; if (getCurrentUser(session) != null) { strLocale = (String) PreferencesService.getPreferences(session) .getValue(UserPreferencesBean.PREF_INTERFACELANGUAGE); if (strLocale != null) { locale = I18NUtil.parseLocale(strLocale); } else { // failing that, use the server default locale locale = Locale.getDefault(); } } else { // else get from web-client config - the first item in the configured list of languages locale = getLanguage(WebApplicationContextUtils .getRequiredWebApplicationContext(session.getServletContext())); } // This is an interface session - the same locale will be used for the rest of the session session.setAttribute(LOCALE, locale); } else { // Get the request default, already decoded from the request headers locale = I18NUtil.getLocale(); } } return locale; }