List of usage examples for java.text DateFormat DEFAULT
int DEFAULT
To view the source code for java.text DateFormat DEFAULT.
Click Source Link
From source file:com.example.styleddialog.MyActivity.java
@Override public void onNegativeButtonClicked(int resultCode, Date date) { String text = ""; if (resultCode == 12) { text = "Date "; } else if (resultCode == 13) { text = "Time "; }//from w w w. j a v a2s . c o m DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT); Toast.makeText(this, text + "Cancelled " + dateFormat.format(date), Toast.LENGTH_SHORT).show(); }
From source file:org.splevo.ui.dashboard.ProcessControlTab.java
private void createTable(Table exampleTable) { tableViewer = new TableViewer(exampleTable); tableViewer.getTable().setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL)); TableViewerColumn vpmColumn = new TableViewerColumn(tableViewer, SWT.NONE); vpmColumn.getColumn().setText("VPM"); vpmColumn.setLabelProvider(new ColumnLabelProvider() { @Override//www . j a v a 2s . co m public String getText(Object element) { if (!(element instanceof VPMModelReference)) { return ""; } VPMModelReference vpm = (VPMModelReference) element; return FilenameUtils.getBaseName(vpm.getPath()); } }); TableViewerColumn dateColumn = new TableViewerColumn(tableViewer, SWT.NONE); dateColumn.getColumn().setText("Date"); dateColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { if (!(element instanceof VPMModelReference)) { return ""; } VPMModelReference vpm = (VPMModelReference) element; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(vpm.getPath()); File file = new File(resource.getLocationURI()); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.getDefault()); return dateFormat.format(file.lastModified()); } }); TableViewerColumn actionColumn = new TableViewerColumn(tableViewer, SWT.NONE); actionColumn.getColumn().setText("Action"); actionColumn.setLabelProvider(new CellButtonLabelProvider()); tableViewer.setContentProvider(new ArrayContentProvider()); vpmInput = getSPLevoProject().getVpmModelReferences(); tableViewer.setInput(vpmInput); }
From source file:org.akaza.openclinica.control.submit.CreateDiscrepancyNoteServlet.java
@Override protected void processRequest() throws Exception { FormProcessor fp = new FormProcessor(request); DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource()); List<DiscrepancyNoteType> types = DiscrepancyNoteType.list; request.setAttribute(DIS_TYPES, types); request.setAttribute(RES_STATUSES, ResolutionStatus.list); boolean writeToDB = fp.getBoolean(WRITE_TO_DB, true); //this should be set based on a new property of DisplayItemBean boolean isReasonForChange = fp.getBoolean(IS_REASON_FOR_CHANGE); int entityId = fp.getInt(ENTITY_ID); // subjectId has to be added to the database when disc notes area saved // as entity_type 'subject' int subjectId = fp.getInt(SUBJECT_ID); int itemId = fp.getInt(ITEM_ID); String entityType = fp.getString(ENTITY_TYPE); String field = fp.getString(ENTITY_FIELD); String column = fp.getString(ENTITY_COLUMN); int parentId = fp.getInt(PARENT_ID); //patch for repeating groups and RFC on empty fields int isGroup = fp.getInt(IS_GROUP_ITEM); // request.setAttribute(IS_GROUP_ITEM, new Integer(isGroup)); int eventCRFId = fp.getInt(EVENT_CRF_ID); request.setAttribute(EVENT_CRF_ID, new Integer(eventCRFId)); int rowCount = fp.getInt(PARENT_ROW_COUNT); // run only once: try to recalculate writeToDB if (!StringUtils.isBlank(entityType) && "itemData".equalsIgnoreCase(entityType) && isGroup != 0 && eventCRFId != 0) { // request.setAttribute(PARENT_ROW_COUNT, new Integer(eventCRFId)); int ordinal_for_repeating_group_field = calculateOrdinal(isGroup, field, eventCRFId, rowCount); int writeToDBStatus = isWriteToDB(isGroup, field, entityId, itemId, ordinal_for_repeating_group_field, eventCRFId);//from w w w . j a v a 2 s . c o m writeToDB = (writeToDBStatus == -1) ? false : ((writeToDBStatus == 1) ? true : writeToDB); } boolean isInError = fp.getBoolean(ERROR_FLAG); boolean isNew = fp.getBoolean(NEW_NOTE); request.setAttribute(NEW_NOTE, isNew ? "1" : "0"); String strResStatus = fp.getString(PRESET_RES_STATUS); if (!strResStatus.equals("")) { request.setAttribute(PRESET_RES_STATUS, strResStatus); } String monitor = fp.getString("monitor"); String enterData = fp.getString("enterData"); request.setAttribute("enterData", enterData); boolean enteringData = false; if (enterData != null && "1".equalsIgnoreCase(enterData)) { // variables are not set in JSP, so not from viewing data and from // entering data request.setAttribute(CAN_MONITOR, "1"); request.setAttribute("monitor", monitor); enteringData = true; } else if ("1".equalsIgnoreCase(monitor)) {// change to allow user to // enter note for all items, // not just blank items request.setAttribute(CAN_MONITOR, "1"); request.setAttribute("monitor", monitor); } else { request.setAttribute(CAN_MONITOR, "0"); } if ("itemData".equalsIgnoreCase(entityType) && enteringData) { request.setAttribute("enterItemData", "yes"); } DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); int preUserId = 0; if (!StringUtils.isBlank(entityType)) { if ("itemData".equalsIgnoreCase(entityType) || "itemdata".equalsIgnoreCase(entityType)) { ItemBean item = (ItemBean) new ItemDAO(sm.getDataSource()).findByPK(itemId); ItemDataBean itemData = (ItemDataBean) new ItemDataDAO(sm.getDataSource()).findByPK(entityId); request.setAttribute("entityValue", itemData.getValue()); request.setAttribute("entityName", item.getName()); EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource()); EventCRFBean ec = (EventCRFBean) ecdao.findByPK(itemData.getEventCRFId()); preUserId = ec.getOwnerId(); } else if ("studySub".equalsIgnoreCase(entityType)) { StudySubjectBean ssub = (StudySubjectBean) new StudySubjectDAO(sm.getDataSource()) .findByPK(entityId); SubjectBean sub = (SubjectBean) new SubjectDAO(sm.getDataSource()).findByPK(ssub.getSubjectId()); preUserId = ssub.getOwnerId(); if (!StringUtils.isBlank(column)) { if ("enrollment_date".equalsIgnoreCase(column)) { if (ssub.getEnrollmentDate() != null) { request.setAttribute("entityValue", dateFormatter.format(ssub.getEnrollmentDate())); } else { request.setAttribute("entityValue", resword.getString("N/A")); } request.setAttribute("entityName", resword.getString("enrollment_date")); } else if ("gender".equalsIgnoreCase(column)) { request.setAttribute("entityValue", sub.getGender() + ""); request.setAttribute("entityName", resword.getString("gender")); } else if ("date_of_birth".equalsIgnoreCase(column)) { if (sub.getDateOfBirth() != null) { request.setAttribute("entityValue", dateFormatter.format(sub.getDateOfBirth())); } else { request.setAttribute("entityValue", resword.getString("N/A")); } request.setAttribute("entityName", resword.getString("date_of_birth")); } else if ("unique_identifier".equalsIgnoreCase(column)) { if (sub.getUniqueIdentifier() != null) { request.setAttribute("entityValue", sub.getUniqueIdentifier()); } request.setAttribute("entityName", resword.getString("unique_identifier")); } } } else if ("subject".equalsIgnoreCase(entityType)) { SubjectBean sub = (SubjectBean) new SubjectDAO(sm.getDataSource()).findByPK(entityId); preUserId = sub.getOwnerId(); if (!StringUtils.isBlank(column)) { if ("gender".equalsIgnoreCase(column)) { request.setAttribute("entityValue", sub.getGender() + ""); request.setAttribute("entityName", resword.getString("gender")); } else if ("date_of_birth".equalsIgnoreCase(column)) { if (sub.getDateOfBirth() != null) { request.setAttribute("entityValue", dateFormatter.format(sub.getDateOfBirth())); } request.setAttribute("entityName", resword.getString("date_of_birth")); } else if ("unique_identifier".equalsIgnoreCase(column)) { request.setAttribute("entityValue", sub.getUniqueIdentifier()); request.setAttribute("entityName", resword.getString("unique_identifier")); } } } else if ("studyEvent".equalsIgnoreCase(entityType)) { StudyEventBean se = (StudyEventBean) new StudyEventDAO(sm.getDataSource()).findByPK(entityId); preUserId = se.getOwnerId(); if (!StringUtils.isBlank(column)) { if ("location".equalsIgnoreCase(column)) { request.setAttribute("entityValue", se.getLocation().equals("") || se.getLocation() == null ? resword.getString("N/A") : se.getLocation()); request.setAttribute("entityName", resword.getString("location")); } else if ("start_date".equalsIgnoreCase(column)) { if (se.getDateStarted() != null) { request.setAttribute("entityValue", dateFormatter.format(se.getDateStarted())); } else { request.setAttribute("entityValue", resword.getString("N/A")); } request.setAttribute("entityName", resword.getString("start_date")); } else if ("end_date".equalsIgnoreCase(column)) { if (se.getDateEnded() != null) { request.setAttribute("entityValue", dateFormatter.format(se.getDateEnded())); } else { request.setAttribute("entityValue", resword.getString("N/A")); } request.setAttribute("entityName", resword.getString("end_date")); } } } else if ("eventCrf".equalsIgnoreCase(entityType)) { EventCRFBean ec = (EventCRFBean) new EventCRFDAO(sm.getDataSource()).findByPK(entityId); preUserId = ec.getOwnerId(); if (!StringUtils.isBlank(column)) { if ("date_interviewed".equals(column)) { if (ec.getDateInterviewed() != null) { request.setAttribute("entityValue", dateFormatter.format(ec.getDateInterviewed())); } else { request.setAttribute("entityValue", resword.getString("N/A")); } request.setAttribute("entityName", resword.getString("date_interviewed")); } else if ("interviewer_name".equals(column)) { request.setAttribute("entityValue", ec.getInterviewerName()); request.setAttribute("entityName", resword.getString("interviewer_name")); } } } } // finds all the related notes ArrayList notes = (ArrayList) dndao.findAllByEntityAndColumn(entityType, entityId, column); DiscrepancyNoteBean parent = new DiscrepancyNoteBean(); if (parentId > 0) { dndao.setFetchMapping(true); parent = (DiscrepancyNoteBean) dndao.findByPK(parentId); if (parent.isActive()) { request.setAttribute("parent", parent); } dndao.setFetchMapping(false); } FormDiscrepancyNotes newNotes = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); if (newNotes == null) { newNotes = new FormDiscrepancyNotes(); } boolean isNotesExistInSession = (!newNotes.getNotes(field).isEmpty()) ? true : (!newNotes.getNotes(eventCRFId + "_" + field).isEmpty()) ? true : false; if (!notes.isEmpty() || isNotesExistInSession) { request.setAttribute("hasNotes", "yes"); } else { request.setAttribute("hasNotes", "no"); logger.debug("has notes:" + "no"); } //only for adding a new thread if (currentRole.getRole().equals(Role.RESEARCHASSISTANT) || currentRole.getRole().equals(Role.RESEARCHASSISTANT2) || currentRole.getRole().equals(Role.INVESTIGATOR)) { ArrayList<ResolutionStatus> resStatuses = new ArrayList<ResolutionStatus>(); resStatuses.add(ResolutionStatus.OPEN); resStatuses.add(ResolutionStatus.RESOLVED); request.setAttribute(RES_STATUSES, resStatuses); List<DiscrepancyNoteType> types2 = new ArrayList<DiscrepancyNoteType>(DiscrepancyNoteType.list); types2.remove(DiscrepancyNoteType.QUERY); request.setAttribute(DIS_TYPES, types2); request.setAttribute(WHICH_RES_STATUSES, "22"); } else if (currentRole.getRole().equals(Role.MONITOR)) { ArrayList<ResolutionStatus> resStatuses = new ArrayList(); resStatuses.add(ResolutionStatus.OPEN); resStatuses.add(ResolutionStatus.UPDATED); resStatuses.add(ResolutionStatus.CLOSED); request.setAttribute(RES_STATUSES, resStatuses); request.setAttribute(WHICH_RES_STATUSES, "1"); ArrayList<DiscrepancyNoteType> types2 = new ArrayList<DiscrepancyNoteType>(); types2.add(DiscrepancyNoteType.QUERY); request.setAttribute(DIS_TYPES, types2); } else {//Role.STUDYDIRECTOR Role.COORDINATOR List<ResolutionStatus> resStatuses = new ArrayList<ResolutionStatus>(ResolutionStatus.list); resStatuses.remove(ResolutionStatus.NOT_APPLICABLE); request.setAttribute(RES_STATUSES, resStatuses); ; request.setAttribute(WHICH_RES_STATUSES, "2"); } if (!fp.isSubmitted()) { DiscrepancyNoteBean dnb = new DiscrepancyNoteBean(); if (subjectId > 0) { // BWP: this doesn't seem correct, because the SubjectId should // be the id for // the SubjectBean, different from StudySubjectBean StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource()); StudySubjectBean ssub = (StudySubjectBean) ssdao.findByPK(subjectId); dnb.setSubjectName(ssub.getName()); dnb.setSubjectId(ssub.getId()); dnb.setStudySub(ssub); StudyDAO studyDAO = new StudyDAO(sm.getDataSource()); int parentStudyForSubject = 0; StudyBean studyBeanSub = (StudyBean) studyDAO.findByPK(ssub.getStudyId()); if (null != studyBeanSub) { parentStudyForSubject = studyBeanSub.getParentStudyId(); } if (ssub.getStudyId() != currentStudy.getId() && currentStudy.getId() != parentStudyForSubject) { addPageMessage(noAccessMessage); throw new InsufficientPermissionException(Page.MENU_SERVLET, exceptionName, "1"); } } if (itemId > 0) { ItemBean item = (ItemBean) new ItemDAO(sm.getDataSource()).findByPK(itemId); dnb.setEntityName(item.getName()); request.setAttribute("item", item); } dnb.setEntityType(entityType); dnb.setColumn(column); dnb.setEntityId(entityId); dnb.setField(field); dnb.setParentDnId(parent.getId()); dnb.setCreatedDate(new Date()); // When a user is performing Data Entry, Initial Data Entry or // Double Data Entry and // have not received any validation warnings or messages for a // particular item, // they will see Annotation as the default type in the Add // Discrepancy note window. // When a user is performing Data Entry, Initial Data Entry or // Double Data Entry and they // have received a validation warning or message for a particular // item, // they can click on the flag and the default type should be Failed // Validation Check // When a user is viewing a CRF and they click on the flag icon, the // default type should be query. // when the type is query, we should also get the user id for the // person who completed data entry /* Mantis issue: tbh 08/31/2009 * 0004092: CRCs and Investigators allowed to close a Query CRCs and Investigators are allowed to choose Closed for a Query. they are also allowed to choose New. They should only be allowed to choose Updated or Resolution Proposed. */ // above extra business rule here, tbh if (parent.getId() == 0 || isNew) {// no parent, new note thread if (enteringData) { if (isInError) { dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.FAILEDVAL.getId()); } else { dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.ANNOTATION.getId()); dnb.setResolutionStatusId(ResolutionStatus.NOT_APPLICABLE.getId()); // >> tbh WHO bug: set an assigned user for the parent // note // dnb.setAssignedUser(ub); // dnb.setAssignedUserId(ub.getId()); // << tbh 08/2009 } if (isReasonForChange) { dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.REASON_FOR_CHANGE.getId()); dnb.setResolutionStatusId(ResolutionStatus.NOT_APPLICABLE.getId()); } // << tbh 02/2010, trumps failed evaluation error checks // can we put this in admin editing request.setAttribute("autoView", "0"); // above set to automatically open up the user panel } else { // when the user is a CRC and is adding a note to the thread // it should default to Resolution Proposed, // and the assigned should be the user who logged the query, // NOT the one who is proposing the solution, tbh 02/2009 // if (currentRole.getRole().equals(Role.COORDINATOR)) { // dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType. // REASON_FOR_CHANGE.getId()); // request.setAttribute("autoView", "1"); // // above set to automatically open up the user panel // } else { dnb.setDiscrepancyNoteTypeId(DiscrepancyNoteType.QUERY.getId()); // remove this option for CRCs and Investigators //if (currentRole.getRole().equals(Role.RESEARCHASSISTANT) && currentStudy.getId() != currentStudy.getParentStudyId() if (currentRole.getRole().equals(Role.RESEARCHASSISTANT) || currentRole.getRole().equals(Role.RESEARCHASSISTANT2) || currentRole.getRole().equals(Role.INVESTIGATOR)) { request.setAttribute("autoView", "0"); } else { request.setAttribute("autoView", "1"); dnb.setAssignedUserId(preUserId); } // above set to automatically open up the user panel // } } } else if (parent.getDiscrepancyNoteTypeId() > 0) { dnb.setDiscrepancyNoteTypeId(parent.getDiscrepancyNoteTypeId()); // if it is a CRC then we should automatically propose a // solution, tbh // adding second rule here, tbh 08/2009 if ((currentRole.getRole().equals(Role.RESEARCHASSISTANT) || currentRole.getRole().equals(Role.RESEARCHASSISTANT2)) && currentStudy.getId() != currentStudy.getParentStudyId()) { dnb.setResolutionStatusId(ResolutionStatus.RESOLVED.getId()); request.setAttribute("autoView", "0"); // hide the panel, tbh } else { dnb.setResolutionStatusId(ResolutionStatus.UPDATED.getId()); } } dnb.setOwnerId(parent.getOwnerId()); String detailedDes = fp.getString("strErrMsg"); if (detailedDes != null) { dnb.setDetailedNotes(detailedDes); logger.debug("found strErrMsg: " + fp.getString("strErrMsg")); } // #4346 TBH 10/2009 //If the data entry form has not been saved yet, collecting info from parent page. dnb = getNoteInfo(dnb);// populate note infos if (dnb.getEventName() == null || dnb.getEventName().equals("")) { dnb.setEventName(fp.getString("eventName")); } if (dnb.getEventStart() == null) { dnb.setEventStart(fp.getDate("eventDate")); } if (dnb.getCrfName() == null || dnb.getCrfName().equals("")) { dnb.setCrfName(fp.getString("crfName")); } // // #4346 TBH 10/2009 request.setAttribute(DIS_NOTE, dnb); request.setAttribute("unlock", "0"); request.setAttribute(WRITE_TO_DB, writeToDB ? "1" : "0");//this should go from UI & here ArrayList userAccounts = this.generateUserAccounts(ub.getActiveStudyId(), subjectId); request.setAttribute(USER_ACCOUNTS, userAccounts); // ideally should be only two cases if ((currentRole.getRole().equals(Role.RESEARCHASSISTANT) || currentRole.getRole().equals(Role.RESEARCHASSISTANT2)) && currentStudy.getId() != currentStudy.getParentStudyId()) { // assigning back to OP, tbh request.setAttribute(USER_ACCOUNT_ID, Integer.valueOf(parent.getOwnerId()).toString()); logger.debug("assigned owner id: " + parent.getOwnerId()); } else if (dnb.getEventCRFId() > 0) { logger.debug("found a event crf id: " + dnb.getEventCRFId()); EventCRFDAO eventCrfDAO = new EventCRFDAO(sm.getDataSource()); EventCRFBean eventCrfBean = new EventCRFBean(); eventCrfBean = (EventCRFBean) eventCrfDAO.findByPK(dnb.getEventCRFId()); request.setAttribute(USER_ACCOUNT_ID, Integer.valueOf(eventCrfBean.getOwnerId()).toString()); logger.debug("assigned owner id: " + eventCrfBean.getOwnerId()); } else { // the end case } // set the user account id for the user who completed data entry forwardPage(Page.ADD_DISCREPANCY_NOTE); } else { FormDiscrepancyNotes noteTree = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); FormDiscrepancyNotes noteTree_RFC_REPEAT = (FormDiscrepancyNotes) session .getAttribute(FLAG_DISCREPANCY_RFC); ; if (noteTree_RFC_REPEAT == null) noteTree_RFC_REPEAT = new FormDiscrepancyNotes(); if (noteTree == null) { noteTree = new FormDiscrepancyNotes(); logger.debug("No note tree initailized in session"); } Validator v = new Validator(request); String description = fp.getString("description"); int typeId = fp.getInt("typeId"); int assignedUserAccountId = fp.getInt(SUBMITTED_USER_ACCOUNT_ID); int resStatusId = fp.getInt(RES_STATUS_ID); String detailedDes = fp.getString("detailedDes"); int sectionId = fp.getInt("sectionId"); DiscrepancyNoteBean note = new DiscrepancyNoteBean(); v.addValidation("description", Validator.NO_BLANKS); v.addValidation("description", Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 255); v.addValidation("detailedDes", Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 1000); v.addValidation("typeId", Validator.NO_BLANKS); HashMap errors = v.validate(); note.setDescription(description); note.setDetailedNotes(detailedDes); note.setOwner(ub); note.setOwnerId(ub.getId()); note.setCreatedDate(new Date()); note.setResolutionStatusId(resStatusId); note.setDiscrepancyNoteTypeId(typeId); note.setParentDnId(parent.getId()); if (typeId != DiscrepancyNoteType.ANNOTATION.getId() && typeId != DiscrepancyNoteType.FAILEDVAL.getId() && typeId != DiscrepancyNoteType.REASON_FOR_CHANGE.getId()) { if (assignedUserAccountId > 0) { note.setAssignedUserId(assignedUserAccountId); logger.debug("^^^ found assigned user id: " + assignedUserAccountId); } else { // a little bit of a workaround, should ideally be always from // the form note.setAssignedUserId(parent.getOwnerId()); logger.debug("found user assigned id, in the PARENT OWNER ID: " + parent.getOwnerId() + " note that user assgined id did not work: " + assignedUserAccountId); } } note.setField(field); if (DiscrepancyNoteType.ANNOTATION.getId() == note.getDiscrepancyNoteTypeId()) { updateStudyEvent(entityType, entityId); updateStudySubjectStatus(entityType, entityId); } if (DiscrepancyNoteType.ANNOTATION.getId() == note.getDiscrepancyNoteTypeId() || DiscrepancyNoteType.REASON_FOR_CHANGE.getId() == note.getDiscrepancyNoteTypeId()) { note.setResStatus(ResolutionStatus.NOT_APPLICABLE); note.setResolutionStatusId(ResolutionStatus.NOT_APPLICABLE.getId()); } if (DiscrepancyNoteType.FAILEDVAL.getId() == note.getDiscrepancyNoteTypeId() || DiscrepancyNoteType.QUERY.getId() == note.getDiscrepancyNoteTypeId()) { if (ResolutionStatus.NOT_APPLICABLE.getId() == note.getResolutionStatusId()) { Validator.addError(errors, RES_STATUS_ID, restext.getString("not_valid_res_status")); } } if (!parent.isActive()) { note.setEntityId(entityId); note.setEntityType(entityType); note.setColumn(column); } else { note.setEntityId(parent.getEntityId()); note.setEntityType(parent.getEntityType()); if (!StringUtils.isBlank(parent.getColumn())) { note.setColumn(parent.getColumn()); } else { note.setColumn(column); } note.setParentDnId(parent.getId()); } note.setStudyId(currentStudy.getId()); note = getNoteInfo(note);// populate note infos request.setAttribute(DIS_NOTE, note); request.setAttribute(WRITE_TO_DB, writeToDB ? "1" : "0");//this should go from UI & here ArrayList userAccounts = this.generateUserAccounts(ub.getActiveStudyId(), subjectId); request.setAttribute(USER_ACCOUNT_ID, Integer.valueOf(note.getAssignedUserId()).toString()); // formality more than anything else, we should go to say the note // is done Role r = currentRole.getRole(); if (r.equals(Role.MONITOR) || r.equals(Role.INVESTIGATOR) || r.equals(Role.RESEARCHASSISTANT) || r.equals(Role.RESEARCHASSISTANT2) || r.equals(Role.COORDINATOR)) { // investigator request.setAttribute("unlock", "1"); logger.debug("set UNLOCK to ONE"); } else { request.setAttribute("unlock", "0"); logger.debug("set UNLOCK to ZERO"); } request.setAttribute(USER_ACCOUNTS, userAccounts); if (errors.isEmpty()) { if (!writeToDB) { noteTree.addNote(field, note); noteTree.addIdNote(note.getEntityId(), field); noteTree_RFC_REPEAT.addNote(EVENT_CRF_ID + "_" + field, note); noteTree_RFC_REPEAT.addIdNote(note.getEntityId(), field); //-> catcher // FORM_DISCREPANCY_NOTES_NAME session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, noteTree); session.setAttribute(FLAG_DISCREPANCY_RFC, noteTree_RFC_REPEAT); // /*Setting a marker to check later while saving administrative edited data. This is needed to make * sure the system flags error while changing data for items which already has a DiscrepanyNote*/ manageReasonForChangeState(session, eventCRFId + "_" + field); forwardPage(Page.ADD_DISCREPANCY_NOTE_DONE); } else { // if not creating a new thread(note), update exsiting notes // if necessary //if ("itemData".equalsIgnoreCase(entityType) && !isNew) { int pdnId = note != null ? note.getParentDnId() : 0; if (pdnId > 0) { logger.debug("Create:find parent note for item data:" + note.getEntityId()); DiscrepancyNoteBean pNote = (DiscrepancyNoteBean) dndao.findByPK(pdnId); logger.debug("setting DN owner id: " + pNote.getOwnerId()); note.setOwnerId(pNote.getOwnerId()); if (note.getDiscrepancyNoteTypeId() == pNote.getDiscrepancyNoteTypeId()) { if (note.getResolutionStatusId() != pNote.getResolutionStatusId()) { pNote.setResolutionStatusId(note.getResolutionStatusId()); dndao.update(pNote); } if (note.getAssignedUserId() != pNote.getAssignedUserId()) { pNote.setAssignedUserId(note.getAssignedUserId()); if (pNote.getAssignedUserId() > 0) { dndao.updateAssignedUser(pNote); } else { dndao.updateAssignedUserToNull(pNote); } } } } note = (DiscrepancyNoteBean) dndao.create(note); dndao.createMapping(note); request.setAttribute(DIS_NOTE, note); if (note.getParentDnId() == 0) { // see issue 2659 this is a new thread, we will create // two notes in this case, // This way one can be the parent that updates as the // status changes, but one also stays as New. note.setParentDnId(note.getId()); note = (DiscrepancyNoteBean) dndao.create(note); dndao.createMapping(note); } /*Setting a marker to check later while saving administrative edited data. This is needed to make * sure the system flags error while changing data for items which already has a DiscrepanyNote*/ //session.setAttribute(DataEntryServlet.NOTE_SUBMITTED, true); //session.setAttribute(DataEntryServlet.NOTE_SUBMITTED, true); // String field_id_for_RFC_hash = buildDiscrepancyNoteIdForRFCHash(eventCRFId,entityId, isGroup, field, ordinal_for_repeating_group_field); String field_id_for_RFC_hash = eventCRFId + "_" + field; manageReasonForChangeState(session, field_id_for_RFC_hash); logger.debug("found resolution status: " + note.getResolutionStatusId()); String email = fp.getString(EMAIL_USER_ACCOUNT); logger.debug("found email: " + email); if (note.getAssignedUserId() > 0 && "1".equals(email.trim()) && DiscrepancyNoteType.QUERY.getId() == note.getDiscrepancyNoteTypeId()) { logger.debug("++++++ found our way here: " + note.getDiscrepancyNoteTypeId() + " id number and " + note.getDisType().getName()); // generate email for user here StringBuffer message = new StringBuffer(); // generate message here UserAccountDAO userAccountDAO = new UserAccountDAO(sm.getDataSource()); ItemDAO itemDAO = new ItemDAO(sm.getDataSource()); ItemDataDAO iddao = new ItemDataDAO(sm.getDataSource()); ItemBean item = new ItemBean(); ItemDataBean itemData = new ItemDataBean(); SectionBean section = new SectionBean(); StudyDAO studyDAO = new StudyDAO(sm.getDataSource()); UserAccountBean assignedUser = (UserAccountBean) userAccountDAO .findByPK(note.getAssignedUserId()); String alertEmail = assignedUser.getEmail(); message.append(MessageFormat.format(respage.getString("mailDNHeader"), assignedUser.getFirstName(), assignedUser.getLastName())); message.append("<A HREF='" + SQLInitServlet.getField("sysURL.base") + "ViewNotes?module=submit&listNotes_f_discrepancyNoteBean.user=" + assignedUser.getName() + "&listNotes_f_entityName=" + note.getEntityName() + "'>" + SQLInitServlet.getField("sysURL.base") + "</A><BR/>"); message.append(respage.getString("you_received_this_from")); StudyBean study = (StudyBean) studyDAO.findByPK(note.getStudyId()); SectionDAO sectionDAO = new SectionDAO(sm.getDataSource()); if ("itemData".equalsIgnoreCase(entityType)) { itemData = (ItemDataBean) iddao.findByPK(note.getEntityId()); item = (ItemBean) itemDAO.findByPK(itemData.getItemId()); if (sectionId > 0) { section = (SectionBean) sectionDAO.findByPK(sectionId); } else { //Todo section should be initialized when sectionId = 0 } } message.append(respage.getString("email_body_separator")); message.append(respage.getString("disc_note_info")); message.append(respage.getString("email_body_separator")); message.append(MessageFormat.format(respage.getString("mailDNParameters1"), note.getDescription(), note.getDetailedNotes(), ub.getName())); message.append(respage.getString("email_body_separator")); message.append(respage.getString("entity_information")); message.append(respage.getString("email_body_separator")); message.append(MessageFormat.format(respage.getString("mailDNParameters2"), study.getName(), note.getSubjectName())); if (!("studySub".equalsIgnoreCase(entityType) || "subject".equalsIgnoreCase(entityType))) { message.append(MessageFormat.format(respage.getString("mailDNParameters3"), note.getEventName())); if (!"studyEvent".equalsIgnoreCase(note.getEntityType())) { message.append(MessageFormat.format(respage.getString("mailDNParameters4"), note.getCrfName())); if (!"eventCrf".equalsIgnoreCase(note.getEntityType())) { if (sectionId > 0) { message.append(MessageFormat.format(respage.getString("mailDNParameters5"), section.getName())); } message.append(MessageFormat.format(respage.getString("mailDNParameters6"), item.getName())); } } } message.append(respage.getString("email_body_separator")); message.append(MessageFormat.format(respage.getString("mailDNThanks"), study.getName())); message.append(respage.getString("email_body_separator")); message.append(respage.getString("disclaimer")); message.append(respage.getString("email_body_separator")); message.append(respage.getString("email_footer")); String emailBodyString = message.toString(); sendEmail(alertEmail.trim(), EmailEngine.getAdminEmail(), MessageFormat .format(respage.getString("mailDNSubject"), study.getName(), note.getEntityName()), emailBodyString, true, null, null, true); } else { logger.debug("did not send email, but did save DN"); } // addPageMessage( // "Your discrepancy note has been saved into database."); addPageMessage(respage.getString("note_saved_into_db")); addPageMessage(respage.getString("page_close_automatically")); forwardPage(Page.ADD_DISCREPANCY_NOTE_SAVE_DONE); } } else { if (parentId > 0) { if (note.getResolutionStatusId() == ResolutionStatus.NOT_APPLICABLE.getId()) { request.setAttribute("autoView", "0"); } } else { if (note.getDiscrepancyNoteTypeId() == DiscrepancyNoteType.QUERY.getId()) { request.setAttribute("autoView", "1"); } else { request.setAttribute("autoView", "0"); } } setInputMessages(errors); forwardPage(Page.ADD_DISCREPANCY_NOTE); } } }
From source file:org.apache.click.util.Format.java
/** * Return a formatted date string using the given date and the default * DateFormat.//from ww w . j av a 2 s . c om * <p/> * If the date is null this method will return the * {@link #getEmptyString()} value. * * @param date the date value to format * @return a formatted date string */ public String date(Date date) { if (date != null) { DateFormat format = DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale()); return format.format(date); } else { return getEmptyString(); } }
From source file:de.betterform.xml.xforms.ui.AbstractFormControl.java
/** * convert a localized value into its XML Schema datatype representation. If the value given cannot be parsed with * the locale in betterForm context the default locale (US) will be used as fallback. This can be convenient for * user-agents that do not pass a localized value back. * * @param value the value to convert/*from w w w . jav a2 s . c o m*/ * @return converted value that can be used to update instance data and match the Schema datatype lexical space * @throws java.text.ParseException in case the incoming string cannot be converted into a Schema datatype representation */ protected String delocaliseValue(String value) throws XFormsException, ParseException { if (value == null || value.equals("")) { return value; } if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N).equals("true")) { Locale locale = (Locale) getModel().getContainer().getProcessor().getContext() .get(XFormsProcessorImpl.BETTERFORM_LOCALE); XFormsProcessorImpl processor = this.model.getContainer().getProcessor(); if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":float") || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":decimal") || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":double")) { NumberFormat formatter = NumberFormat.getNumberInstance(locale); formatter.setMaximumFractionDigits(Double.SIZE); BigDecimal number; try { number = strictParse(value, locale); } catch (ParseException e) { LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale); return value; } catch (NumberFormatException nfe) { LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale); return value; } catch (InputMismatchException ime) { LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale); return value; } return number.toPlainString(); } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":date")) { DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); Date d = null; try { d = df.parse(value); } catch (ParseException e) { //try the default locale - else fail with ParseException df = new SimpleDateFormat("yyyy-MM-dd"); df.setLenient(false); d = df.parse(value); } df = new SimpleDateFormat("yyyy-MM-dd"); return df.format(d); } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":dateTime")) { String timezone = ""; // int position = ; if (value.contains("GMT")) { timezone = value.substring(value.indexOf("GMT") + 3, value.length()); } else if (value.contains("+")) { timezone = value.substring(value.indexOf("+"), value.length()); } else if (value.contains("Z")) { timezone = "Z"; } DateFormat sf = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale); Date d = null; try { d = sf.parse(value); } catch (ParseException e) { //try the default locale - else fail with ParseException sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); d = null; d = sf.parse(value); } sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String converted = sf.format(d); if (!timezone.equals("")) { return converted + timezone; } return converted; } } return value; }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Create a Message List.//w w w .jav a2 s.c o m * Fetches a list of headers in folder foldername for part list_part. * The messagelist will be stored in the "MESSAGES" environment. * * @param foldername folder for which a message list should be built * @param list_part part of list to display (1 = last xx messages, 2 = total-2*xx - total-xx messages) */ public void createMessageList(String folderhash, int list_part) throws NoSuchFolderException { long time_start = System.currentTimeMillis(); TimeZone tz = TimeZone.getDefault(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, user.getPreferredLocale()); df.setTimeZone(tz); try { Folder folder = getFolder(folderhash); Element xml_folder = model.getFolder(folderhash); Element xml_current = model.setCurrentFolder(folderhash); Element xml_messagelist = model.getMessageList(xml_folder); if (folder == null) { throw new NoSuchFolderException(folderhash); } long fetch_start = System.currentTimeMillis(); if (!folder.isOpen()) { folder.open(Folder.READ_ONLY); } else { folder.close(false); folder.open(Folder.READ_ONLY); } /* Calculate first and last message to show */ int total_messages = folder.getMessageCount(); int new_messages = folder.getNewMessageCount(); int show_msgs = user.getMaxShowMessages(); xml_messagelist.setAttribute("total", total_messages + ""); xml_messagelist.setAttribute("new", new_messages + ""); log.debug("Total: " + total_messages); /* Handle small messagelists correctly */ if (total_messages < show_msgs) { show_msgs = total_messages; } /* Don't accept list-parts smaller than 1 */ if (list_part < 1) { list_part = 1; } for (int k = 0; k < list_part; k++) { total_messages -= show_msgs; } /* Handle beginning of message list */ if (total_messages < 0) { total_messages = 0; } int first = total_messages + 1; int last = total_messages + show_msgs; /* Set environment variable */ setEnv(); xml_current.setAttribute("first_msg", first + ""); xml_current.setAttribute("last_msg", last + ""); xml_current.setAttribute("list_part", list_part + ""); /* Fetch headers */ FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.CONTENT_INFO); log.debug("Last: " + last + ", first: " + first); Message[] msgs = folder.getMessages(first, last); log.debug(msgs.length + " messages fetching..."); folder.fetch(msgs, fp); long fetch_stop = System.currentTimeMillis(); Map header = new Hashtable(15); Flags.Flag[] sf; String from, to, cc, bcc, replyto, subject; String messageid; for (int i = msgs.length - 1; i >= 0; i--) { // if(((MimeMessage)msgs[i]).getMessageID() == null) { // folder.close(false); // folder.open(Folder.READ_WRITE); // ((MimeMessage)msgs[i]).setHeader("Message-ID","<"+user.getLogin()+"."+System.currentTimeMillis()+".jwebmail@"+user.getDomain()+">"); // ((MimeMessage)msgs[i]).saveChanges(); // folder.close(false); // folder.open(Folder.READ_ONLY); // } try { StringTokenizer tok = new StringTokenizer(((MimeMessage) msgs[i]).getMessageID(), "<>"); messageid = tok.nextToken(); } catch (NullPointerException ex) { // For mail servers that don't generate a Message-ID (Outlook et al) messageid = user.getLogin() + "." + i + ".jwebmail@" + user.getDomain(); } XMLMessage xml_message = model.getMessage(xml_folder, msgs[i].getMessageNumber() + "", messageid); /* Addresses */ from = ""; replyto = ""; to = ""; cc = ""; bcc = ""; try { from = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getFrom())); } catch (UnsupportedEncodingException e) { from = Helper.joinAddress(msgs[i].getFrom()); } try { replyto = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getReplyTo())); } catch (UnsupportedEncodingException e) { replyto = Helper.joinAddress(msgs[i].getReplyTo()); } try { to = MimeUtility .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO))); } catch (UnsupportedEncodingException e) { to = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO)); } try { cc = MimeUtility .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC))); } catch (UnsupportedEncodingException e) { cc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC)); } try { bcc = MimeUtility .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC))); } catch (UnsupportedEncodingException e) { bcc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC)); } if (from == "") from = getStringResource("unknown sender"); if (to == "") to = getStringResource("unknown recipient"); /* Flags */ sf = msgs[i].getFlags().getSystemFlags(); String basepath = parent.getBasePath(); for (int j = 0; j < sf.length; j++) { if (sf[j] == Flags.Flag.RECENT) xml_message.setAttribute("recent", "true"); if (sf[j] == Flags.Flag.SEEN) xml_message.setAttribute("seen", "true"); if (sf[j] == Flags.Flag.DELETED) xml_message.setAttribute("deleted", "true"); if (sf[j] == Flags.Flag.ANSWERED) xml_message.setAttribute("answered", "true"); if (sf[j] == Flags.Flag.DRAFT) xml_message.setAttribute("draft", "true"); if (sf[j] == Flags.Flag.FLAGGED) xml_message.setAttribute("flagged", "true"); if (sf[j] == Flags.Flag.USER) xml_message.setAttribute("user", "true"); } if (msgs[i] instanceof MimeMessage && ((MimeMessage) msgs[i]).getContentType().toUpperCase().startsWith("MULTIPART/")) { xml_message.setAttribute("attachment", "true"); } if (msgs[i] instanceof MimeMessage) { int size = ((MimeMessage) msgs[i]).getSize(); size /= 1024; xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB"); } /* Subject */ subject = ""; if (msgs[i].getSubject() != null) { try { subject = MimeUtility.decodeText(msgs[i].getSubject()); } catch (UnsupportedEncodingException ex) { subject = msgs[i].getSubject(); log.warn("Unsupported Encoding: " + ex.getMessage()); } } if (subject == null || subject.equals("")) { subject = getStringResource("no subject"); } /* Set all of what we found into the DOM */ xml_message.setHeader("FROM", from); try { // hmm, why decode subject twice? Though it doesn't matter.. xml_message.setHeader("SUBJECT", MimeUtility.decodeText(subject)); } catch (UnsupportedEncodingException e) { xml_message.setHeader("SUBJECT", subject); log.warn("Unsupported Encoding: " + e.getMessage()); } xml_message.setHeader("TO", to); xml_message.setHeader("CC", cc); xml_message.setHeader("BCC", bcc); xml_message.setHeader("REPLY-TO", replyto); /* Date */ Date d = msgs[i].getSentDate(); String ds = ""; if (d != null) { ds = df.format(d); } xml_message.setHeader("DATE", ds); } long time_stop = System.currentTimeMillis(); // try { // XMLCommon.writeXML(model.getRoot(),new FileOutputStream("/tmp/wmdebug"),""); // } catch(IOException ex) {} log.debug("Construction of message list took " + (time_stop - time_start) + " ms. Time for IMAP transfer was " + (fetch_stop - fetch_start) + " ms."); folder.close(false); } catch (NullPointerException e) { log.error("Failed to construct message list", e); throw new NoSuchFolderException(folderhash); } catch (MessagingException ex) { log.error("Failed to construct message list. " + "For some reason, contuing anyways.", ex); } }
From source file:org.getobjects.foundation.UObject.java
/** * Returns a java.util.Date for the given object. This method checks: * <ul>//ww w . j a va 2s . c om * <li>for null, which is returned as null * <li>for Date, which is returned as-is * <li>for java.util.Calendar, getTime() will be called and returned * <li>for String's. Which will get parsed using the default DateFormat. * <li>for Number's, which are treated like ms since 1970 * </ul> * All other objects are checked for a 'dateValue' method, which is then * called. * * @param _v - some object * * @return a java.util.Date or null */ public static Date dateValue(final Object _v) { return UObject.dateValue(_v, DateFormat.DEFAULT, Locale.getDefault()); }
From source file:io.bitsquare.gui.util.BSFormatter.java
public String formatDateTime(Date date) { if (date != null) { DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale); return dateFormatter.format(date) + " " + timeFormatter.format(date); } else {//from w ww . j a v a 2 s . c o m return ""; } }
From source file:io.bitsquare.gui.util.BSFormatter.java
public String formatDateTimeSpan(Date dateFrom, Date dateTo) { if (dateFrom != null && dateTo != null) { DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale); return dateFormatter.format(dateFrom) + " " + timeFormatter.format(dateFrom) + " - " + timeFormatter.format(dateTo); } else {//w w w .jav a2 s . c om return ""; } }
From source file:io.bitsquare.gui.util.BSFormatter.java
public String formatTime(Date date) { if (date != null) { DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale); return timeFormatter.format(date); } else {//from w ww.java 2 s. c o m return ""; } }