List of usage examples for java.util HashMap isEmpty
public boolean isEmpty()
From source file:edu.ehu.galan.wiki2wordnet.wikipedia2wordnet.Mapper.java
/** * Maps LiteWi loaded topics (LionTopics) that have a Wikipedia Mapping to WordNet using * Babelnet and Fernando's work.//from w ww. j av a 2s. com * * @param pBabelnetMappings - Babelnet Mappings * @param pFernandoMappings - Samuel Fernando Mappings * @param pWikiTitles - The List of Wipedia articles that will be mapped to WordNet * @param pDesambiguationContext - The reference topics that will be used as context, MUST HAVE * an unique wordnet mapping (synset) in babelnet/fernando mappings * @param pFile - The file where the ubk will be processed in case its needed * @param pWordnet - A Wordnet dict using edu.mit.jwi library with WordNet 3.0 * @param pUkbBinDir - The dir where the ukb binaries are * @return - a hashmap with the wikititles / synsets pairs */ public static HashMap<String, Integer> babelnetFernandoToWordnet( HashMap<String, List<Wiki2WordnetMapping>> pBabelnetMappings, HashMap<String, Wiki2WordnetMapping> pFernandoMappings, List<String> pWikiTitles, String pFile, IDictionary pWordnet, List<String> pDesambiguationContext, String pUkbBinDir) { HashMap<String, Integer> mappings = new HashMap<>(pWikiTitles.size()); HashMap<String, List<Wiki2WordnetMapping>> ukbList = new HashMap<>(); if (pBabelnetMappings != null && pFernandoMappings != null) { pWikiTitles.addAll(pDesambiguationContext); for (String title : pWikiTitles) { List<Wiki2WordnetMapping> babelMapping = null; Wiki2WordnetMapping fernandoMapping = null; if (pBabelnetMappings.containsKey(title)) { babelMapping = pBabelnetMappings.get(title); } if (pFernandoMappings.containsKey(title)) { fernandoMapping = pFernandoMappings.get(title); } if (babelMapping != null && fernandoMapping == null) { if (babelMapping.size() == 1) { mappings.put(title, babelMapping.get(0).getWordNetSynset()); } else if (babelMapping.size() > 1) { ukbList.put(title, babelMapping); int l = title.split("\\s").length; for (Wiki2WordnetMapping babelMapping1 : babelMapping) { int l1 = babelMapping1.getWordnetTitle().split("\\s+").length; if (l == l1) { mappings.put(title, babelMapping1.getWordNetSynset()); break; } } if (!mappings.containsKey(title)) { mappings.put(title, babelMapping.get(0).getWordNetSynset()); } } } else if (babelMapping == null && fernandoMapping != null) { mappings.put(title, fernandoMapping.getWordNetSynset()); } else if (babelMapping != null && fernandoMapping != null) { if (babelMapping.size() == 1) { if (babelMapping.get(0).getWordNetSynset() == fernandoMapping.getWordNetSynset()) { mappings.put(title, +fernandoMapping.getWordNetSynset()); } else { List<Wiki2WordnetMapping> maps = new ArrayList<>(); maps.add(fernandoMapping); maps.add(babelMapping.get(0)); ukbList.put(title, maps); mappings.put(title, fernandoMapping.getWordNetSynset()); } } else { List<Wiki2WordnetMapping> maps = new ArrayList<>(); maps.add(fernandoMapping); maps.addAll(babelMapping); ukbList.put(title, maps); int l = title.split("\\s+").length; for (Wiki2WordnetMapping babelMapping1 : babelMapping) { int l1 = babelMapping1.getWordnetTitle().split("\\s+").length; if (l == l1) { mappings.put(title, babelMapping1.getWordNetSynset()); break; } } if (mappings.get(title) == -1) { mappings.put(title, fernandoMapping.getWordNetSynset()); } } } } } else { logger.error("No mappings provided"); } if (!ukbList.isEmpty()) { disambiguateUKB(ukbList, pDesambiguationContext, pFile, pWordnet, mappings, pUkbBinDir); } for (String context : pDesambiguationContext) { mappings.remove(context); } return mappings; }
From source file:org.akaza.openclinica.control.managestudy.UpdateStudyEventServlet.java
@Override public void processRequest() throws Exception { ctx = WebApplicationContextUtils.getWebApplicationContext(context); FormDiscrepancyNotes discNotes = null; FormProcessor fp = new FormProcessor(request); int studyEventId = fp.getInt(EVENT_ID, true); int studySubjectId = fp.getInt(STUDY_SUBJECT_ID, true); String module = fp.getString(MODULE); request.setAttribute(MODULE, module); String fromResolvingNotes = fp.getString("fromResolvingNotes", true); if (StringUtil.isBlank(fromResolvingNotes)) { session.removeAttribute(ViewNotesServlet.WIN_LOCATION); session.removeAttribute(ViewNotesServlet.NOTES_TABLE); checkStudyLocked(Page.MANAGE_STUDY, respage.getString("current_study_locked")); checkStudyFrozen(Page.MANAGE_STUDY, respage.getString("current_study_frozen")); }//from w w w.ja v a 2 s . com if (studyEventId == 0 || studySubjectId == 0) { addPageMessage(respage.getString("choose_a_study_event_to_edit")); request.setAttribute("id", new Integer(studySubjectId).toString()); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); return; } StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource()); StudySubjectBean ssub = null; if (studySubjectId > 0) { ssub = (StudySubjectBean) ssdao.findByPK(studySubjectId); request.setAttribute("studySubject", ssub); request.setAttribute("id", studySubjectId + "");// for the workflow // box, so it can // link back to view // study subject } // YW 11-07-2007, a study event could not be updated if its study // subject has been removed // Status s = ((StudySubjectBean)new // StudySubjectDAO(sm.getDataSource()).findByPK(studySubjectId)).getStatus(); Status s = ssub.getStatus(); if ("removed".equalsIgnoreCase(s.getName()) || "auto-removed".equalsIgnoreCase(s.getName())) { addPageMessage(resword.getString("study_event") + resterm.getString("could_not_be") + resterm.getString("updated") + "." + respage.getString("study_subject_has_been_deleted")); request.setAttribute("id", new Integer(studySubjectId).toString()); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); } // YW request.setAttribute(STUDY_SUBJECT_ID, new Integer(studySubjectId).toString()); StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource()); EventCRFDAO ecrfdao = new EventCRFDAO(sm.getDataSource()); StudyEventBean studyEvent = (StudyEventBean) sedao.findByPK(studyEventId); studyEvent.setEventCRFs(ecrfdao.findAllByStudyEvent(studyEvent)); // only owner, admins, and study director/coordinator can update // if (ub.getId() != studyEvent.getOwnerId()) { // if (!ub.isSysAdmin() && // !currentRole.getRole().equals(Role.STUDYDIRECTOR) // && !currentRole.getRole().equals(Role.COORDINATOR)) { // addPageMessage(respage.getString("no_have_correct_privilege_current_study") // + respage.getString("change_study_contact_sysadmin")); // request.setAttribute("id", new Integer(studySubjectId).toString()); // forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); // return; // } // } // above removed tbh 11162007 ArrayList statuses = SubjectEventStatus.toArrayList(); // remove more statuses here, tbh, 092007 // ### updates to status setting, below added tbh 102007 // following pieces of logic to be added: /* * REMOVED can happen at any step, COMPLETED can happen if the Subject * Event is already complete, COMPLETED can also happen if all required * CRFs in the Subject Event are completed, LOCKED can occur when all * Event CRFs are completed, or not started, or removed, LOCKED/REMOVED * are only options, however, when the user is study director or study * coordinator SKIPPED/STOPPED? Additional rules spelled out on Nov 16 * 2007: STOPPED should only be in the list of choices after IDE has * been started, i.e. not when SCHEDULED SKIPPED should only be in the * list before IDE has been started, i.e. when SCHEDULED reminder about * LOCKED happening only when CRFs are completed (not as in the * above...) if a status is LOCKED already, it should allow a user to * set the event back to COMPLETED */ StudyDAO sdao = new StudyDAO(this.sm.getDataSource()); StudyBean studyBean = (StudyBean) sdao.findByPK(ssub.getStudyId()); checkRoleByUserAndStudy(ub, studyBean, sdao); // To remove signed status from the list EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource()); boolean removeSign = false; // DiscrepancyNoteDAO discDao = new // DiscrepancyNoteDAO(sm.getDataSource()); ArrayList eventCrfs = studyEvent.getEventCRFs(); for (int i = 0; i < eventCrfs.size(); i++) { EventCRFBean ecrf = (EventCRFBean) eventCrfs.get(i); EventDefinitionCRFBean edcBean = edcdao.findByStudyEventIdAndFormLayoutId(studyBean, studyEventId, ecrf.getFormLayoutId()); if (ecrf.getStage().equals(DataEntryStage.INITIAL_DATA_ENTRY) || ecrf.getStage().equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE) && edcBean.isDoubleEntry() == true) { removeSign = true; break; } } if (currentRole.isResearchAssistant()) { removeSign = true; } if (currentRole.isResearchAssistant2()) { removeSign = true; } if (removeSign == true || !currentRole.isInvestigator()) { statuses.remove(SubjectEventStatus.SIGNED); } // ///End of remove signed status from the list // BWP: 2735>>keep the DATA_ENTRY_STARTED status /* * if(!studyEvent.getSubjectEventStatus().equals(SubjectEventStatus. * DATA_ENTRY_STARTED)) { * statuses.remove(SubjectEventStatus.DATA_ENTRY_STARTED); * //statuses.remove(SubjectEventStatus.SKIPPED); // per new rule * 11-2007 } */ if (!studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.NOT_SCHEDULED)) { statuses.remove(SubjectEventStatus.NOT_SCHEDULED); } if (!studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.SCHEDULED)) { // can't lock a non-completed CRF, but removed above statuses.remove(SubjectEventStatus.SCHEDULED); // statuses.remove(SubjectEventStatus.SKIPPED); // addl rule: skipped should only be present before data starts // being entered } if (studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.DATA_ENTRY_STARTED)) { statuses.remove(SubjectEventStatus.SKIPPED); } if ((studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.SCHEDULED) || studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.DATA_ENTRY_STARTED)) && currentRole.isInvestigator()) { statuses.remove(SubjectEventStatus.SIGNED); } ArrayList getECRFs = studyEvent.getEventCRFs(); // above removed tbh 102007, require to get all definitions, no matter // if they are filled in or now EventDefinitionCRFDAO edefcrfdao = new EventDefinitionCRFDAO(sm.getDataSource()); ArrayList getAllECRFs = (ArrayList) edefcrfdao.findAllByDefinition(studyBean, studyEvent.getStudyEventDefinitionId()); // does the study event have all complete CRFs which are required? logger.debug("found number of ecrfs: " + getAllECRFs.size()); // may not be populated, only entered crfs seem to ping the list for (int u = 0; u < getAllECRFs.size(); u++) { EventDefinitionCRFBean ecrfBean = (EventDefinitionCRFBean) getAllECRFs.get(u); // logger.debug("found number of existing ecrfs: " + getECRFs.size()); if (getECRFs.size() == 0) { statuses.remove(SubjectEventStatus.COMPLETED); statuses.remove(SubjectEventStatus.LOCKED); } // otherwise... for (int uv = 0; uv < getECRFs.size(); uv++) { EventCRFBean existingBean = (EventCRFBean) getECRFs.get(uv); logger.debug("***** found: " + existingBean.getCRFVersionId() + " " + existingBean.getCrf().getId() + " " + existingBean.getCrfVersion().getName() + " " + existingBean.getStatus().getName() + " " + existingBean.getStage().getName()); logger.debug( "***** comparing above to ecrfBean.DefaultVersionID: " + ecrfBean.getDefaultVersionId()); // if (existingBean.getCRFVersionId() == // ecrfBean.getDefaultVersionId()) { // OK. this only works if we go ahead and remove the drop down // will this match up? Do we need to pull it out of // studyEvent.getEventCRFs()? // only case that this will screw up is if there are no crfs // whatsoever // this is addressed in the if-clause above if (!existingBean.getStatus().equals(Status.UNAVAILABLE) && edefcrfdao.isRequiredInDefinition(existingBean.getCRFVersionId(), studyEvent)) { logger.debug("found that " + existingBean.getCrfVersion().getName() + " is required..."); // that is, it's not completed but required to complete statuses.remove(SubjectEventStatus.COMPLETED); statuses.remove(SubjectEventStatus.LOCKED); // per new rule above 11-16-2007 } // } } } // below added 092007, tbh, task #1390 if (!ub.isSysAdmin() && !currentRole.getRole().equals(Role.STUDYDIRECTOR) && !currentRole.getRole().equals(Role.COORDINATOR)) { statuses.remove(SubjectEventStatus.LOCKED); } // also, if data entry is started, can't move back to scheduled or not // scheduled if (studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.DATA_ENTRY_STARTED)) { statuses.remove(SubjectEventStatus.NOT_SCHEDULED); statuses.remove(SubjectEventStatus.SCHEDULED); } // ### tbh, above modified 102007 request.setAttribute("statuses", statuses); String action = fp.getString("action"); StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource()); StudyEventDefinitionBean sed = (StudyEventDefinitionBean) seddao .findByPK(studyEvent.getStudyEventDefinitionId()); request.setAttribute(EVENT_DEFINITION_BEAN, sed); String start_date = fp.getDateTimeInputString(INPUT_STARTDATE_PREFIX); String end_date = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX); SimpleDateFormat dteFormat = new SimpleDateFormat( ResourceBundleProvider.getFormatBundle().getString("date_format_string")); Date start = null; Date end = null; if (!StringUtils.isEmpty(start_date)) { start = fp.getDateTime(INPUT_STARTDATE_PREFIX); start_date = dteFormat.format(start); } if (!StringUtils.isEmpty(end_date)) { end = fp.getDateTime(INPUT_ENDDATE_PREFIX); end_date = dteFormat.format(end); } if (action.equalsIgnoreCase("submit")) { discNotes = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); DiscrepancyValidator v = new DiscrepancyValidator(request, discNotes); SubjectEventStatus ses = SubjectEventStatus.get(fp.getInt(SUBJECT_EVENT_STATUS_ID)); studyEvent.setSubjectEventStatus(ses); EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource()); ArrayList<EventCRFBean> eventCRFs = ecdao.findAllByStudyEvent(studyEvent); if (ses.equals(SubjectEventStatus.SKIPPED) || ses.equals(SubjectEventStatus.STOPPED)) { studyEvent.setStatus(Status.UNAVAILABLE); for (int i = 0; i < eventCRFs.size(); i++) { EventCRFBean ecb = eventCRFs.get(i); ecb.setOldStatus(ecb.getStatus()); ecb.setStatus(Status.UNAVAILABLE); ecb.setUpdater(ub); ecb.setUpdatedDate(new Date()); ecdao.update(ecb); } } else { for (int i = 0; i < eventCRFs.size(); i++) { EventCRFBean ecb = eventCRFs.get(i); ecb.setUpdater(ub); ecb.setUpdatedDate(new Date()); ecdao.update(ecb); } } // YW 3-12-2008, 2220 fix String strEnd = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX); String strEndScheduled = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX); String strStartScheduled = fp.getDateTimeInputString(INPUT_STARTDATE_PREFIX); if (!strStartScheduled.equals("")) { v.addValidation(INPUT_STARTDATE_PREFIX, Validator.IS_DATE_TIME); v.alwaysExecuteLastValidation(INPUT_STARTDATE_PREFIX); } if (!strEndScheduled.equals("")) { v.addValidation(INPUT_ENDDATE_PREFIX, Validator.IS_DATE_TIME); v.alwaysExecuteLastValidation(INPUT_ENDDATE_PREFIX); } // v.addValidation(INPUT_LOCATION, Validator.NO_BLANKS); Disable validation on location, location can be // empty when updating a study event HashMap errors = v.validate(); // YW, 3-12-2008, 2220 fix << if (!strEnd.equals("") && !errors.containsKey(INPUT_STARTDATE_PREFIX) && !errors.containsKey(INPUT_ENDDATE_PREFIX)) { end = fp.getDateTime(INPUT_ENDDATE_PREFIX); if (!fp.getString(INPUT_STARTDATE_PREFIX + "Date") .equals(fp.getString(INPUT_ENDDATE_PREFIX + "Date"))) { if (end.before(start)) { v.addError(errors, INPUT_ENDDATE_PREFIX, resexception.getString("input_provided_not_occure_after_previous_start_date_time")); } } else { // if in same date, only check when both had time entered if (fp.timeEntered(INPUT_STARTDATE_PREFIX) && fp.timeEntered(INPUT_ENDDATE_PREFIX)) { if (end.before(start) || end.equals(start)) { v.addError(errors, INPUT_ENDDATE_PREFIX, resexception .getString("input_provided_not_occure_after_previous_start_date_time")); } } } } // YW >> if (!errors.isEmpty()) { setInputMessages(errors); String prefixes[] = { INPUT_STARTDATE_PREFIX, INPUT_ENDDATE_PREFIX }; fp.setCurrentDateTimeValuesAsPreset(prefixes); setPresetValues(fp.getPresetValues()); studyEvent.setLocation(fp.getString(INPUT_LOCATION)); request.setAttribute("changeDate", fp.getString("changeDate")); request.setAttribute(EVENT_BEAN, studyEvent); forwardPage(Page.UPDATE_STUDY_EVENT); } else if (studyEvent.getSubjectEventStatus().isSigned()) { // Checks if the status is signed // ----------------- request.setAttribute(STUDY_SUBJECT_ID, new Integer(studySubjectId).toString()); if (fp.getString(INPUT_STARTDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Half").equals("")) { studyEvent.setStartTimeFlag(false); } else { studyEvent.setStartTimeFlag(true); } studyEvent.setDateStarted(start); if (!strEnd.equals("")) { studyEvent.setDateEnded(end); if (fp.getString(INPUT_ENDDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Half").equals("")) { studyEvent.setEndTimeFlag(false); } else { studyEvent.setEndTimeFlag(true); } } studyEvent.setLocation(fp.getString(INPUT_LOCATION)); studyEvent.setStudyEventDefinition(sed); // ------------------- ssdao = new StudySubjectDAO(sm.getDataSource()); StudySubjectBean ssb = (StudySubjectBean) ssdao.findByPK(studyEvent.getStudySubjectId()); ecdao = new EventCRFDAO(sm.getDataSource()); eventCRFs = ecdao.findAllByStudyEvent(studyEvent); ArrayList<Boolean> doRuleSetsExist = new ArrayList<Boolean>(); RuleSetDAO ruleSetDao = new RuleSetDAO(sm.getDataSource()); StudyBean study = (StudyBean) sdao.findByPK(ssb.getStudyId()); ArrayList eventDefinitionCRFs = (ArrayList) edcdao.findAllActiveByEventDefinitionId(study, studyEvent.getStudyEventDefinitionId()); ArrayList uncompletedEventDefinitionCRFs = getUncompletedCRFs(eventDefinitionCRFs, eventCRFs); populateUncompletedCRFsWithCRFAndVersions(uncompletedEventDefinitionCRFs); ArrayList displayEventCRFs = ViewStudySubjectServlet.getDisplayEventCRFs(sm.getDataSource(), eventCRFs, eventDefinitionCRFs, ub, currentRole, studyEvent.getSubjectEventStatus(), study); request.setAttribute("studySubject", ssb); request.setAttribute("uncompletedEventDefinitionCRFs", uncompletedEventDefinitionCRFs); request.setAttribute("displayEventCRFs", displayEventCRFs); request.setAttribute(EVENT_BEAN, studyEvent); session.setAttribute("eventSigned", studyEvent); DiscrepancyNoteUtil discNoteUtil = new DiscrepancyNoteUtil(); DisplayStudyEventBean displayEvBean = new DisplayStudyEventBean(); List<DisplayStudyEventBean> displayEvents = new ArrayList<DisplayStudyEventBean>(); // Set up a Map for the JSP view, mapping the eventCRFId to // another Map: the // inner Map maps the resolution status name to the number of // notes for that // eventCRF id, as in New --> 2 displayEvBean.setDisplayEventCRFs(displayEventCRFs); displayEvBean.setStudyEvent(studyEvent); displayEvents.add(displayEvBean); // Don't filter for res status or disc note type; disc note // beans are returned with eventCRFId set discNoteUtil.injectParentDiscNotesIntoDisplayStudyEvents(displayEvents, new HashSet(), sm.getDataSource(), 0); Map discNoteByEventCRFid = discNoteUtil.createDiscNoteMapByEventCRF(displayEvents); request.setAttribute("discNoteByEventCRFid", discNoteByEventCRFid); session.setAttribute("signatureURL", request.getRequestURL()); String originationUrl = "UpdateStudyEvent?action=" + action + "%26event_id=" + studyEventId + "%26ss_id=" + studySubjectId + "%26startDate=" + start_date + "%26startHour=" + fp.getString(INPUT_STARTDATE_PREFIX + "Hour") + "%26startMinute=" + fp.getString(INPUT_STARTDATE_PREFIX + "Minute") + "%26startHalf=" + fp.getString(INPUT_STARTDATE_PREFIX + "Half") + "%26endDate=" + end_date + "%26endHour=" + fp.getString(INPUT_ENDDATE_PREFIX + "Hour") + "%26endMinute=" + fp.getString(INPUT_ENDDATE_PREFIX + "Minute") + "%26endHalf=" + fp.getString(INPUT_ENDDATE_PREFIX + "Half") + "%26statusId=" + studyEvent.getSubjectEventStatus().getId(); request.setAttribute(ORIGINATING_PAGE, originationUrl); // response.sendRedirect(request.getContextPath() + "/pages/userSignature"); forwardPage(Page.UPDATE_STUDY_EVENT_SIGNED); } else { logger.debug("no validation error"); // YW 08-17-2007 << update start_time_flag column if (fp.getString(INPUT_STARTDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Half").equals("")) { studyEvent.setStartTimeFlag(false); } else { studyEvent.setStartTimeFlag(true); } // YW >> studyEvent.setDateStarted(start); // YW, 3-12-2008, 2220 fix which adding End datetime << if (!strEnd.equals("")) { studyEvent.setDateEnded(end); if (fp.getString(INPUT_ENDDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Half").equals("")) { studyEvent.setEndTimeFlag(false); } else { studyEvent.setEndTimeFlag(true); } } // YW >> studyEvent.setLocation(fp.getString(INPUT_LOCATION)); logger.debug("update study event and discrepancy notes..."); studyEvent.setUpdater(ub); studyEvent.setUpdatedDate(new Date()); updateClosedQueriesForUpdatedStudySubjectFields(studyEvent); StudyEventBean updatedStudyEvent = (StudyEventBean) sedao.update(studyEvent); // save discrepancy notes into DB FormDiscrepancyNotes fdn = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource()); AddNewSubjectServlet.saveFieldNotes(INPUT_LOCATION, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_STARTDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_ENDDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); // getRuleSetService().runRulesInBeanProperty(createRuleSet(ssub,sed),currentStudy,ub,request,ssub); addPageMessage(respage.getString("study_event_updated")); request.setAttribute("id", new Integer(studySubjectId).toString()); session.removeAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); // FORWARD SHOULD BE TO THE NEW PAGE } } else if (action.equalsIgnoreCase("confirm")) {// confirming the signed // status String username = request.getParameter("j_user"); String password = request.getParameter("j_pass"); if (username == null) username = ""; if (password == null) password = ""; // tring encodedUserPass = // org.akaza.openclinica.core.SecurityManager.getInstance().encrytPassword(password); UserAccountBean ub = (UserAccountBean) session.getAttribute("userBean"); StudyEventBean seb = (StudyEventBean) session.getAttribute("eventSigned"); Auth0UserService auth0UserService = ctx.getBean("auth0UserService", Auth0UserServiceImpl.class); boolean isAuthenticated = auth0UserService.authenticateAuth0User(username, password); if (isAuthenticated && ub.getName().equals(username)) { Date date = new Date(); seb.setUpdater(ub); seb.setUpdatedDate(date); seb.setAttestation("The eCRFs that are part of this event were signed by " + ub.getFirstName() + " " + ub.getLastName() + " (" + ub.getName() + ") " + "on Date Time " + date + " under the following attestation:\n\n" + resword.getString("sure_to_sign_subject3")); sedao.update(seb); // If all the StudyEvents become signed we will make the // StudySubject signed as well List studyEvents = sedao.findAllByStudySubject(ssub); boolean allSigned = true; for (Iterator iterator = studyEvents.iterator(); iterator.hasNext();) { StudyEventBean temp = (StudyEventBean) iterator.next(); if (!temp.getSubjectEventStatus().equals(SubjectEventStatus.SIGNED)) { allSigned = false; break; } } if (allSigned) { logger.debug("Signing StudySubject [" + ssub.getSubjectId() + "]"); ssub.setStatus(Status.SIGNED); ssub.setUpdater(ub); ssdao.update(ssub); } // save discrepancy notes into DB FormDiscrepancyNotes fdn = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource()); AddNewSubjectServlet.saveFieldNotes(INPUT_LOCATION, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_STARTDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_ENDDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); session.removeAttribute("eventSigned"); request.setAttribute("id", new Integer(studySubjectId).toString()); addPageMessage(respage.getString("study_event_updated")); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); } else { request.setAttribute(STUDY_SUBJECT_ID, new Integer(studySubjectId).toString()); request.setAttribute("studyEvent", seb); // ------------------- ssdao = new StudySubjectDAO(sm.getDataSource()); StudySubjectBean ssb = (StudySubjectBean) ssdao.findByPK(studyEvent.getStudySubjectId()); // prepare to figure out what the display should look like EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource()); ArrayList<EventCRFBean> eventCRFs = ecdao.findAllByStudyEvent(studyEvent); ArrayList<Boolean> doRuleSetsExist = new ArrayList<Boolean>(); RuleSetDAO ruleSetDao = new RuleSetDAO(sm.getDataSource()); StudyBean study = (StudyBean) sdao.findByPK(ssb.getStudyId()); ArrayList eventDefinitionCRFs = (ArrayList) edcdao.findAllActiveByEventDefinitionId(study, studyEvent.getStudyEventDefinitionId()); ArrayList uncompletedEventDefinitionCRFs = getUncompletedCRFs(eventDefinitionCRFs, eventCRFs); populateUncompletedCRFsWithCRFAndVersions(uncompletedEventDefinitionCRFs); ArrayList<DisplayEventCRFBean> displayEventCRFs = ViewStudySubjectServlet.getDisplayEventCRFs( sm.getDataSource(), eventCRFs, eventDefinitionCRFs, ub, currentRole, studyEvent.getSubjectEventStatus(), study); DiscrepancyNoteUtil discNoteUtil = new DiscrepancyNoteUtil(); DisplayStudyEventBean displayEvBean = new DisplayStudyEventBean(); List<DisplayStudyEventBean> displayEvents = new ArrayList<DisplayStudyEventBean>(); displayEvBean.setDisplayEventCRFs(displayEventCRFs); displayEvBean.setStudyEvent(studyEvent); displayEvents.add(displayEvBean); discNoteUtil.injectParentDiscNotesIntoDisplayStudyEvents(displayEvents, new HashSet(), sm.getDataSource(), 0); Map discNoteByEventCRFid = discNoteUtil.createDiscNoteMapByEventCRF(displayEvents); request.setAttribute("discNoteByEventCRFid", discNoteByEventCRFid); request.setAttribute("studySubject", ssb); request.setAttribute("uncompletedEventDefinitionCRFs", uncompletedEventDefinitionCRFs); request.setAttribute("displayEventCRFs", displayEventCRFs); // ------------------ request.setAttribute("studyEvent", session.getAttribute("eventSigned")); addPageMessage(restext.getString("password_match")); String originationUrl = "UpdateStudyEvent?action=" + action + "%26event_id=" + studyEventId + "%26ss_id=" + studySubjectId + "%26startDate=" + start_date + "%26startHour=" + fp.getString(INPUT_STARTDATE_PREFIX + "Hour") + "%26startMinute=" + fp.getString(INPUT_STARTDATE_PREFIX + "Minute") + "%26startHalf=" + fp.getString(INPUT_STARTDATE_PREFIX + "Half") + "%26endDate=" + end_date + "%26endHour=" + fp.getString(INPUT_ENDDATE_PREFIX + "Hour") + "%26endMinute=" + fp.getString(INPUT_ENDDATE_PREFIX + "Minute") + "%26endHalf=" + fp.getString(INPUT_ENDDATE_PREFIX + "Half") + "%26statusId=" + studyEvent.getSubjectEventStatus().getId(); request.setAttribute(ORIGINATING_PAGE, originationUrl); forwardPage(Page.UPDATE_STUDY_EVENT_SIGNED); } } else { logger.debug("no action, go to update page"); DiscrepancyNoteDAO discrepancyNoteDAO = new DiscrepancyNoteDAO(sm.getDataSource()); StudySubjectBean studySubjectBean = (StudySubjectBean) ssdao.findByPK(studyEvent.getStudySubjectId()); int studyId = studySubjectBean.getStudyId(); boolean subjectStudyIsCurrentStudy = studyId == currentStudy.getId(); boolean isParentStudy = studyBean.getParentStudyId() < 1; ArrayList<DiscrepancyNoteBean> allNotesforSubjectAndEvent = new ArrayList<DiscrepancyNoteBean>(); allNotesforSubjectAndEvent = discrepancyNoteDAO.findExistingNoteForStudyEvent(studyEvent); if (!allNotesforSubjectAndEvent.isEmpty()) { setRequestAttributesForNotes(allNotesforSubjectAndEvent); } HashMap presetValues = new HashMap(); // YW 08-17-2007 << if (studyEvent.getDateStarted() != null) { if (studyEvent.getStartTimeFlag() == true) { Calendar c = new GregorianCalendar(); c.setTime(studyEvent.getDateStarted()); presetValues.put(INPUT_STARTDATE_PREFIX + "Hour", new Integer(c.get(Calendar.HOUR_OF_DAY))); presetValues.put(INPUT_STARTDATE_PREFIX + "Minute", new Integer(c.get(Calendar.MINUTE))); // Later it could be put to somewhere as a static method if // necessary. switch (c.get(Calendar.AM_PM)) { case 0: presetValues.put(INPUT_STARTDATE_PREFIX + "Half", "am"); break; case 1: presetValues.put(INPUT_STARTDATE_PREFIX + "Half", "pm"); break; default: presetValues.put(INPUT_STARTDATE_PREFIX + "Half", ""); break; } } else { presetValues.put(INPUT_STARTDATE_PREFIX + "Hour", new Integer(-1)); presetValues.put(INPUT_STARTDATE_PREFIX + "Minute", new Integer(-1)); presetValues.put(INPUT_STARTDATE_PREFIX + "Half", ""); } // YW >> String dateValue = local_df.format(studyEvent.getDateStarted()); presetValues.put(INPUT_STARTDATE_PREFIX + "Date", dateValue); // YW 3-12-2008, add end datetime for 2220 fix<< presetValues.put(INPUT_ENDDATE_PREFIX + "Hour", new Integer(-1)); presetValues.put(INPUT_ENDDATE_PREFIX + "Minute", new Integer(-1)); presetValues.put(INPUT_ENDDATE_PREFIX + "Half", ""); } if (studyEvent.getDateEnded() != null) { if (studyEvent.getEndTimeFlag() == true) { Calendar c = new GregorianCalendar(); c.setTime(studyEvent.getDateEnded()); presetValues.put(INPUT_ENDDATE_PREFIX + "Hour", new Integer(c.get(Calendar.HOUR_OF_DAY))); presetValues.put(INPUT_ENDDATE_PREFIX + "Minute", new Integer(c.get(Calendar.MINUTE))); // Later it could be put to somewhere as a static method if // necessary. switch (c.get(Calendar.AM_PM)) { case 0: presetValues.put(INPUT_ENDDATE_PREFIX + "Half", "am"); break; case 1: presetValues.put(INPUT_ENDDATE_PREFIX + "Half", "pm"); break; default: presetValues.put(INPUT_ENDDATE_PREFIX + "Half", ""); break; } } presetValues.put(INPUT_ENDDATE_PREFIX + "Date", local_df.format(studyEvent.getDateEnded())); } // YW >> setPresetValues(presetValues); request.setAttribute("studyEvent", studyEvent); request.setAttribute("studySubject", studySubjectBean); discNotes = new FormDiscrepancyNotes(); session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes); forwardPage(Page.UPDATE_STUDY_EVENT); } // else }
From source file:org.geoserver.catalog.CoverageViewReader.java
@Override public GridCoverage2D read(GeneralParameterValue[] parameters) throws IllegalArgumentException, IOException { List<CoverageBand> bands = coverageView.getCoverageBands(); List<GridCoverage2D> coverages = new ArrayList<GridCoverage2D>(); CoveragesConsistencyChecker checker = null; int coverageBandsSize = bands.size(); // Check params, populate band indices to read if BANDS param has been defined ArrayList<Integer> selectedBandIndices = new ArrayList<Integer>(); for (int m = 0; m < coverageBandsSize; m++) { selectedBandIndices.add(m);/* w w w. j a v a2 s .c o m*/ } if (parameters != null) { for (int i = 0; i < parameters.length; i++) { final ParameterValue param = (ParameterValue) parameters[i]; if (AbstractGridFormat.BANDS.getName().equals(param.getDescriptor().getName())) { int[] bandIndicesParam = (int[]) param.getValue(); if (bandIndicesParam != null) { selectedBandIndices = new ArrayList<Integer>(); for (int bIdx = 0; bIdx < bandIndicesParam.length; bIdx++) { selectedBandIndices.add(bandIndicesParam[bIdx]); } break; } } } } // Since composition of a raster band using a formula applied on individual bands has not // been implemented, the normal case is that each CoverageBand is in fact a single band from // an input coverage. When band composition will be implemented, this will be the point where // band composition will occur, before the final BandSelect/BandMerge ops // This is a good spot to read coverages. Reading a coverage is done only once, it is // cached to be used for its other bands that possibly take part in the CoverageView definition HashMap<String, GridCoverage2D> inputCoverages = new HashMap<String, GridCoverage2D>(); GridCoverage2D dynamicAlphaSource = null; for (int bIdx : selectedBandIndices) { CoverageBand band = bands.get(bIdx); List<InputCoverageBand> selectedBands = band.getInputCoverageBands(); // Peek for coverage name String coverageName = selectedBands.get(0).getCoverageName(); if (!inputCoverages.containsKey(coverageName)) { GridCoverage2DReader reader = SingleGridCoverage2DReader.wrap(delegate, coverageName); // Remove this when removing constraints if (checker == null) { checker = new CoveragesConsistencyChecker(reader); } else { checker.checkConsistency(reader); } // bands selection parameter inside on final bands so they should not be propagated to the delegate reader GeneralParameterValue[] filteredParameters = parameters; if (parameters != null) { // creating a copy of parameters excluding the bands parameter filteredParameters = Arrays.stream(parameters) .filter(parameter -> !parameter.getDescriptor().getName() .equals(AbstractGridFormat.BANDS.getName())) .toArray(GeneralParameterValue[]::new); } final GridCoverage2D coverage = reader.read(filteredParameters); if (coverage == null) { continue; } if (dynamicAlphaSource == null && hasDynamicAlpha(coverage, reader)) { dynamicAlphaSource = coverage; } inputCoverages.put(coverageName, coverage); } } // all readers returned null? if (inputCoverages.isEmpty()) { return null; } // Group together bands that come from the same coverage ArrayList<CoverageBand> mergedBands = new ArrayList<CoverageBand>(); int idx = 0; CoverageBand mBand = null; while (idx < selectedBandIndices.size()) { if (mBand == null) { // Create a temporary CoverageBand, to use later for SelectSampleDimension operations mBand = new CoverageBand(); mBand.setInputCoverageBands(bands.get(selectedBandIndices.get(idx)).getInputCoverageBands()); } // peek to the next band. Is it from the same coverage? String coverageName = bands.get(selectedBandIndices.get(idx)).getInputCoverageBands().get(0) .getCoverageName(); if (idx + 1 < selectedBandIndices.size() && bands.get(selectedBandIndices.get(idx + 1)) .getInputCoverageBands().get(0).getCoverageName().equals(coverageName)) { // Same coverage, add its bands to the previous ArrayList<InputCoverageBand> groupBands = new ArrayList<InputCoverageBand>(); groupBands.addAll(mBand.getInputCoverageBands()); groupBands.addAll(bands.get(selectedBandIndices.get(idx + 1)).getInputCoverageBands()); mBand.setInputCoverageBands(groupBands); } else { mergedBands.add(mBand); mBand = null; } idx++; } // perform the band selects as needed for (CoverageBand band : mergedBands) { List<InputCoverageBand> selectedBands = band.getInputCoverageBands(); // Peek for coverage name String coverageName = selectedBands.get(0).getCoverageName(); // Get band indices for band selection ArrayList<Integer> bandIndices = new ArrayList<Integer>(selectedBands.size()); for (InputCoverageBand icb : selectedBands) { int bandIdx = 0; final String bandString = icb.getBand(); if (bandString != null && !bandString.isEmpty()) { bandIdx = Integer.parseInt(bandString); } bandIndices.add(bandIdx); } GridCoverage2D coverage = inputCoverages.get(coverageName); // special case for dynamic alpha on single input, no need to actually select away the alpha Hints localHints = new Hints(hints); if (dynamicAlphaSource != null && mergedBands.size() == 1 && (bandIndices.size() == 1 || bandIndices.size() == 3)) { final int alphaBandIndex = getAlphaBandIndex(coverage); addAlphaColorModelHint(localHints, bandIndices.size()); bandIndices.add(alphaBandIndex); } coverage = retainBands(bandIndices, coverage, localHints); coverages.add(coverage); } GridCoverage2D result; if (coverages.size() > 1) { // dynamic alpha but more than one source Hints localHints = new Hints(hints); if (dynamicAlphaSource != null) { int currentBandCount = countBands(coverages); // and the output is suitable for getting an alpha band if (currentBandCount == 1 || currentBandCount == 3) { final int alphaBandIndex = getAlphaBandIndex(dynamicAlphaSource); GridCoverage2D alphaBandCoverage = retainBands(Arrays.asList(alphaBandIndex), dynamicAlphaSource, hints); coverages.add(alphaBandCoverage); addAlphaColorModelHint(localHints, currentBandCount); } } // perform final band merge final ParameterValueGroup param = PROCESSOR.getOperation("BandMerge").getParameters(); param.parameter("sources").setValue(coverages); result = (GridCoverage2D) PROCESSOR.doOperation(param, localHints); } else { // optimize out, no need to do a band merge result = coverages.get(0); } return result; }
From source file:cms.service.template.TemplateUtility.java
public ArrayList<String> getChartPropertyJSON(String table, TemplateTable tabdata, String field) { HashMap<String, String> chartprop = new ServiceObject().getChartProperty(table, field); ArrayList<String> result = new ArrayList<String>(); String data = ""; String grid = ""; if (chartprop != null && !chartprop.isEmpty()) { String chartname = chartprop.get("chartname"); String charttype = chartprop.get("charttype"); String[] fieldnames = chartprop.get("fieldnames").split(","); String chartdatatype = chartprop.get("chartdatatype"); String chartalias = chartprop.get("chartalias"); String x_axis = chartprop.get("x_axis"); String y_axis = chartprop.get("y_axis"); String selectcolumn = chartprop.get("selectcolumn"); String[] captions = chartprop.get("captions").split(","); String isdefault = chartprop.get("isdefault"); grid += "{" + "\n\tview:'" + charttype + "',\n\t" + "\n\tlabel:'" + chartalias + "',\n\t" + "\n\ttooltip:{" + "\n\t\t template:'#data#'" + "\n\t}," + "\n\tlegend:{\"template\":\"#caption#\",\"marker\":{\"type\":\"square\",\"width\":25,\"height\":15}}," + "\n\tgradient: false," + "\n\tvalue:'#data#'" + "\n}"; if ((fieldnames.length == captions.length) && fieldnames.length > 0) { int c = 0; float balance; String val = "0.0"; for (String col : fieldnames) { if (c == 0) { val = tabdata.getFieldValue(col, tabdata.getRowCount() - 1); data += "\n\t\t{data:'" + tabdata.getFieldValue(col, tabdata.getRowCount() - 1) + "',caption:'" + captions[c] + "'}"; } else { data += ",\n\t\t{data:'" + tabdata.getFieldValue(col, tabdata.getRowCount() - 1) + "',caption:'" + captions[c] + "'}"; }/*w w w.j a v a 2 s. c o m*/ c++; } if (!val.isEmpty() && fieldnames.length == 1 && chartdatatype.equalsIgnoreCase("percent")) { balance = 100 - Float.valueOf(val); data += ",\n\t\t{data:'" + balance + "',caption:'Remain'}"; } } result.add(grid); result.add("[" + data + "\n]"); } return result; }
From source file:com.wasteofplastic.askyblock.commands.Challenges.java
/** * Checks if a player has enough for a challenge. Supports two types of * checks, inventory and island. Removes items if required. * //w ww.java2s .c om * @param player * @param challenge * @param type * @return true if the player has everything required */ public boolean hasRequired(final Player player, final String challenge, final String type) { // Check money double moneyReq = 0D; if (Settings.useEconomy) { moneyReq = getChallengeConfig().getDouble("challenges.challengeList." + challenge + ".requiredMoney", 0D); if (moneyReq > 0D) { if (!VaultHelper.econ.has(player, Settings.worldName, moneyReq)) { player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorNotEnoughItems); String desc = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.challengeList." + challenge + ".description") .replace("[label]", Settings.ISLANDCOMMAND)); List<String> result = new ArrayList<String>(); if (desc.contains("|")) { result.addAll(Arrays.asList(desc.split("\\|"))); } else { result.add(desc); } for (String line : result) { player.sendMessage(ChatColor.RED + line); } return false; } } } final String reqList = getChallengeConfig() .getString("challenges.challengeList." + challenge + ".requiredItems"); // The format of the requiredItems is as follows: // Material:Qty // or // Material:DamageModifier:Qty // This second one is so that items such as potions or variations on // standard items can be collected if (type.equalsIgnoreCase("inventory")) { List<ItemStack> toBeRemoved = new ArrayList<ItemStack>(); Material reqItem; int reqAmount = 0; if (!reqList.isEmpty()) { for (final String s : reqList.split(" ")) { final String[] part = s.split(":"); // Material:Qty if (part.length == 2) { try { // Correct some common mistakes if (part[0].equalsIgnoreCase("potato")) { part[0] = "POTATO_ITEM"; } else if (part[0].equalsIgnoreCase("brewing_stand")) { part[0] = "BREWING_STAND_ITEM"; } else if (part[0].equalsIgnoreCase("carrot")) { part[0] = "CARROT_ITEM"; } else if (part[0].equalsIgnoreCase("cauldron")) { part[0] = "CAULDRON_ITEM"; } else if (part[0].equalsIgnoreCase("skull")) { part[0] = "SKULL_ITEM"; } // TODO: add netherwart vs. netherstalk? if (StringUtils.isNumeric(part[0])) { reqItem = Material.getMaterial(Integer.parseInt(part[0])); } else { reqItem = Material.getMaterial(part[0].toUpperCase()); } reqAmount = Integer.parseInt(part[1]); ItemStack item = new ItemStack(reqItem); if (DEBUG) { plugin.getLogger().info("DEBUG: required item = " + reqItem.toString()); plugin.getLogger().info("DEBUG: item amount = " + reqAmount); } if (!player.getInventory().contains(reqItem)) { if (DEBUG) plugin.getLogger().info("DEBUG: item not in inventory"); return false; } else { // check amount int amount = 0; if (DEBUG) plugin.getLogger().info("DEBUG: Amount in inventory = " + player.getInventory().all(reqItem).size()); // Go through all the inventory and try to find // enough required items for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem) .entrySet()) { // Get the item ItemStack i = en.getValue(); // If the item is enchanted, skip - it doesn't count if (!i.getEnchantments().isEmpty()) { if (DEBUG) plugin.getLogger().info("DEBUG: item has enchantment - doesn't count"); continue; } // Map needs special handling because the // durability increments every time a new one is // made by the player // TODO: if there are any other items that act // in the same way, they need adding too... if (i.getDurability() == 0 || (reqItem == Material.MAP && i.getType() == Material.MAP)) { // Clear any naming, or lore etc. //i.setItemMeta(null); //player.getInventory().setItem(en.getKey(), i); // #1 item stack qty + amount is less than // required items - take all i // #2 item stack qty + amount = required // item - // take all // #3 item stack qty + amount > req items - // take // portion of i // amount += i.getAmount(); if ((amount + i.getAmount()) < reqAmount) { // Remove all of this item stack - clone // otherwise it will keep a reference to // the // original toBeRemoved.add(i.clone()); amount += i.getAmount(); if (DEBUG) plugin.getLogger() .info("DEBUG: amount is <= req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount()); } else if ((amount + i.getAmount()) == reqAmount) { if (DEBUG) plugin.getLogger() .info("DEBUG: amount is = req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount()); toBeRemoved.add(i.clone()); amount += i.getAmount(); break; } else { // Remove a portion of this item if (DEBUG) plugin.getLogger() .info("DEBUG: amount is > req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount()); item.setAmount(reqAmount - amount); item.setDurability(i.getDurability()); toBeRemoved.add(item); amount += i.getAmount(); break; } } } if (DEBUG) plugin.getLogger().info("DEBUG: amount " + amount); if (amount < reqAmount) { return false; } } } catch (Exception e) { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady); String materialList = ""; boolean hint = false; for (Material m : Material.values()) { materialList += m.toString() + ","; if (m.toString().contains(s.substring(0, 3).toUpperCase())) { plugin.getLogger().severe("Did you mean " + m.toString() + "?"); hint = true; } } if (!hint) { plugin.getLogger() .severe("Sorry, I have no idea what " + s + " is. Pick from one of these:"); plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1)); } else { plugin.getLogger().severe("Correct challenges.yml with the correct material."); } return false; } } else if (part.length == 3) { if (DEBUG) plugin.getLogger().info("DEBUG: Item with durability"); // This handles items with durability // Correct some common mistakes if (part[0].equalsIgnoreCase("potato")) { part[0] = "POTATO_ITEM"; } else if (part[0].equalsIgnoreCase("brewing_stand")) { part[0] = "BREWING_STAND_ITEM"; } else if (part[0].equalsIgnoreCase("carrot")) { part[0] = "CARROT_ITEM"; } else if (part[0].equalsIgnoreCase("cauldron")) { part[0] = "CAULDRON_ITEM"; } else if (part[0].equalsIgnoreCase("skull")) { part[0] = "SKULL_ITEM"; } if (StringUtils.isNumeric(part[0])) { reqItem = Material.getMaterial(Integer.parseInt(part[0])); } else { reqItem = Material.getMaterial(part[0].toUpperCase()); } reqAmount = Integer.parseInt(part[2]); int reqDurability = Integer.parseInt(part[1]); ItemStack item = new ItemStack(reqItem); // Item item.setDurability((short) reqDurability); // check amount int amount = 0; // Go through all the inventory and try to find // enough required items for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem) .entrySet()) { // Get the item ItemStack i = en.getValue(); if (i.hasItemMeta()) { continue; } if (i.getDurability() == reqDurability) { // Clear any naming, or lore etc. //i.setItemMeta(null); // player.getInventory().setItem(en.getKey(), i); // #1 item stack qty + amount is less than // required items - take all i // #2 item stack qty + amount = required // item - // take all // #3 item stack qty + amount > req items - // take // portion of i // amount += i.getAmount(); if ((amount + i.getAmount()) < reqAmount) { // Remove all of this item stack - clone // otherwise it will keep a reference to // the // original toBeRemoved.add(i.clone()); amount += i.getAmount(); if (DEBUG) plugin.getLogger().info("DEBUG: amount is <= req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount()); } else if ((amount + i.getAmount()) == reqAmount) { toBeRemoved.add(i.clone()); amount += i.getAmount(); break; } else { // Remove a portion of this item if (DEBUG) plugin.getLogger().info("DEBUG: amount is > req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount()); item.setAmount(reqAmount - amount); item.setDurability(i.getDurability()); toBeRemoved.add(item); amount += i.getAmount(); break; } } } if (DEBUG) { plugin.getLogger().info("DEBUG: amount is " + amount); plugin.getLogger().info("DEBUG: req amount is " + reqAmount); } if (amount < reqAmount) { if (DEBUG) plugin.getLogger().info("DEBUG: Failure! Insufficient amount of " + item.toString() + " required = " + reqAmount + " actual = " + amount); return false; } if (DEBUG) plugin.getLogger().info("DEBUG: before set amount " + item.toString() + ":" + item.getDurability() + " x " + item.getAmount()); } else if (part.length == 6 && part[0].contains("POTION")) { // Run through player's inventory for the item ItemStack[] playerInv = player.getInventory().getContents(); try { reqAmount = Integer.parseInt(part[5]); if (DEBUG) plugin.getLogger().info("DEBUG: required amount is " + reqAmount); } catch (Exception e) { plugin.getLogger().severe("Could not parse the quantity of the potion item " + s); return false; } int count = reqAmount; for (ItemStack i : playerInv) { // Catches all POTION, LINGERING_POTION and SPLASH_POTION if (i != null && i.getType().toString().contains("POTION")) { //plugin.getLogger().info("DEBUG:6 part potion check!"); // POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY if (plugin.getServer().getVersion().contains("(MC: 1.8") || plugin.getServer().getVersion().contains("(MC: 1.7")) { // Test potion Potion potion = Potion.fromItemStack(i); PotionType potionType = potion.getType(); boolean match = true; if (DEBUG) plugin.getLogger().info("DEBUG: name check " + part[1]); // Name check if (potion != null && potionType != null && !part[1].isEmpty()) { // There is a name // Custom potions may not have names if (potionType.name() != null) { if (!part[1].equalsIgnoreCase(potionType.name())) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: name does not match"); } else { if (DEBUG) plugin.getLogger().info("DEBUG: name matches"); } } else { plugin.getLogger().severe( "Potion type is unknown. Please pick from the following:"); for (PotionType pt : PotionType.values()) { plugin.getLogger().severe(pt.name()); } match = false; } } // Level check (upgraded) if (DEBUG) plugin.getLogger().info("DEBUG: level check " + part[2]); if (!part[2].isEmpty()) { // There is a level declared - check it if (StringUtils.isNumeric(part[2])) { int level = Integer.valueOf(part[2]); if (level != potion.getLevel()) { if (DEBUG) plugin.getLogger().info("DEBUG: level does not match"); match = false; } } } // Extended check if (DEBUG) plugin.getLogger().info("DEBUG: extended check " + part[3]); if (!part[3].isEmpty()) { if (part[3].equalsIgnoreCase("EXTENDED") && !potion.hasExtendedDuration()) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: extended does not match"); } if (part[3].equalsIgnoreCase("NOTEXTENDED") && potion.hasExtendedDuration()) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: extended does not match"); } } // Splash check if (DEBUG) plugin.getLogger().info("DEBUG: splash/linger check " + part[4]); if (!part[4].isEmpty()) { if (part[4].equalsIgnoreCase("SPLASH") && !potion.isSplash()) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: not splash"); } if (part[4].equalsIgnoreCase("NOSPLASH") && potion.isSplash()) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: not no splash"); } } // Quantity check if (match) { if (DEBUG) plugin.getLogger().info("DEBUG: potion matches!"); ItemStack removeItem = i.clone(); if (removeItem.getAmount() > reqAmount) { if (DEBUG) plugin.getLogger().info( "DEBUG: found " + removeItem.getAmount() + " qty in inv"); removeItem.setAmount(reqAmount); } count = count - removeItem.getAmount(); if (DEBUG) plugin.getLogger().info("DEBUG: " + count + " left"); toBeRemoved.add(removeItem); } } else { // V1.9 and above PotionMeta potionMeta = (PotionMeta) i.getItemMeta(); // If any of the settings above are missing, then any is okay boolean match = true; if (DEBUG) plugin.getLogger().info("DEBUG: name check " + part[1]); // Name check if (!part[1].isEmpty()) { // There is a name if (PotionType.valueOf(part[1]) != null) { if (!potionMeta.getBasePotionData().getType().name() .equalsIgnoreCase(part[1])) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: name does not match"); } else { if (DEBUG) plugin.getLogger().info("DEBUG: name matches"); } } else { plugin.getLogger().severe( "Potion type is unknown. Please pick from the following:"); for (PotionType pt : PotionType.values()) { plugin.getLogger().severe(pt.name()); } match = false; } } // Level check (upgraded) // plugin.getLogger().info("DEBUG: level check " + part[2]); if (!part[2].isEmpty()) { // There is a level declared - check it if (StringUtils.isNumeric(part[2])) { int level = Integer.valueOf(part[2]); if (level == 1 && potionMeta.getBasePotionData().isUpgraded()) { if (DEBUG) plugin.getLogger().info("DEBUG: level does not match"); match = false; } if (level != 1 && !potionMeta.getBasePotionData().isUpgraded()) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: level does not match"); } } } // Extended check if (DEBUG) plugin.getLogger().info("DEBUG: extended check " + part[3]); if (!part[3].isEmpty()) { if (part[3].equalsIgnoreCase("EXTENDED") && !potionMeta.getBasePotionData().isExtended()) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: extended does not match"); } if (part[3].equalsIgnoreCase("NOTEXTENDED") && potionMeta.getBasePotionData().isExtended()) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: extended does not match"); } } // Splash or Linger check if (DEBUG) plugin.getLogger().info("DEBUG: splash/linger check " + part[4]); if (!part[4].isEmpty()) { if (part[4].equalsIgnoreCase("SPLASH") && !i.getType().equals(Material.SPLASH_POTION)) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: not splash"); } if (part[4].equalsIgnoreCase("NOSPLASH") && i.getType().equals(Material.SPLASH_POTION)) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: not no splash"); } if (part[4].equalsIgnoreCase("LINGER") && !i.getType().equals(Material.LINGERING_POTION)) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: not linger"); } if (part[4].equalsIgnoreCase("NOLINGER") && i.getType().equals(Material.LINGERING_POTION)) { match = false; if (DEBUG) plugin.getLogger().info("DEBUG: not no linger"); } } // Quantity check if (match) { if (DEBUG) plugin.getLogger().info("DEBUG: potion matches!"); ItemStack removeItem = i.clone(); if (removeItem.getAmount() > reqAmount) { if (DEBUG) plugin.getLogger().info( "DEBUG: found " + removeItem.getAmount() + " qty in inv"); removeItem.setAmount(reqAmount); } count = count - removeItem.getAmount(); if (DEBUG) plugin.getLogger().info("DEBUG: " + count + " left"); toBeRemoved.add(removeItem); } } } if (count <= 0) { if (DEBUG) plugin.getLogger().info("DEBUG: Player has enough"); break; } if (DEBUG) plugin.getLogger().info("DEBUG: still need " + count + " to complete"); } if (count > 0) { if (DEBUG) plugin.getLogger().info("DEBUG: Player does not have enough"); return false; } } else { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); return false; } } } // Build up the items in the inventory and remove them if they are // all there. if (getChallengeConfig().getBoolean("challenges.challengeList." + challenge + ".takeItems")) { // checkChallengeItems(player, challenge); // int qty = 0; if (DEBUG) plugin.getLogger().info("DEBUG: Removing items"); for (ItemStack i : toBeRemoved) { // qty += i.getAmount(); if (DEBUG) plugin.getLogger().info( "DEBUG: Remove " + i.toString() + "::" + i.getDurability() + " x " + i.getAmount()); HashMap<Integer, ItemStack> leftOver = player.getInventory().removeItem(i); if (!leftOver.isEmpty()) { plugin.getLogger().warning("Exploit? Could not remove the following in challenge " + challenge + " for player " + player.getName() + ":"); for (ItemStack left : leftOver.values()) { plugin.getLogger().info(left.toString()); } return false; } } // Remove money if (moneyReq > 0D) { EconomyResponse er = VaultHelper.econ.withdrawPlayer(player, moneyReq); if (!er.transactionSuccess()) { plugin.getLogger().warning("Exploit? Could not remove " + VaultHelper.econ.format(moneyReq) + " from " + player.getName() + " in challenge " + challenge); plugin.getLogger().warning("Player's balance is " + VaultHelper.econ.format(VaultHelper.econ.getBalance(player))); } } // plugin.getLogger().info("DEBUG: total = " + qty); } return true; } if (type.equalsIgnoreCase("island")) { final HashMap<Material, Integer> neededItem = new HashMap<Material, Integer>(); final HashMap<EntityType, Integer> neededEntities = new HashMap<EntityType, Integer>(); if (!reqList.isEmpty()) { for (int i = 0; i < reqList.split(" ").length; i++) { final String[] sPart = reqList.split(" ")[i].split(":"); // Parse the qty required first try { final int qty = Integer.parseInt(sPart[1]); // Find out if the needed item is a Material or an Entity boolean isEntity = false; for (EntityType entityType : EntityType.values()) { if (entityType.toString().equalsIgnoreCase(sPart[0])) { isEntity = true; break; } } if (isEntity) { // plugin.getLogger().info("DEBUG: Item " + // sPart[0].toUpperCase() + " is an entity"); EntityType entityType = EntityType.valueOf(sPart[0].toUpperCase()); if (entityType != null) { neededEntities.put(entityType, qty); // plugin.getLogger().info("DEBUG: Needed entity is " // + Integer.parseInt(sPart[1]) + " x " + // EntityType.valueOf(sPart[0].toUpperCase()).toString()); } } else { Material item; if (StringUtils.isNumeric(sPart[0])) { item = Material.getMaterial(Integer.parseInt(sPart[0])); } else { item = Material.getMaterial(sPart[0].toUpperCase()); } if (item != null) { neededItem.put(item, qty); // plugin.getLogger().info("DEBUG: Needed item is " // + Integer.parseInt(sPart[1]) + " x " + // Material.getMaterial(sPart[0]).toString()); } else { plugin.getLogger().warning("Problem parsing required item for challenge " + challenge + " in challenges.yml!"); return false; } } } catch (Exception intEx) { plugin.getLogger().warning("Problem parsing required items for challenge " + challenge + " in challenges.yml - skipping"); return false; } } } // We now have two sets of required items or entities // Check the items first final Location l = player.getLocation(); // if (!neededItem.isEmpty()) { final int px = l.getBlockX(); final int py = l.getBlockY(); final int pz = l.getBlockZ(); // Get search radius - min is 10, max is 50 int searchRadius = getChallengeConfig() .getInt("challenges.challengeList." + challenge + ".searchRadius", 10); if (searchRadius < 10) { searchRadius = 10; } else if (searchRadius > 50) { searchRadius = 50; } for (int x = -searchRadius; x <= searchRadius; x++) { for (int y = -searchRadius; y <= searchRadius; y++) { for (int z = -searchRadius; z <= searchRadius; z++) { final Material b = new Location(l.getWorld(), px + x, py + y, pz + z).getBlock().getType(); if (neededItem.containsKey(b)) { if (neededItem.get(b) == 1) { neededItem.remove(b); } else { // Reduce the require amount by 1 neededItem.put(b, neededItem.get(b) - 1); } } } } } // } // Check if all the needed items have been amassed if (!neededItem.isEmpty()) { // plugin.getLogger().info("DEBUG: Insufficient items around"); for (Material missing : neededItem.keySet()) { player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " " + neededItem.get(missing) + " x " + Util.prettifyText(missing.toString())); } return false; } else { // plugin.getLogger().info("DEBUG: Items are there"); // Check for needed entities for (Entity entity : player.getNearbyEntities(searchRadius, searchRadius, searchRadius)) { // plugin.getLogger().info("DEBUG: Entity found:" + // entity.getType().toString()); if (neededEntities.containsKey(entity.getType())) { // plugin.getLogger().info("DEBUG: Entity in list"); if (neededEntities.get(entity.getType()) == 1) { neededEntities.remove(entity.getType()); // plugin.getLogger().info("DEBUG: Entity qty satisfied"); } else { neededEntities.put(entity.getType(), neededEntities.get(entity.getType()) - 1); // plugin.getLogger().info("DEBUG: Entity qty reduced by 1"); } } else { // plugin.getLogger().info("DEBUG: Entity not in list"); } } if (neededEntities.isEmpty()) { return true; } else { for (EntityType missing : neededEntities.keySet()) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " " + neededEntities.get(missing) + " x " + Util.prettifyText(missing.toString())); } return false; } } } return true; }
From source file:com.healthcit.cacure.businessdelegates.QuestionAnswerManager.java
public void modifyShortNames(List<FormElement> newElements) { //Make unique among this collection HashMap<String, Object> shortNamesMap = new HashMap<String, Object>(); for (FormElement formElement : newElements) { if (formElement instanceof TableElement) { TableElement tableElement = (TableElement) formElement; String tableShortName = com.healthcit.cacure.utils.StringUtils .prepareForShortName(tableElement.getTableShortName()); if (StringUtils.isBlank(tableShortName)) { tableShortName = "tableShortName"; }/*from w ww .j a v a2 s . c om*/ if (shortNamesMap.containsKey(tableShortName)) { int counter = 1; while (shortNamesMap.containsKey(tableShortName + counter)) { counter += 1; } shortNamesMap.put(tableShortName + counter, tableElement); } else { shortNamesMap.put(tableShortName, tableElement); } } List<? extends BaseQuestion> questions = formElement.getQuestions(); if (questions != null) { for (BaseQuestion baseQuestion : questions) { String shortName = com.healthcit.cacure.utils.StringUtils .prepareForShortName(baseQuestion.getShortName()); if (StringUtils.isBlank(shortName)) { shortName = "tableShortName"; } if (shortNamesMap.containsKey(shortName)) { int counter = 1; while (shortNamesMap.containsKey(shortName + counter)) { counter += 1; } shortNamesMap.put(shortName + counter, baseQuestion); } else { shortNamesMap.put(shortName, baseQuestion); } } } } if (shortNamesMap.isEmpty()) { return; } //Check similar short names in DB Set<String> similarShortNamesInDb = qstDao.getQuestionsShortNamesLike(shortNamesMap.keySet(), false); similarShortNamesInDb.addAll(teDao.getTableShortNamesLike(shortNamesMap.keySet(), false)); for (Entry<String, Object> entry : shortNamesMap.entrySet()) { String shortName = entry.getKey(); if (similarShortNamesInDb.contains(shortName)) { int counter = 1; while (similarShortNamesInDb.contains(shortName + counter)) { counter += 1; } shortName = shortName + counter; } if (entry.getValue() instanceof BaseQuestion) { ((BaseQuestion) entry.getValue()).setShortName(shortName); } else if (entry.getValue() instanceof TableElement) { ((TableElement) entry.getValue()).setTableShortName(shortName); } } }
From source file:com.krawler.esp.servlets.importProjectPlanCSV.java
/** * Prepare task for inserting in Db by reading it from CSV. Looks for exceptions while storing and skips such tasks, * which are then inserted into the failure file *//* ww w. java 2s .c o m*/ public String UpdateTaskList(HttpServletRequest request, Connection conn) throws ServiceException { String result = " "; CsvReader csvReader = null; FileInputStream fstream = null; String failedRecords = "", csvFile = ""; try { String mappedHeaders = request.getParameter("mappedheader"); csvFile = request.getParameter("filename"); String appendchoice = request.getParameter("append"); String includeheader = request.getParameter("includeheader"); String projectid = request.getParameter("projectid"); int dfid = 2; if (!StringUtil.isNullOrEmpty(request.getParameter("dfid"))) dfid = Integer.parseInt(request.getParameter("dfid")); dateFormat = dateFormatHandlers.getDateFormat(conn, dfid); com.krawler.utils.json.base.JSONObject headers = new com.krawler.utils.json.base.JSONObject( mappedHeaders); com.krawler.utils.json.base.JSONObject jtemp; String userid = AuthHandler.getUserid(request); String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + "importplans"; File csv = new File(destinationDirectory + StorageHandler.GetFileSeparator() + csvFile); fstream = new FileInputStream(csv); csvReader = new CsvReader(new InputStreamReader(fstream)); int totalrecords = 0; String s = ""; if (includeheader.equals("0")) { if (csvReader.readHeaders()) { String[] heads = csvReader.getHeaders(); for (int i = 0; i < heads.length; i++) { s += "\"" + heads[i] + "\","; } s = s.concat("\"log\""); } } failedRecords += s; int totalOldTasks = 0; if (appendchoice.equals("0")) { totalOldTasks = projdb.getLastTaskIndex(conn, projectid); } else { projdb.deleteAllRecords(conn, projectid); } resNames = new HashSet<String>(); int skipped = 0; while (csvReader.readRecord()) { totalrecords++; HashMap<Integer, String> skip = new HashMap<Integer, String>(); jtemp = new com.krawler.utils.json.base.JSONObject(); jtemp.put("taskname", getFieldFromCSV(csvReader, headers, "Task Name")); jtemp.put("startdate", getFieldFromCSV(csvReader, headers, "Start Date")); jtemp.put("enddate", getFieldFromCSV(csvReader, headers, "End Date")); String pc = getFieldFromCSV(csvReader, headers, "Percent Completed"); if (StringUtil.isNullOrEmpty(pc)) pc = "0"; else if (pc.contains("%")) { pc = pc.substring(0, pc.indexOf("%")); } jtemp.put("percentcomplete", pc); String priority = getFieldFromCSV(csvReader, headers, "Priority"); String prt = "1"; if (priority != null) { if (priority.equalsIgnoreCase("Low")) { prt = "2"; } else if (priority.equalsIgnoreCase("High")) { prt = "0"; } } jtemp.put("priority", prt); jtemp.put("notes", getFieldFromCSV(csvReader, headers, "Notes")); jtemp.put("duration", getFieldFromCSV(csvReader, headers, "Duration")); jtemp.put("resourcename", getFieldFromCSV(csvReader, headers, "Resource Name")); jtemp.put("predecessor", getFieldFromCSV(csvReader, headers, "Predecessor")); String parent = getFieldFromCSV(csvReader, headers, "Parent"); String p = ""; if (!StringUtil.equal(parent, "") && !parent.equalsIgnoreCase("Parent")) p = parent; jtemp.put("parent", p); skip = storeInDB(conn, jtemp, projectid, appendchoice, userid, totalOldTasks, totalrecords); if (!skip.isEmpty()) { if (includeheader.equals("0")) failedRecords += "\n" + csvReader.getRawRecord() + ",\"" + skip.get(1) + "\""; else failedRecords += "\n" + csvReader.getRawRecord() + "\n\"Header row was included while importing. Cannot create task for it.\""; skipped++; } else { totalOldTasks++; } } String msg_client = "", msg = "", logkey = ""; if (skipped == totalrecords) { if (appendchoice.equals("1")) { DbPool.quietRollback(conn); // Restore deleted records in case of overwrite & when nothing added from CSV } msg = "CSV discarded due to incorrect data/mapping."; msg_client = MessageSourceProxy.getMessage("pm.importlog.csvdiscarded", null, locale); logkey = "pm.importlog.csvdiscarded"; result = "{\"success\":true,\"msg\":\"" + msg + "\", \"importResult\":\"failure\"}"; } else if (skipped == 0) { msg = "Project plan imported successfully."; msg_client = MessageSourceProxy.getMessage("pm.importlog.succPlan", null, locale); logkey = "pm.importlog.succPlan"; result = "{\"success\":true,\"msg\":\"" + msg + "\", \"importResult\":\"success\"}"; } else { msg = "Some rows have been discarded due to incorrect data."; msg_client = MessageSourceProxy.getMessage("pm.importlog.discardrow", null, locale); logkey = "pm.importlog.discardrow"; result = "{\"success\":true,\"msg\":\"" + msg + "\", \"importResult\":\"success\"}"; } String fid = csvFile.substring(0, csvFile.lastIndexOf(".")); ImportLogHandler.updateRecordCount(conn, fid, msg, logkey, totalrecords, skipped, -1); fstream.close(); csvReader.close(); } catch (SessionExpiredException ex) { Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); } catch (ConfigurationException ex) { Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); } catch (com.krawler.utils.json.base.JSONException ex) { Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); } finally { createFailureFile(conn, failedRecords, csvFile); } return result; }
From source file:org.opensilk.music.library.folders.provider.FoldersLibraryProvider.java
public static List<Track> convertAudioFilesToTracks(Context context, File base, List<File> audioFiles) { if (audioFiles.size() == 0) { return Collections.emptyList(); }//from w w w .j av a2 s . co m final List<Track> trackList = new ArrayList<>(audioFiles.size()); Cursor c = null; Cursor c2 = null; try { final HashMap<String, File> pathMap = new HashMap<>(); //Build the selection final int size = audioFiles.size(); final StringBuilder selection = new StringBuilder(); selection.append(MediaStore.Audio.AudioColumns.DATA + " IN ("); for (int i = 0; i < size; i++) { final File f = audioFiles.get(i); final String path = f.getAbsolutePath(); pathMap.put(path, f); //Add file to map while where iterating selection.append("'").append(StringUtils.replace(path, "'", "''")).append("'"); if (i < size - 1) { selection.append(","); } } selection.append(")"); //make query c = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, SONG_PROJECTION, selection.toString(), null, null); if (c != null && c.moveToFirst()) { //track albums for second query final HashMap<Long, List<Track.Builder>> albumsMap = new HashMap<>(); do { final File f = pathMap .remove(c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA))); if (f != null) { Track.Builder tb = Track.builder().setIdentity(toRelativePath(base, f)) .setName(c.getString( c.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DISPLAY_NAME))) .setArtistName( c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.ARTIST))) .setAlbumName( c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.ALBUM))) .setAlbumIdentity(c .getString(c.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.ALBUM_ID))) .setDuration( c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DURATION)) / 1000) .setMimeType(c.getString( c.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.MIME_TYPE))) .setDataUri(ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, c.getLong(c.getColumnIndexOrThrow(BaseColumns._ID)))) .setArtworkUri(ContentUris.withAppendedId(BASE_ARTWORK_URI, c.getLong(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)))); long albumId = c.getLong(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)); List<Track.Builder> tsForAlbum = albumsMap.get(albumId); if (tsForAlbum == null) { tsForAlbum = new ArrayList<>(); albumsMap.put(albumId, tsForAlbum); } tsForAlbum.add(tb); } } while (c.moveToNext()); //Get the albumartists final Set<Long> albumIds = albumsMap.keySet(); final int size2 = albumIds.size(); final StringBuilder selection2 = new StringBuilder(); selection2.append(BaseColumns._ID + " IN ("); int i = 0; for (long id : albumIds) { selection2.append(id); if (++i < size2) { selection2.append(","); } } selection2.append(")"); c2 = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, SONG_ALBUM_PROJECTION, selection2.toString(), null, null); if (c2 != null && c2.moveToFirst()) { do { final long id = c2.getLong(0); final String artist = c2.getString(1); List<Track.Builder> albumTracks = albumsMap.remove(id); if (albumTracks != null) { for (Track.Builder tb : albumTracks) { tb.setAlbumArtistName(artist); trackList.add(tb.build()); } } } while (c2.moveToNext()); } if (!albumsMap.isEmpty()) { Timber.w("%d albums didn't make the cursor", albumsMap.size()); for (List<Track.Builder> tbs : albumsMap.values()) { for (Track.Builder tb : tbs) { trackList.add(tb.build()); } } } } if (!pathMap.isEmpty()) { Timber.w("%d audioFiles didn't make the cursor", pathMap.size()); for (File f : pathMap.values()) { Track t = Track.builder().setIdentity(toRelativePath(base, f)).setName(f.getName()) .setMimeType(guessMimeType(f)).setDataUri(Uri.fromFile(f)).build(); trackList.add(t); } } } catch (Exception e) { if (DUMPSTACKS) Timber.e(e, "convertAudioFilesToTracks"); } finally { closeQuietly(c); closeQuietly(c2); } return trackList; }
From source file:org.processbase.ui.bpm.generator.GeneratedWindow.java
private void prepareGroovyScripts() throws Exception { if (taskInstance != null) { processInstanceVariables.clear(); processInstanceVariables/*w w w. j a v a2s. c o m*/ .putAll(bpmModule.getProcessInstanceVariables(taskInstance.getProcessInstanceUUID())); } HashSet<String> expressions = new HashSet<String>(); HashMap<String, String> scripts = new HashMap<String, String>(); HashMap<String, String> strings = new HashMap<String, String>(); List<Page> pages_ = null; if (isDynamicForm) pages_ = generateDynamicPage(); else pages_ = pageFlow.getPages().getPages(); for (Page page : pages_) { for (Object wg : page.getWidgets().getWidgetsAndGroups()) { if (wg instanceof Widget) { Widget widget = (Widget) wg; if (widget.getInitialValue() != null && widget.getInitialValue().getExpression() != null) { expressions.add(widget.getInitialValue().getExpression()); } if (widget.getAvailableValues() != null && widget.getAvailableValues().getExpression() != null) { expressions.add(widget.getAvailableValues().getExpression()); } if (widget.getHorizontalHeader() != null) { expressions.add(widget.getHorizontalHeader()); } } else if (wg instanceof WidgetGroup) { // not yet implemented } } } for (String expression : expressions) { // System.out.println("expression = " + expression); if (expression != null && !expression.isEmpty()) { int begin = expression.indexOf(GroovyExpression.START_DELIMITER); int end = expression.indexOf(GroovyExpression.END_DELIMITER); if (begin >= end) { strings.put(expression, expression); } else { scripts.put(expression, expression); } } } Map<String, Object> context = new Hashtable<String, Object>(); context.put("parent", this);// for groovy component hack if (taskInstance != null && !scripts.isEmpty()) { groovyScripts = getBpmModule().evaluateGroovyExpressions(scripts, taskInstance.getUUID(), context, false, false); } else if (taskInstance == null && !scripts.isEmpty()) { groovyScripts = getBpmModule().evaluateGroovyExpressions(scripts, processDefinition.getUUID(), context, true); } for (String string : strings.keySet()) { groovyScripts.put(string, strings.get(string)); } // // for (String key : groovyScripts.keySet()){ // System.out.println(key + " = " + groovyScripts.get(key) + " " + // groovyScripts.get(key).getClass().getCanonicalName()); // } }
From source file:org.openbravo.userinterface.selector.CustomQuerySelectorDatasource.java
private HashMap<String, String[]> getCriteria(JSONArray criterias) { HashMap<String, String[]> criteriaValues = new HashMap<String, String[]>(); try {/* ww w. j a v a2s . c o m*/ for (int i = 0; i < criterias.length(); i++) { JSONObject criteria = criterias.getJSONObject(i); if (!criteria.has("fieldName") && criteria.has("criteria") && criteria.has("_constructor")) { // nested criteria, eval it recursively JSONArray cs = criteria.getJSONArray("criteria"); HashMap<String, String[]> c = getCriteria(cs); for (String k : c.keySet()) { criteriaValues.put(k, c.get(k)); } continue; } final String operator = criteria.getString("operator"); final String fieldName = criteria.getString("fieldName"); String[] criterion; if (operator.equals(AdvancedQueryBuilder.OPERATOR_EXISTS) && criteria.has(AdvancedQueryBuilder.EXISTS_QUERY_KEY)) { String value = ""; JSONArray values = criteria.getJSONArray("value"); for (int v = 0; v < values.length(); v++) { value += value.length() > 0 ? ", " : ""; value += "'" + values.getString(v) + "'"; } String qry = criteria.getString(AdvancedQueryBuilder.EXISTS_QUERY_KEY) .replace(AdvancedQueryBuilder.EXISTS_VALUE_HOLDER, value); if (criteriaValues.containsKey(fieldName)) { // assuming it is possible to have more than one query for exists in same field, storing // them as array String[] originalCriteria = criteriaValues.get(fieldName); List<String> newCriteria = new ArrayList<String>(Arrays.asList(originalCriteria)); newCriteria.add(qry); criteriaValues.put(fieldName, newCriteria.toArray(new String[newCriteria.size()])); } else { criteriaValues.put(fieldName, new String[] { AdvancedQueryBuilder.EXISTS_QUERY_KEY, qry }); } } else { criterion = new String[] { operator, criteria.getString("value") }; criteriaValues.put(fieldName, criterion); } } } catch (JSONException e) { log.error("Error getting criteria for custom query selector", e); } if (criteriaValues.isEmpty()) { return null; } return criteriaValues; }