List of usage examples for java.util ArrayList clear
public void clear()
From source file:com.qmetry.qaf.automation.step.client.gherkin.GherkinFileParser.java
@SuppressWarnings("unchecked") @Override/*w w w.ja v a 2 s. co m*/ protected Collection<Object[]> parseFile(String strFile) { ArrayList<Object[]> rows = new ArrayList<Object[]>(); ArrayList<Object[]> background = new ArrayList<Object[]>(); File textFile; int lineNo = 0; boolean bglobalTags = true; boolean outline = false; boolean isBackground = false; ArrayList<String> globalTags = new ArrayList<String>(); ArrayList<String> scenarioTags = new ArrayList<String>(); ArrayList<List<Object>> examplesTable = new ArrayList<List<Object>>(); BufferedReader br = null; try { logger.info("loading feature file: " + strFile); textFile = new File(strFile); br = new BufferedReader(new FileReader(textFile)); String strLine = ""; int lastScenarioIndex = 0; // file line by line // exclude blank lines and comments StringBuffer currLineBuffer = new StringBuffer(); while ((strLine = br.readLine()) != null) { // record line number lineNo++; /** * ignore if line is empty or comment line */ if (!("".equalsIgnoreCase(strLine.trim()) || COMMENT_CHARS.contains("" + strLine.trim().charAt(0)))) { currLineBuffer.append((strLine.trim())); // process single statement Object[] cols = new Object[] { "", "", "", lineNo }; String currLine = currLineBuffer.toString(); String type = getType(currLine); if (type == "") { // this is a statement cols[0] = outline ? convertParam(currLine) : currLine; } else { isBackground = false; if (type.equalsIgnoreCase(TAG)) { String[] tags = currLine.split(" "); if (bglobalTags) { globalTags.addAll(Arrays.asList(tags)); } else { scenarioTags.addAll(Arrays.asList(tags)); } currLineBuffer = new StringBuffer(); continue; } if (type.equalsIgnoreCase(BACKGROUND)) { isBackground = true; currLineBuffer = new StringBuffer(); continue; } System.arraycopy(currLine.split(":", 2), 0, cols, 0, 2); if (type.equalsIgnoreCase(EXAMPLES)) { Object[] scenario = rows.get(lastScenarioIndex); scenario[0] = SCENARIO; Map<Object, Object> metadata = new Gson().fromJson((String) scenario[2], Map.class); //scenario[2] = new Gson().toJson(metadata); String exampleMetadata = (String) cols[1]; if (StringUtil.isNotBlank(exampleMetadata) && exampleMetadata.trim().startsWith("{")) { metadata.putAll(new Gson().fromJson(exampleMetadata, Map.class)); scenario[2] = new Gson().toJson(metadata); currLineBuffer = new StringBuffer(); continue; } } else { scenarioTags.addAll(globalTags); String metadata = String.format("{\"groups\":%s}", new Gson().toJson(scenarioTags)); cols[2] = metadata; scenarioTags.clear(); if (type.equalsIgnoreCase(FEATURE)) { bglobalTags = false; outline = false; } else { outline = type.equalsIgnoreCase(SCENARIO_OUTELINE); } } } if (!examplesTable.isEmpty()) { String lastStamtent = (String) rows.get(rows.size() - 1)[0]; int lastStatementIndex = lastStamtent.equalsIgnoreCase(EXAMPLES) ? lastScenarioIndex : (rows.size() - 1); setExamples(rows.get(lastStatementIndex), examplesTable); examplesTable.clear(); if (lastStamtent.equalsIgnoreCase(EXAMPLES)) { rows.remove(rows.size() - 1); } } if (isBackground) background.add(cols); else { rows.add(cols); boolean scenarioStarted = StringUtil.indexOfIgnoreCase(type, SCENARIO) == 0; if (scenarioStarted) { lastScenarioIndex = rows.size() - 1; rows.addAll(background); } } currLineBuffer = new StringBuffer(); } else if (StringUtil.isNotBlank(strLine) && strLine.trim().charAt(0) == '|') { addExample(strLine.trim(), examplesTable); } } int lastStatementIndex = rows.size() - 1; String lastStamtent = (String) rows.get(lastStatementIndex)[0]; if (lastStamtent.equalsIgnoreCase(EXAMPLES)) { rows.remove(lastStatementIndex); lastStatementIndex = lastScenarioIndex; } if (!examplesTable.isEmpty()) { setExamples(rows.get(lastStatementIndex), examplesTable); examplesTable.clear(); } } catch (Exception e) { String strMsg = "Exception while reading BDD file: " + strFile + "#" + lineNo; logger.error(strMsg + e); throw new AutomationError(strMsg, e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } rows.add(new Object[] { "END", "", "", lineNo + 1 });//indicate end of BDD return rows; }
From source file:com.android.launcher2.Workspace.java
void removeItems(final ArrayList<String> packages) { final HashSet<String> packageNames = new HashSet<String>(); packageNames.addAll(packages);/*w ww . j av a 2 s. c om*/ ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); for (final CellLayout layoutParent : cellLayouts) { final ViewGroup layout = layoutParent.getShortcutsAndWidgets(); // Avoid ANRs by treating each screen separately post(new Runnable() { public void run() { final ArrayList<View> childrenToRemove = new ArrayList<View>(); childrenToRemove.clear(); int childCount = layout.getChildCount(); for (int j = 0; j < childCount; j++) { final View view = layout.getChildAt(j); Object tag = view.getTag(); if (tag instanceof ShortcutInfo) { final ShortcutInfo info = (ShortcutInfo) tag; final Intent intent = info.intent; final ComponentName name = intent.getComponent(); if (name != null) { if (packageNames.contains(name.getPackageName())) { LauncherModel.deleteItemFromDatabase(mLauncher, info); childrenToRemove.add(view); } } } else if (tag instanceof FolderInfo) { final FolderInfo info = (FolderInfo) tag; final ArrayList<ShortcutInfo> contents = info.contents; final int contentsCount = contents.size(); final ArrayList<ShortcutInfo> appsToRemoveFromFolder = new ArrayList<ShortcutInfo>(); for (int k = 0; k < contentsCount; k++) { final ShortcutInfo appInfo = contents.get(k); final Intent intent = appInfo.intent; final ComponentName name = intent.getComponent(); if (name != null) { if (packageNames.contains(name.getPackageName())) { appsToRemoveFromFolder.add(appInfo); } } } for (ShortcutInfo item : appsToRemoveFromFolder) { info.remove(item); LauncherModel.deleteItemFromDatabase(mLauncher, item); } } else if (tag instanceof LauncherAppWidgetInfo) { final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; final ComponentName provider = info.providerName; if (provider != null) { if (packageNames.contains(provider.getPackageName())) { LauncherModel.deleteItemFromDatabase(mLauncher, info); childrenToRemove.add(view); } } } } childCount = childrenToRemove.size(); for (int j = 0; j < childCount; j++) { View child = childrenToRemove.get(j); // Note: We can not remove the view directly from CellLayoutChildren as this // does not re-mark the spaces as unoccupied. layoutParent.removeViewInLayout(child); if (child instanceof DropTarget) { mDragController.removeDropTarget((DropTarget) child); } } if (childCount > 0) { layout.requestLayout(); layout.invalidate(); } } }); } // Clean up new-apps animation list final Context context = getContext(); post(new Runnable() { @Override public void run() { String spKey = LauncherApplication.getSharedPreferencesKey(); SharedPreferences sp = context.getSharedPreferences(spKey, Context.MODE_PRIVATE); Set<String> newApps = sp.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, null); // Remove all queued items that match the same package if (newApps != null) { synchronized (newApps) { Iterator<String> iter = newApps.iterator(); while (iter.hasNext()) { try { Intent intent = Intent.parseUri(iter.next(), 0); String pn = ItemInfo.getPackageName(intent); if (packageNames.contains(pn)) { iter.remove(); } // It is possible that we've queued an item to be loaded, yet it has // not been added to the workspace, so remove those items as well. ArrayList<ItemInfo> shortcuts; shortcuts = LauncherModel.getWorkspaceShortcutItemInfosWithIntent(intent); for (ItemInfo info : shortcuts) { LauncherModel.deleteItemFromDatabase(context, info); } } catch (URISyntaxException e) { } } } } } }); }
From source file:com.chinamobile.bcbsp.bspstaff.BSPStaff.java
/** * Prepare the network and checknumber for Migrate. * //from w w w. j a va2 s.c o m * @param workerAgent * @param hostName */ private void prepareForMigrate(WorkerAgentProtocol workerAgent, String hostName) { this.ssc = sssc.secondStageSuperStepBarrierForRecovery(this.currentSuperStepCounter); this.setPartitionToWorkerManagerNameAndPort(ssc.getPartitionToWorkerManagerNameAndPort()); this.localBarrierNum = getLocalBarrierNumber(hostName); ArrayList<String> tmp = new ArrayList<String>(); for (String str : this.getPartitionToWorkerManagerNameAndPort().values()) { if (!tmp.contains(str)) { tmp.add(str); } } // Update the worker information workerAgent.setNumberWorkers(this.getJobId(), this.getSid(), tmp.size()); tmp.clear(); this.workerMangerNum = workerAgent.getNumberWorkers(this.getJobId(), this.getSid()); }
From source file:com.krawler.crm.reportBuilder.bizservice.ReportBuilderServiceImpl.java
public JSONObject getDataCustomReport(String companyid, String searchJson, String groupByColumns, String ss, String filterCol, String filterSS, boolean detailFlag, String fromDate, String toDate, String filterCombo, boolean heirarchyPerm, String field, String direction, String start, String limit, int moduleid, String query, String countquery, String masterIds, String[] quicksearchcol, ArrayList filter_names, ArrayList filter_params, HashMap<String, String> dataIndexReftableMap, String extraFilter) throws ServiceException { JSONObject jobj = new JSONObject(); KwlReturnObject kmsg = null;//www .ja va2 s. co m try { HashMap<String, Object> requestParams = new HashMap<String, Object>(); if (!StringUtil.isNullOrEmpty(fromDate) && !StringUtil.isNullOrEmpty(toDate) && !StringUtil.isNullOrEmpty(filterCombo)) { requestParams.put("fromDate", fromDate); requestParams.put("toDate", toDate); requestParams.put("filterCombo", filterCombo); } requestParams.put("ss", ss); if (!StringUtil.isNullOrEmpty(filterCol) && !StringUtil.isNullOrEmpty(filterSS)) { requestParams.put("filterCol", filterCol); requestParams.put("filterSS", filterSS); requestParams.put("detailFlag", detailFlag); } requestParams.put("searchJson", searchJson); if (!StringUtil.isNullOrEmpty(start)) { requestParams.put("start", StringUtil.checkForNull(start)); requestParams.put("limit", StringUtil.checkForNull(limit)); requestParams.put("pagingFlag", true); } else { requestParams.put("pagingFlag", false); } requestParams.put("companyid", companyid); if (!StringUtil.isNullOrEmpty(field)) { requestParams.put("field", field); requestParams.put("direction", direction); } requestParams.put("heirarchyPerm", heirarchyPerm); requestParams.put("query", query); requestParams.put("countquery", countquery); if (!StringUtil.isNullOrEmpty(groupByColumns)) { requestParams.put("groupByColumns", groupByColumns); } if (!StringUtil.isNullOrEmpty(extraFilter)) { requestParams.put("extrafilter", extraFilter); } requestParams.put(Constants.moduleid, moduleid); requestParams.put("quicksearchcol", quicksearchcol); kmsg = reportBuilderDaoObj.getDataCustomReport(requestParams, filter_names, filter_params); SqlRowSet rs = (SqlRowSet) kmsg.getEntityList().get(0); //ToDo- Get ids of crmCombomaster table - Only fetch those combo which are present in report. filter_names.clear(); filter_params.clear(); filter_names.add("INc.crmCombomaster"); filter_params.add(masterIds); filter_names.add("c.company.companyID"); filter_params.add(companyid); requestParams.put(Constants.filter_names, filter_names); requestParams.put(Constants.filter_params, filter_params); HashMap<String, DefaultMasterItem> defaultMasterMap = getCrmCommonDAO() .getDefaultMasterItemsMap(requestParams); //ToDo - fetch map only custom drop-down columns present in the report. Add companyid filter while fetching customComboMap. requestParams.clear(); HashMap<String, FieldComboData> customComboMap = getCrmCommonDAO() .getCustomComboItemsMap(requestParams); List<Object> ll = getIdsList(rs); List<String> idsList = (List<String>) ll.get(0); Boolean productColFlag = (Boolean) ll.get(1); // Map<String, List<LeadOwnerInfo>> ownersMap = crmLeadDAOObj.getLeadOwners(idsList); Map ownersMap = new HashMap(); Map<String, List<CrmProduct>> productsMap = new HashMap<String, List<CrmProduct>>(); if (productColFlag) { switch (moduleid) { case 1: //Account productsMap = crmAccountDAOObj.getAccountProducts(idsList); break; case 2: //Lead // ownersMap = crmLeadDAOObj.getLeadOwners(idsList); productsMap = crmLeadDAOObj.getLeadProducts(idsList); break; case 3: //Case productsMap = crmCaseDAOObj.getCaseProducts(idsList); break; case 5: //Opportunity productsMap = crmOpportunityDAOObj.getOpportunityProducts(idsList); break; } } jobj = getReportJSON(moduleid, rs, defaultMasterMap, customComboMap, productsMap, ownersMap, dataIndexReftableMap, detailFlag, productColFlag); jobj.put("totalCount", kmsg.getRecordTotalCount()); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } return jobj; }
From source file:com.chinamobile.bcbsp.bspstaff.BSPStaff.java
/** * Prepare the network, checknumber and superstep for recovery. * //from ww w . j a v a 2 s. co m * @param workerAgent * @param hostName */ private void prepareForRecovery(WorkerAgentProtocol workerAgent, String hostName) { LOG.info("[Command]--[routeTableSize]" + ssc.getPartitionToWorkerManagerNameAndPort().size()); this.setPartitionToWorkerManagerNameAndPort(ssc.getPartitionToWorkerManagerNameAndPort()); ArrayList<String> tmp = new ArrayList<String>(); for (String str : this.getPartitionToWorkerManagerNameAndPort().values()) { if (!tmp.contains(str)) { tmp.add(str); } } this.localBarrierNum = getLocalBarrierNumber(hostName); workerAgent.setNumberWorkers(this.getJobId(), this.getSid(), tmp.size()); tmp.clear(); this.workerMangerNum = workerAgent.getNumberWorkers(this.getJobId(), this.getSid()); displayFirstRoute(); }
From source file:com.chinamobile.bcbsp.bspstaff.BSPStaff.java
/** * Reset the localcheck number and communicator(RPC,ActiveMQ) for Migrating. * /*from www .j a va 2 s. co m*/ * @param ssrc * @param workerAgent */ private void resetPortsMigrate(SuperStepReportContainer ssrc, WorkerAgentProtocol workerAgent, String hostName) { ssrc.setCheckNum(this.staffNum); ssrc.setPort1(this.partitionRPCPort); ssrc.setPort2(this.activeMQPort); LOG.info("[BSPStaff migrate] Get the port for partitioning RPC is : " + this.partitionRPCPort + "!"); LOG.info("[BSPStaff migrate] Get the port for ActiveMQ Broker is : " + this.activeMQPort + "!"); this.partitionToWorkerManagerHostWithPorts = sssc.scheduleBarrierForMigrate(ssrc); // record the map from partitions to workermanagers for (Integer e : this.partitionToWorkerManagerHostWithPorts.keySet()) { String[] nameAndPorts = this.partitionToWorkerManagerHostWithPorts.get(e).split(":"); String[] ports = nameAndPorts[1].split("-"); this.getPartitionToWorkerManagerNameAndPort().put(e, nameAndPorts[0] + ":" + ports[1]); } ArrayList<String> tmp = new ArrayList<String>(); for (String str : this.getPartitionToWorkerManagerNameAndPort().values()) { String workerName = str.split(":")[0]; if (!tmp.contains(workerName)) { tmp.add(workerName); } } workerAgent.setNumberWorkers(this.getJobId(), this.getSid(), tmp.size()); tmp.clear(); this.workerMangerNum = workerAgent.getNumberWorkers(this.getJobId(), this.getSid()); LOG.info("get globle partitiontoWorkerNanagerNameAndPort is " + this.getPartitionToWorkerManagerNameAndPort()); this.localBarrierNum = getLocalBarrierNumber(hostName); }
From source file:och.front.service.FrontAppTest.java
private void test_billing_paySync() throws Exception { MapProps props = new MapProps(); props.putVal(admin_Emails, "some@host"); props.putVal(paypal_sync_debug_DisableTimer, true); props.putVal(mail_storeToDisc, false); MailServiceStub mailService = new MailServiceStub(mailSender, props); PaypalClientStub clientStub = new PaypalClientStub(); ArrayList<PaymentExt> syncPaymentsByDate = new ArrayList<PaymentExt>(); ArrayList<PaymentExt> syncPaymentsById = new ArrayList<PaymentExt>(); boolean[] canSync = { false }; //service//from www .j a va 2 s . c o m PaypalPaymentsSynchService syncService = new PaypalPaymentsSynchService() { @Override protected void syncPaymentsByDate(List<PaymentExt> list, Date now) { syncPaymentsByDate.clear(); syncPaymentsByDate.addAll(list); if (canSync[0]) super.syncPaymentsByDate(list, now); } @Override protected void syncPaymentsByIdAsync(List<PaymentExt> list, Date now) { syncPaymentsById.clear(); syncPaymentsById.addAll(list); if (canSync[0]) super.syncPaymentsByIdAsync(list, now); } }; syncService.setCacheServerContext(new CacheServerContext(props, cacheSever, db, mailService)); syncService.setClient(clientStub); syncService.init(); Date now = new Date(); Date minuteAgo = new Date(now.getTime() - DateUtil.ONE_MINUTE); Date twoHoursAgo = new Date(now.getTime() - DateUtil.ONE_HOUR * 2); Date monthAgo = DateUtil.addDays(now, -31); long userId = 103L; //fill db universal.update(new CreatePayment(new PaymentExt(universal.nextSeqFor(payments), userId, PAYPAL, "p1", WAIT, minuteAgo, minuteAgo, BigDecimal.ONE))); universal.update(new CreatePayment(new PaymentExt(universal.nextSeqFor(payments), userId, PAYPAL, "p2", WAIT, twoHoursAgo, twoHoursAgo, BigDecimal.ONE))); universal.update(new CreatePayment(new PaymentExt(universal.nextSeqFor(payments), userId, PAYPAL, "p3", WAIT, monthAgo, monthAgo, BigDecimal.ONE))); //check filter logic pushToSecurityContext_SYSTEM_USER(); try { assertEquals(0, billing.getUserBalance(userId).intValue()); //first call -- all payments to sync { syncService.doSyncWork(now); assertEquals(2, syncPaymentsByDate.size()); assertEquals(1, syncPaymentsById.size()); assertEquals("p1", syncPaymentsByDate.get(0).externalId); assertEquals("p2", syncPaymentsByDate.get(1).externalId); assertEquals("p3", syncPaymentsById.get(0).externalId); syncPaymentsByDate.clear(); syncPaymentsById.clear(); } //second call -- only new now = new Date(now.getTime() + 1000); { syncService.doSyncWork(now); assertEquals(1, syncPaymentsByDate.size()); assertEquals(0, syncPaymentsById.size()); assertEquals("p1", syncPaymentsByDate.get(0).externalId); syncPaymentsByDate.clear(); syncPaymentsById.clear(); } //next call -- same now = new Date(now.getTime() + 1000); { syncService.doSyncWork(now); assertEquals(1, syncPaymentsByDate.size()); assertEquals(0, syncPaymentsById.size()); assertEquals("p1", syncPaymentsByDate.get(0).externalId); syncPaymentsByDate.clear(); syncPaymentsById.clear(); } //after long delta -- all now = new Date(now.getTime() + 1000); props.putVal(paypal_sync_longUpdateDelta, 0); { syncService.doSyncWork(now); assertEquals(2, syncPaymentsByDate.size()); assertEquals(1, syncPaymentsById.size()); syncPaymentsByDate.clear(); syncPaymentsById.clear(); } now = new Date(now.getTime() + 1000); props.putVal(paypal_sync_longUpdateDelta, paypal_sync_longUpdateDelta.longDefVal()); { syncService.doSyncWork(now); assertEquals(1, syncPaymentsByDate.size()); assertEquals(0, syncPaymentsById.size()); assertEquals("p1", syncPaymentsByDate.get(0).externalId); syncPaymentsByDate.clear(); syncPaymentsById.clear(); } } finally { popUserFromSecurityContext(); } //sync by pushToSecurityContext_SYSTEM_USER(); try { canSync[0] = true; //update by date now = new Date(now.getTime() + 1000); assertEquals(WAIT, universal.selectOne(new GetPaymentByExternalId(PAYPAL, "p1")).paymentStatus); clientStub.paymentHistory = list(new PaymentBase("p1", COMPLETED)); syncService.doSyncWork(now); assertEquals(COMPLETED, universal.selectOne(new GetPaymentByExternalId(PAYPAL, "p1")).paymentStatus); assertEquals(1, universal.selectOne(new SelectUserBalanceById(userId)).balance.intValue()); assertEquals(1, billing.getUserBalance(userId).intValue()); //update by ids now = new Date(now.getTime() + 1000); props.putVal(paypal_sync_longUpdateDelta, 0); clientStub.paymentHistory = list(new PaymentBase("p2", COMPLETED)); clientStub.paymentId = "p3"; clientStub.payment = new PaymentBase(clientStub.paymentId, COMPLETED); syncService.doSyncWork(now); assertEquals(COMPLETED, universal.selectOne(new GetPaymentByExternalId(PAYPAL, "p2")).paymentStatus); assertEquals(COMPLETED, universal.selectOne(new GetPaymentByExternalId(PAYPAL, "p3")).paymentStatus); assertEquals(3, billing.getUserBalance(userId).intValue()); now = new Date(now.getTime() + 1000); syncPaymentsByDate.clear(); syncPaymentsById.clear(); syncService.doSyncWork(now); assertEquals(0, syncPaymentsByDate.size()); assertEquals(0, syncPaymentsById.size()); } finally { popUserFromSecurityContext(); } //test timers props.putVal(paypal_sync_debug_DisableTimer, false); props.putVal(paypal_sync_timerDelay, 1L); props.putVal(paypal_sync_timerDelta, 20L); syncService.stop(); syncService.init(); pushToSecurityContext_SYSTEM_USER(); try { canSync[0] = true; clientStub.paymentHistory = list(new PaymentBase("p4", COMPLETED)); universal.update(new CreatePayment(new PaymentExt(universal.nextSeqFor(payments), userId, PAYPAL, "p4", WAIT, minuteAgo, minuteAgo, BigDecimal.ONE))); Thread.sleep(50); assertEquals(COMPLETED, universal.selectOne(new GetPaymentByExternalId(PAYPAL, "p4")).paymentStatus); assertEquals(4, billing.getUserBalance(userId).intValue()); } finally { syncService.stop(); popUserFromSecurityContext(); } //test send errors to admin props.putVal(paypal_sync_sendErrorsDelay, 1L); props.putVal(paypal_sync_sendErrorsDelta, 20L); syncService.init(); try { universal.update(new CreatePayment(new PaymentExt(universal.nextSeqFor(payments), userId, PAYPAL, "p5", WAIT, minuteAgo, minuteAgo, BigDecimal.ONE))); mailSender.tasks.clear(); clientStub.paymentHistory = null; Thread.sleep(100); assertTrue(mailSender.tasks.size() > 0); //dissable send errors props.putVal(paypal_sync_debug_DisableSendErrors, true); Thread.sleep(50); mailSender.tasks.clear(); Thread.sleep(50); assertTrue(mailSender.tasks.size() == 0); //enable again props.putVal(paypal_sync_debug_DisableSendErrors, false); Thread.sleep(50); assertTrue(mailSender.tasks.size() > 0); //set filter props.putVal(paypal_sync_skipErrorTerms, "empty history by daysBefore"); Thread.sleep(50); mailSender.tasks.clear(); Thread.sleep(50); assertTrue(mailSender.tasks.size() == 0); //remove filter props.putVal(paypal_sync_skipErrorTerms, (String) null); Thread.sleep(50); assertTrue(mailSender.tasks.size() > 0); } finally { syncService.stop(); } }
From source file:op.care.prescription.PnlPrescription.java
private JPanel getMenu(final Prescription prescription) { JPanel pnlMenu = new JPanel(new VerticalLayout()); long numBHPs = BHPTools.getConfirmedBHPs(prescription); final MedInventory inventory = prescription.shouldBeCalculated() ? TradeFormTools.getInventory4TradeForm(prescription.getResident(), prescription.getTradeForm()) : null;//w w w .j av a2s .c o m final MedStock stockInUse = MedStockTools.getStockInUse(inventory); // checked for acls if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) { /*** * ____ _ * / ___| |__ __ _ _ __ __ _ ___ * | | | '_ \ / _` | '_ \ / _` |/ _ \ * | |___| | | | (_| | | | | (_| | __/ * \____|_| |_|\__,_|_| |_|\__, |\___| * |___/ */ final JButton btnChange = GUITools.createHyperlinkButton( "nursingrecords.prescription.btnChange.tooltip", SYSConst.icon22playerPlay, null); btnChange.setAlignmentX(Component.RIGHT_ALIGNMENT); btnChange.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgRegular(prescription.clone(), DlgRegular.MODE_CHANGE, new Closure() { @Override public void execute(Object o) { if (o != null) { Pair<Prescription, java.util.List<PrescriptionSchedule>> returnPackage = (Pair<Prescription, List<PrescriptionSchedule>>) o; EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); // Fetch the new prescription from the PAIR Prescription newPrescription = em.merge(returnPackage.getFirst()); Prescription oldPrescription = em.merge(prescription); em.lock(oldPrescription, LockModeType.OPTIMISTIC); // First close the old prescription DateTime now = new DateTime(); oldPrescription.setTo(now.toDate()); oldPrescription.setUserOFF(em.merge(OPDE.getLogin().getUser())); oldPrescription.setDocOFF(newPrescription.getDocON() == null ? null : em.merge(newPrescription.getDocON())); oldPrescription.setHospitalOFF(newPrescription.getHospitalON() == null ? null : em.merge(newPrescription.getHospitalON())); // the new prescription starts 1 second after the old one closes newPrescription.setFrom(now.plusSeconds(1).toDate()); // create new BHPs according to the prescription BHPTools.generate(em, newPrescription.getPrescriptionSchedule(), new LocalDate(), true); em.getTransaction().commit(); lstPrescriptions.remove(prescription); lstPrescriptions.add(oldPrescription); lstPrescriptions.add(newPrescription); Collections.sort(lstPrescriptions); // Refresh Display createCP4(oldPrescription); final CollapsiblePane myNewCP = createCP4(newPrescription); buildPanel(); GUITools.flashBackground(myNewCP, Color.YELLOW, 2); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } // buildPanel(); } } }); } }); btnChange.setEnabled(!prescription.isClosed() && !prescription.isOnDemand() && numBHPs != 0); pnlMenu.add(btnChange); /*** * ____ _ * / ___|| |_ ___ _ __ * \___ \| __/ _ \| '_ \ * ___) | || (_) | |_) | * |____/ \__\___/| .__/ * |_| */ final JButton btnStop = GUITools.createHyperlinkButton("nursingrecords.prescription.btnStop.tooltip", SYSConst.icon22playerStop, null); btnStop.setAlignmentX(Component.RIGHT_ALIGNMENT); btnStop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgDiscontinue(prescription, new Closure() { @Override public void execute(Object o) { if (o != null) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Prescription myPrescription = (Prescription) em.merge(o); em.lock(myPrescription.getResident(), LockModeType.OPTIMISTIC); em.lock(myPrescription, LockModeType.OPTIMISTIC); myPrescription.setTo(new Date()); em.getTransaction().commit(); lstPrescriptions.remove(prescription); lstPrescriptions.add(myPrescription); Collections.sort(lstPrescriptions); final CollapsiblePane myCP = createCP4(myPrescription); buildPanel(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100, new Closure() { @Override public void execute(Object o) { GUITools.flashBackground(myCP, Color.YELLOW, 2); } }); } }); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { em.getTransaction().rollback(); OPDE.fatal(e); } finally { em.close(); } } } }); } }); btnStop.setEnabled(!prescription.isClosed()); // && numBHPs != 0 pnlMenu.add(btnStop); /*** * _____ _ _ _ * | ____|__| (_) |_ * | _| / _` | | __| * | |__| (_| | | |_ * |_____\__,_|_|\__/ * */ final JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.prescription.btnEdit.tooltip", SYSConst.icon22edit3, null); btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT); btnEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (prescription.isOnDemand()) { new DlgOnDemand(prescription, new Closure() { @Override public void execute(Object o) { if (o != null) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); Prescription myPrescription = em.merge((Prescription) o); em.lock(myPrescription, LockModeType.OPTIMISTIC); Query queryDELBHP = em.createQuery( "DELETE FROM BHP bhp WHERE bhp.prescription = :prescription"); queryDELBHP.setParameter("prescription", myPrescription); queryDELBHP.executeUpdate(); em.getTransaction().commit(); lstPrescriptions.remove(prescription); lstPrescriptions.add(myPrescription); Collections.sort(lstPrescriptions); final CollapsiblePane myCP = createCP4(myPrescription); buildPanel(); synchronized (listUsedCommontags) { boolean reloadSearch = false; for (Commontags ctag : myPrescription.getCommontags()) { if (!listUsedCommontags.contains(ctag)) { listUsedCommontags.add(ctag); reloadSearch = true; } } if (reloadSearch) { prepareSearchArea(); } } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100, new Closure() { @Override public void execute(Object o) { GUITools.flashBackground(myCP, Color.YELLOW, 2); } }); } }); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } // buildPanel(); } } }); } else { new DlgRegular(prescription, DlgRegular.MODE_EDIT, new Closure() { @Override public void execute(Object o) { if (o != null) { Pair<Prescription, java.util.List<PrescriptionSchedule>> returnPackage = (Pair<Prescription, List<PrescriptionSchedule>>) o; EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); Prescription myPrescription = em.merge(returnPackage.getFirst()); em.lock(myPrescription, LockModeType.OPTIMISTIC); // delete whats not in the new prescription anymore for (PrescriptionSchedule schedule : returnPackage.getSecond()) { em.remove(em.merge(schedule)); } Query queryDELBHP = em.createQuery( "DELETE FROM BHP bhp WHERE bhp.prescription = :prescription"); queryDELBHP.setParameter("prescription", myPrescription); queryDELBHP.executeUpdate(); BHPTools.generate(em, myPrescription.getPrescriptionSchedule(), new LocalDate(), true); em.getTransaction().commit(); lstPrescriptions.remove(prescription); lstPrescriptions.add(myPrescription); Collections.sort(lstPrescriptions); final CollapsiblePane myCP = createCP4(myPrescription); buildPanel(); synchronized (listUsedCommontags) { boolean reloadSearch = false; for (Commontags ctag : myPrescription.getCommontags()) { if (!listUsedCommontags.contains(ctag)) { listUsedCommontags.add(ctag); reloadSearch = true; } } if (reloadSearch) { prepareSearchArea(); } } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100, new Closure() { @Override public void execute(Object o) { GUITools.flashBackground(myCP, Color.YELLOW, 2); } }); } }); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } // buildPanel(); } } }); } } }); btnEdit.setEnabled(!prescription.isClosed() && numBHPs == 0); pnlMenu.add(btnEdit); /*** * _ _ _____ _ ____ * | |__ | |_ _ _|_ _|/ \ / ___|___ * | '_ \| __| '_ \| | / _ \| | _/ __| * | |_) | |_| | | | |/ ___ \ |_| \__ \ * |_.__/ \__|_| |_|_/_/ \_\____|___/ * */ final JButton btnTAGs = GUITools.createHyperlinkButton("misc.msg.editTags", SYSConst.icon22tagPurple, null); btnTAGs.setAlignmentX(Component.RIGHT_ALIGNMENT); btnTAGs.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { final JidePopup popup = new JidePopup(); final JPanel pnl = new JPanel(new BorderLayout(5, 5)); final PnlCommonTags pnlCommonTags = new PnlCommonTags(prescription.getCommontags(), true, 3); pnl.add(new JScrollPane(pnlCommonTags), BorderLayout.CENTER); JButton btnApply = new JButton(SYSConst.icon22apply); pnl.add(btnApply, BorderLayout.SOUTH); btnApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); Prescription myPrescription = em.merge(prescription); em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT); // merging is important, hence no addAll() for this one ArrayList<Commontags> listTags2Add = new ArrayList<Commontags>(); for (Commontags tag2add : pnlCommonTags.getListSelectedTags()) { listTags2Add.add(em.merge(tag2add)); } // Annotations need to be added, tooo // these are the remaining tags, that need to be disconnected myPrescription.getCommontags().addAll(listTags2Add); ArrayList<Commontags> listTags2Remove = new ArrayList<Commontags>( myPrescription.getCommontags()); listTags2Remove.removeAll(listTags2Add); myPrescription.getCommontags().removeAll(listTags2Remove); ArrayList<ResInfo> annotations2remove = new ArrayList<ResInfo>(); for (Commontags commontag : listTags2Remove) { for (ResInfo annotation : myPrescription.getAnnotations()) { if (CommontagsTools.getTagForAnnotation(annotation).equals(commontag)) { annotations2remove.add(annotation); em.remove(annotation); } } } myPrescription.getAnnotations().removeAll(annotations2remove); em.getTransaction().commit(); lstPrescriptions.remove(prescription); lstPrescriptions.add(myPrescription); Collections.sort(lstPrescriptions); final CollapsiblePane myCP = createCP4(myPrescription); buildPanel(); synchronized (listUsedCommontags) { boolean reloadSearch = false; for (Commontags ctag : myPrescription.getCommontags()) { if (!listUsedCommontags.contains(ctag)) { listUsedCommontags.add(ctag); reloadSearch = true; } } if (reloadSearch) { prepareSearchArea(); } } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100, new Closure() { @Override public void execute(Object o) { GUITools.flashBackground(myCP, Color.YELLOW, 2); } }); } }); } catch (OptimisticLockException ole) { OPDE.warn(ole); OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } else { reloadDisplay(); } } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } }); popup.setMovable(false); popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS)); popup.setOwner(btnTAGs); popup.removeExcludedComponent(btnTAGs); pnl.setPreferredSize(new Dimension(350, 150)); popup.getContentPane().add(pnl); popup.setDefaultFocusComponent(pnl); GUITools.showPopup(popup, SwingConstants.WEST); } }); btnTAGs.setEnabled(!prescription.isClosed()); pnlMenu.add(btnTAGs); /*** * _ _ * __ _ _ __ _ __ ___ | |_ __ _| |_ ___ * / _` | '_ \| '_ \ / _ \| __/ _` | __/ _ \ * | (_| | | | | | | | (_) | || (_| | || __/ * \__,_|_| |_|_| |_|\___/ \__\__,_|\__\___| * */ final JButton btnAnnotation = GUITools.createHyperlinkButton( "nursingrecords.prescription.edit.annotations", SYSConst.icon22annotate, null); btnAnnotation.setAlignmentX(Component.RIGHT_ALIGNMENT); btnAnnotation.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { DlgAnnotations dlg = new DlgAnnotations(prescription, new Closure() { @Override public void execute(Object o) { if (o != null) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); ResInfo annotation = em.merge((ResInfo) o); annotation.setHtml(ResInfoTools.getContentAsHTML(annotation)); Prescription myPrescription = em.merge(prescription); em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT); myPrescription.getAnnotations().remove(annotation); // just in case, it was an EDIT rather than an ADD myPrescription.getAnnotations().add(annotation); em.lock(annotation, LockModeType.OPTIMISTIC); em.getTransaction().commit(); lstPrescriptions.remove(prescription); lstPrescriptions.add(myPrescription); Collections.sort(lstPrescriptions); final CollapsiblePane myCP = createCP4(myPrescription); buildPanel(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100, new Closure() { @Override public void execute(Object o) { GUITools.flashBackground(myCP, Color.YELLOW, 2); } }); } }); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } } }); OPDE.debug(lstPrescriptions); dlg.setVisible(true); } }); btnAnnotation.setEnabled(!prescription.isClosed() && prescription.hasMed() && PrescriptionTools.isAnnotationNecessary(prescription)); pnlMenu.add(btnAnnotation); } // checked for acls if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) { /*** * ____ _ _ * | _ \ ___| | ___| |_ ___ * | | | |/ _ \ |/ _ \ __/ _ \ * | |_| | __/ | __/ || __/ * |____/ \___|_|\___|\__\___| * */ final JButton btnDelete = GUITools.createHyperlinkButton( "nursingrecords.prescription.btnDelete.tooltip", SYSConst.icon22delete, null); btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT); btnDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/>" + PrescriptionTools.toPrettyString(prescription) + "</br>" + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() { @Override public void execute(Object answer) { if (answer.equals(JOptionPane.YES_OPTION)) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Prescription myverordnung = em.merge(prescription); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); em.lock(myverordnung, LockModeType.OPTIMISTIC); em.remove(myverordnung); Query delQuery = em.createQuery( "DELETE FROM BHP b WHERE b.prescription = :prescription"); delQuery.setParameter("prescription", myverordnung); delQuery.executeUpdate(); em.getTransaction().commit(); OPDE.getDisplayManager().addSubMessage( new DisplayMessage(SYSTools.xx("misc.msg.Deleted") + ": " + PrescriptionTools.toPrettyString(myverordnung))); lstPrescriptions.remove(prescription); buildPanel(); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { em.getTransaction().rollback(); OPDE.fatal(e); } finally { em.close(); } } } }); } }); btnDelete.setEnabled(numBHPs == 0 && !prescription.isClosed()); pnlMenu.add(btnDelete); } // checked for acls if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) { pnlMenu.add(new JSeparator()); /*** * ____ _ _____ _ ____ _ * / ___| ___| |_| ____|_ ___ __ (_)_ __ _ _| _ \ __ _| |_ ___ * \___ \ / _ \ __| _| \ \/ / '_ \| | '__| | | | | | |/ _` | __/ _ \ * ___) | __/ |_| |___ > <| |_) | | | | |_| | |_| | (_| | || __/ * |____/ \___|\__|_____/_/\_\ .__/|_|_| \__, |____/ \__,_|\__\___| * |_| |___/ */ final JButton btnExpiry = GUITools.createHyperlinkButton( "nursingrecords.inventory.tooltip.btnSetExpiry", SYSConst.icon22gotoEnd, null); btnExpiry.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { final JidePopup popup = new JidePopup(); popup.setMovable(false); PnlExpiry pnlExpiry = new PnlExpiry(stockInUse.getExpires(), SYSTools.xx("nursingrecords.inventory.pnlExpiry.title") + ": " + stockInUse.getID(), new Closure() { @Override public void execute(Object o) { popup.hidePopup(); EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); MedStock myStock = em.merge(stockInUse); em.lock(em.merge(myStock.getInventory().getResident()), LockModeType.OPTIMISTIC); em.lock(em.merge(myStock.getInventory()), LockModeType.OPTIMISTIC); myStock.setExpires((Date) o); em.getTransaction().commit(); createCP4(prescription); buildPanel(); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } }); popup.setOwner(btnExpiry); popup.setContentPane(pnlExpiry); popup.removeExcludedComponent(pnlExpiry); popup.setDefaultFocusComponent(pnlExpiry); GUITools.showPopup(popup, SwingConstants.WEST); } }); btnExpiry.setEnabled(inventory != null && stockInUse != null); pnlMenu.add(btnExpiry); /*** * ____ _ ____ _ _ * / ___| | ___ ___ ___/ ___|| |_ ___ ___| | __ * | | | |/ _ \/ __|/ _ \___ \| __/ _ \ / __| |/ / * | |___| | (_) \__ \ __/___) | || (_) | (__| < * \____|_|\___/|___/\___|____/ \__\___/ \___|_|\_\ * */ final JButton btnCloseStock = GUITools.createHyperlinkButton( "nursingrecords.inventory.stock.btnout.tooltip", SYSConst.icon22ledRedOn, null); btnCloseStock.setAlignmentX(Component.RIGHT_ALIGNMENT); btnCloseStock.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgCloseStock(stockInUse, new Closure() { @Override public void execute(Object o) { if (o != null) { // The prescription itself is not changed, but the stock in question. // this information is requested by a single DB request every time // the CP is created for that particular prescription. // A new call to the createCP4 method will reuse the old // CollapsiblePane and set a new TextContent to it. // Now with the MedStock information. // If this current stock was valid until the end of package // it needs to be reread here. if (prescription.isUntilEndOfPackage()) { EntityManager em = OPDE.createEM(); Prescription myPrescription = em.merge(prescription); em.refresh(myPrescription); lstPrescriptions.remove(prescription); lstPrescriptions.add(myPrescription); Collections.sort(lstPrescriptions); final CollapsiblePane myCP = createCP4(myPrescription); } else { final CollapsiblePane myCP = createCP4(prescription); GUITools.flashBackground(myCP, Color.YELLOW, 2); } buildPanel(); } } }); } }); btnCloseStock.setEnabled(inventory != null && stockInUse != null && !stockInUse.isToBeClosedSoon()); pnlMenu.add(btnCloseStock); /*** * ___ ____ _ _ * / _ \ _ __ ___ _ __ / ___|| |_ ___ ___| | __ * | | | | '_ \ / _ \ '_ \\___ \| __/ _ \ / __| |/ / * | |_| | |_) | __/ | | |___) | || (_) | (__| < * \___/| .__/ \___|_| |_|____/ \__\___/ \___|_|\_\ * |_| */ final JButton btnOpenStock = GUITools.createHyperlinkButton( "nursingrecords.inventory.stock.btnopen.tooltip", SYSConst.icon22ledGreenOn, null); btnOpenStock.setAlignmentX(Component.RIGHT_ALIGNMENT); btnOpenStock.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgOpenStock(prescription.getTradeForm(), resident, new Closure() { @Override public void execute(Object o) { if (o != null) { final CollapsiblePane myCP = createCP4(prescription); GUITools.flashBackground(myCP, Color.YELLOW, 2); } } }); } }); btnOpenStock.setEnabled(inventory != null && stockInUse == null && !prescription.isClosed()); pnlMenu.add(btnOpenStock); /*** * ____ _ _ _____ __ __ _ * / ___|(_) __| | ___| ____|/ _|/ _| ___ ___| |_ ___ * \___ \| |/ _` |/ _ \ _| | |_| |_ / _ \/ __| __/ __| * ___) | | (_| | __/ |___| _| _| __/ (__| |_\__ \ * |____/|_|\__,_|\___|_____|_| |_| \___|\___|\__|___/ * */ final JButton btnEditSideEffects = GUITools.createHyperlinkButton( "nursingrecords.prescription.edit.sideeffects", SYSConst.icon22sideeffects, null); btnEditSideEffects.setAlignmentX(Component.RIGHT_ALIGNMENT); btnEditSideEffects.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgYesNo(SYSConst.icon48sideeffects, new Closure() { @Override public void execute(Object o) { if (o != null) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); MedProducts myProduct = em.merge(prescription.getTradeForm().getMedProduct()); myProduct.setSideEffects(o.toString().trim()); for (TradeForm tf : myProduct.getTradeforms()) { em.lock(em.merge(tf), LockModeType.OPTIMISTIC_FORCE_INCREMENT); for (MedPackage mp : tf.getPackages()) { em.lock(em.merge(mp), LockModeType.OPTIMISTIC_FORCE_INCREMENT); } } em.lock(myProduct, LockModeType.OPTIMISTIC); em.getTransaction().commit(); reload(); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } } }, "nursingrecords.prescription.edit.sideeffects", prescription.getTradeForm().getMedProduct().getSideEffects(), null); } }); // checked for acls btnEditSideEffects.setEnabled(prescription.hasMed() && OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, "opde.medication")); pnlMenu.add(btnEditSideEffects); pnlMenu.add(new JSeparator()); /*** * _ _ _____ _ _ * | |__ | |_ _ __ | ___(_) | ___ ___ * | '_ \| __| '_ \| |_ | | |/ _ \/ __| * | |_) | |_| | | | _| | | | __/\__ \ * |_.__/ \__|_| |_|_| |_|_|\___||___/ * */ final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach, null); btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT); btnFiles.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { Closure closure = null; if (!prescription.isClosed()) { closure = new Closure() { @Override public void execute(Object o) { EntityManager em = OPDE.createEM(); final Prescription myPrescription = em.find(Prescription.class, prescription.getID()); em.close(); lstPrescriptions.remove(prescription); lstPrescriptions.add(myPrescription); Collections.sort(lstPrescriptions); final CollapsiblePane myCP = createCP4(myPrescription); buildPanel(); GUITools.flashBackground(myCP, Color.YELLOW, 2); } }; } btnFiles.setEnabled(OPDE.isFTPworking()); new DlgFiles(prescription, closure); } }); pnlMenu.add(btnFiles); /*** * _ _ ____ * | |__ | |_ _ __ | _ \ _ __ ___ ___ ___ ___ ___ * | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __| * | |_) | |_| | | | __/| | | (_) | (_| __/\__ \__ \ * |_.__/ \__|_| |_|_| |_| \___/ \___\___||___/___/ * */ final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip", SYSConst.icon22link, null); btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT); btnProcess.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgProcessAssign(prescription, new Closure() { @Override public void execute(Object o) { if (o == null) { return; } Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o; ArrayList<QProcess> assigned = result.getFirst(); ArrayList<QProcess> unassigned = result.getSecond(); EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); em.lock(em.merge(resident), LockModeType.OPTIMISTIC); Prescription myPrescription = em.merge(prescription); em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT); ArrayList<SYSPRE2PROCESS> attached = new ArrayList<SYSPRE2PROCESS>( prescription.getAttachedProcessConnections()); for (SYSPRE2PROCESS linkObject : attached) { if (unassigned.contains(linkObject.getQProcess())) { linkObject.getQProcess().getAttachedNReportConnections().remove(linkObject); linkObject.getPrescription().getAttachedProcessConnections() .remove(linkObject); em.merge(new PReport( SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": " + myPrescription.getTitle() + " ID: " + myPrescription.getID(), PReportTools.PREPORT_TYPE_REMOVE_ELEMENT, linkObject.getQProcess())); em.remove(linkObject); } } attached.clear(); for (QProcess qProcess : assigned) { List<QProcessElement> listElements = qProcess.getElements(); if (!listElements.contains(myPrescription)) { QProcess myQProcess = em.merge(qProcess); SYSPRE2PROCESS myLinkObject = em .merge(new SYSPRE2PROCESS(myQProcess, myPrescription)); em.merge(new PReport( SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": " + myPrescription.getTitle() + " ID: " + myPrescription.getID(), PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess)); qProcess.getAttachedPrescriptionConnections().add(myLinkObject); myPrescription.getAttachedProcessConnections().add(myLinkObject); } } em.getTransaction().commit(); lstPrescriptions.remove(prescription); lstPrescriptions.add(myPrescription); Collections.sort(lstPrescriptions); final CollapsiblePane myCP = createCP4(myPrescription); buildPanel(); GUITools.flashBackground(myCP, Color.YELLOW, 2); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (RollbackException ole) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } }); } }); btnProcess.setEnabled(!prescription.isClosed()); // if (!prescription.getAttachedProcessConnections().isEmpty()) { // JLabel lblNum = new JLabel(Integer.toString(prescription.getAttachedProcessConnections().size()), SYSConst.icon16redStar, SwingConstants.CENTER); // lblNum.setFont(SYSConst.ARIAL10BOLD); // lblNum.setForeground(Color.YELLOW); // lblNum.setHorizontalTextPosition(SwingConstants.CENTER); // DefaultOverlayable overlayableBtn = new DefaultOverlayable(btnProcess, lblNum, DefaultOverlayable.SOUTH_EAST); // overlayableBtn.setOpaque(false); // pnlMenu.add(overlayableBtn); // } else { pnlMenu.add(btnProcess); // } } return pnlMenu; }
From source file:com.app.rest.ExperianIntegrationService.java
@POST @Path("/landingPageSubmit") @Produces({ MediaType.APPLICATION_JSON }) @Consumes(MediaType.APPLICATION_JSON)//from w w w . java 2 s . c om public ResponseModel getlandingPageDetails(String inputJsonObj) { //BasicConfigurator.configure(); String logMarker = null; ResponseModel responseMap = new ResponseModel(); try { //String requestParams = (String) inputJsonObj.get("input"); Map map = parseJson(inputJsonObj); logger.info("getlandingPageDetails ~ " + map.get("LOG_MARKER") == null ? "NOT_GIVEN" : map.get("LOG_MARKER") + " ~Entry"); logMarker = map.get("LOG_MARKER").toString(); //String voucherCode = "CMD1UjUz9"; if (map.get("clientName").toString() == null) { responseMap.setErrorMessage("Client Name is blank"); return responseMap; } ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("clientName", map.get("clientName").toString())); params.add(new BasicNameValuePair("allowInput", map.get("allowInput").toString())); params.add(new BasicNameValuePair("allowEdit", map.get("allowEdit").toString())); params.add(new BasicNameValuePair("allowCaptcha", map.get("allowCaptcha").toString())); params.add(new BasicNameValuePair("allowConsent", map.get("allowConsent").toString())); params.add(new BasicNameValuePair("allowConsent_additional", map.get("allowConsent_additional").toString())); params.add(new BasicNameValuePair("allowEmailVerify", map.get("allowEmailVerify").toString())); params.add(new BasicNameValuePair("allowVoucher", map.get("allowVoucher").toString())); params.add(new BasicNameValuePair("voucherCode", map.get("voucherCode").toString())); params.add(new BasicNameValuePair("firstName", map.get("firstName").toString())); params.add(new BasicNameValuePair("surname", map.get("surName").toString())); params.add(new BasicNameValuePair("dateOfBirth", map.get("dateOfBirth").toString())); params.add(new BasicNameValuePair("gender", map.get("gender").toString())); params.add(new BasicNameValuePair("mobileNo", map.get("mobileNo").toString())); params.add(new BasicNameValuePair("email", map.get("email").toString())); params.add(new BasicNameValuePair("flatno", map.get("flatno").toString())); params.add(new BasicNameValuePair("city", map.get("city").toString())); params.add(new BasicNameValuePair("state", map.get("state").toString())); params.add(new BasicNameValuePair("pincode", map.get("pincode").toString())); params.add(new BasicNameValuePair("pan", map.get("pan").toString())); params.add(new BasicNameValuePair("reason", map.get("reason").toString())); params.add(new BasicNameValuePair("middleName", map.get("middleName").toString())); params.add(new BasicNameValuePair("telephoneNo", map.get("telephoneNo").toString())); params.add(new BasicNameValuePair("telephoneType", map.get("telephoneType").toString())); params.add(new BasicNameValuePair("passport", map.get("passport").toString())); params.add(new BasicNameValuePair("voterid", map.get("voterid").toString())); params.add(new BasicNameValuePair("aadhaar", map.get("aadhaar").toString())); params.add(new BasicNameValuePair("driverlicense", map.get("driverlicense").toString())); String request = getQuery(params); String jsessionId = HttpConnection.landingPageSubmit(request); String stageOneRequestId = HttpConnection.openCustomerDetailsFormAction(jsessionId, ""); responseMap.setuniqueId(stageOneRequestId.toString()); logger.info("getlandingPageDetails ~ " + (map.get("LOG_MARKER") == null ? "NOT_GIVEN" : map.get("LOG_MARKER")) + " ~ request : " + (request == null ? "null" : request) + " jsessionId: " + (jsessionId == null ? "null" : jsessionId) + " stageOneRequestId: " + (stageOneRequestId == null ? "null" : stageOneRequestId) + "~ Log Marker 1"); params.clear(); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("clientName", map.get("clientName").toString())); params.add(new BasicNameValuePair("allowInput", map.get("allowInput").toString())); params.add(new BasicNameValuePair("allowEdit", map.get("allowEdit").toString())); params.add(new BasicNameValuePair("allowCaptcha", map.get("allowCaptcha").toString())); params.add(new BasicNameValuePair("allowConsent", map.get("allowConsent").toString())); params.add(new BasicNameValuePair("allowConsent_additional", map.get("allowConsent_additional").toString())); params.add(new BasicNameValuePair("allowEmailVerify", map.get("allowEmailVerify").toString())); params.add(new BasicNameValuePair("allowVoucher", map.get("allowVoucher").toString())); params.add(new BasicNameValuePair("voucherCode", map.get("voucherCode").toString())); params.add(new BasicNameValuePair("firstName", map.get("firstName").toString())); params.add(new BasicNameValuePair("surname", map.get("surName").toString())); params.add(new BasicNameValuePair("dob", map.get("dateOfBirth").toString())); params.add(new BasicNameValuePair("gender", map.get("gender").toString())); params.add(new BasicNameValuePair("mobileNo", map.get("mobileNo").toString())); params.add(new BasicNameValuePair("email", map.get("email").toString())); params.add(new BasicNameValuePair("flatPlotHouseNo", map.get("flatno").toString())); params.add(new BasicNameValuePair("city", map.get("city").toString())); params.add(new BasicNameValuePair("state", map.get("stateid").toString())); params.add(new BasicNameValuePair("pincode", map.get("pincode").toString())); params.add(new BasicNameValuePair("panNo", map.get("pan").toString())); params.add(new BasicNameValuePair("reason", map.get("reason").toString())); params.add(new BasicNameValuePair("requestReason", map.get("reason").toString())); params.add(new BasicNameValuePair("middleName", map.get("middleName").toString())); params.add(new BasicNameValuePair("telephoneNo", map.get("telephoneNo").toString())); params.add(new BasicNameValuePair("telephoneType", map.get("telephoneType").toString())); params.add(new BasicNameValuePair("passportNo", map.get("passport").toString())); params.add(new BasicNameValuePair("voterIdNo", map.get("voterid").toString())); params.add(new BasicNameValuePair("universalIdNo", map.get("aadhaar").toString())); params.add(new BasicNameValuePair("driverLicenseNo", map.get("driverlicense").toString())); params.add(new BasicNameValuePair("hitId", stageOneRequestId)); request = getQuery(params); logger.info("getlandingPageDetails ~ " + (map.get("LOG_MARKER") == null ? "NOT_GIVEN" : map.get("LOG_MARKER")) + " ~ request : " + (request == null ? "null" : request) + " jsessionId: " + (jsessionId == null ? "null" : jsessionId) + " stageOneRequestId: " + (stageOneRequestId == null ? "null" : stageOneRequestId) + "~ Log Marker 2"); HttpConnection.fetchScreenMetaDataAction(jsessionId, request); String resp = HttpConnection.submitRequest(jsessionId, request); logger.info("getlandingPageDetails ~ " + (map.get("LOG_MARKER") == null ? "NOT_GIVEN" : map.get("LOG_MARKER")) + " ~ request : " + (request == null ? "null" : request) + " jsessionId: " + (jsessionId == null ? "null" : jsessionId) + " stageOneRequestId: " + (stageOneRequestId == null ? "null" : stageOneRequestId) + " resp: " + (resp == null ? "null" : resp) + "~ Log Marker 4"); if (resp == null) { responseMap.setErrorMessage("RESPONSE_NULL"); return responseMap; } if (resp.equals("")) { responseMap.setErrorMessage("RESPONSE_BLANK"); return responseMap; } if (resp.startsWith("error")) { responseMap.setErrorMessage(resp.replace("error ", "")); return responseMap; } params.clear(); String stageTwoRequestId = HttpConnection.directCRQRequest(resp, jsessionId, params); logger.info("getlandingPageDetails ~ " + (map.get("LOG_MARKER") == null ? "NOT_GIVEN" : map.get("LOG_MARKER")) + " ~ request : " + (request == null ? "null" : request) + " jsessionId: " + (jsessionId == null ? "null" : jsessionId) + " stageOneRequestId: " + (stageOneRequestId == null ? "null" : stageOneRequestId) + " stageTwoRequestId: " + (stageTwoRequestId == null ? "null" : stageTwoRequestId) + "~ Log Marker 5"); params.add(new BasicNameValuePair("captchCode", "-999")); params.add(new BasicNameValuePair("payFlag", "true")); params.add(new BasicNameValuePair("voucherCode", map.get("voucherCode").toString())); params.add(new BasicNameValuePair("stgOneHitId", stageOneRequestId)); params.add(new BasicNameValuePair("stgTwoHitId", stageTwoRequestId)); request = getQuery(params); String jsessionIdResp = HttpConnection.paymentSubmitRequest(request); logger.info("getlandingPageDetails ~ " + (map.get("LOG_MARKER") == null ? "NOT_GIVEN" : map.get("LOG_MARKER")) + " ~ request : " + (request == null ? "null" : request) + " jsessionId: " + (jsessionId == null ? "null" : jsessionId) + " stageOneRequestId: " + (stageOneRequestId == null ? "null" : stageOneRequestId) + " stageTwoRequestId: " + (stageTwoRequestId == null ? "null" : stageTwoRequestId) + " jsessionIdResp: " + (jsessionIdResp == null ? "null" : jsessionIdResp) + "~ Log Marker 6"); if (jsessionIdResp.equalsIgnoreCase("customError")) { responseMap.setErrorMessage(jsessionIdResp); logger.info("getlandingPageDetails ~ " + (map.get("LOG_MARKER") == null ? "NOT_GIVEN" : map.get("LOG_MARKER")) + "~ customError ~ Log Marker 6"); return responseMap; } if (jsessionIdResp.equalsIgnoreCase("Invalid Voucher Code")) { responseMap.setErrorMessage("voucherExpired"); logger.info("getlandingPageDetails ~ " + (map.get("LOG_MARKER") == null ? "NOT_GIVEN" : map.get("LOG_MARKER")) + "~ voucherExpired ~ Log Marker 6"); return responseMap; } String responseJson = null; String message = ""; String answer = ""; String qId = ""; while (true) { logger.info("getlandingPageDetails ~ " + (map.get("LOG_MARKER") == null ? "NOT_GIVEN" : map.get("LOG_MARKER")) + "~ Log Marker 6"); params.clear(); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("stgOneHitId", stageOneRequestId)); params.add(new BasicNameValuePair("stgTwoHitId", stageTwoRequestId)); request = getQuery(params); Map questionMap = HttpConnection.generateQuestionForConsumer(jsessionIdResp, request); responseJson = (String) questionMap.get("responseJson"); logger.info("getlandingPageDetails ~ " + (map.get("LOG_MARKER") == null ? "NOT_GIVEN" : map.get("LOG_MARKER")) + " ~ request : " + (request == null ? "null" : request) + " jsessionId: " + (jsessionId == null ? "null" : jsessionId) + " stageOneRequestId: " + (stageOneRequestId == null ? "null" : stageOneRequestId) + " stageTwoRequestId: " + (stageTwoRequestId == null ? "null" : stageTwoRequestId) + " responseJson: " + (responseJson == null ? "null" : responseJson) + "~ Log Marker 7"); if (responseJson.equalsIgnoreCase("passedReport")) { String pdfData = (String) questionMap.get("showHtmlReportForCreditReport"); Document doc = Jsoup.parse(pdfData); Element input = doc.select("input[name=xmlResponse]").first(); String response = input.attr("value"); responseMap.setXmlResponse(response); } if (responseJson.equalsIgnoreCase("next")) { questionMap.put("jsessionId2", jsessionIdResp); responseMap.setResponseMap(questionMap); } if (responseJson.equalsIgnoreCase("systemError")) { responseMap.setErrorMessage("systemError"); } if (responseJson.equalsIgnoreCase("inCorrectAnswersGiven")) { responseMap.setErrorMessage("inCorrectAnswersGiven"); } if (responseJson.equalsIgnoreCase("insufficientQuestion")) { responseMap.setErrorMessage("insufficientQuestion"); } if (responseJson.equalsIgnoreCase("creditReportEmpty")) { responseMap.setErrorMessage("creditReportEmpty"); } if (responseJson.equalsIgnoreCase("error")) { responseMap.setErrorMessage("error"); } return responseMap; } } catch (Exception e) { logger.info("getlandingPageDetails ~ " + (logMarker == null ? "NOT_GIVEN" : logMarker) + e.toString() + "~ Log Marker 8 "); responseMap.setErrorMessage("Error occured"); responseMap.setExceptionString(e.toString()); return responseMap; } }