List of usage examples for java.util ArrayList removeAll
public boolean removeAll(Collection<?> c)
From source file:org.kuali.student.myplan.course.controller.CourseSearchController.java
/** * Gets the CluIds from the given search requests * * @param requests//from w ww.j a v a 2s. com * @return * @throws MissingParameterException */ public ArrayList<Hit> processSearchRequests(List<SearchRequestInfo> requests) throws MissingParameterException { logger.info("Start of processSearchRequests of CourseSearchController:" + System.currentTimeMillis()); ArrayList<Hit> hits = new ArrayList<Hit>(); ArrayList<Hit> tempHits = new ArrayList<Hit>(); List<String> courseIds = new ArrayList<String>(); for (SearchRequestInfo request : requests) { SearchResultInfo searchResult = null; try { searchResult = getLuService().search(request, CourseSearchConstants.CONTEXT_INFO); } catch (InvalidParameterException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (OperationFailedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (PermissionDeniedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } for (SearchResultRow row : searchResult.getRows()) { String id = SearchHelper.getCellValue(row, "lu.resultColumn.cluId"); if (!courseIds.contains(id)) { /* hitCourseID(courseMap, id);*/ courseIds.add(id); Hit hit = new Hit(id); tempHits.add(hit); } } tempHits.removeAll(hits); hits.addAll(tempHits); tempHits.clear(); } logger.info("End of processSearchRequests of CourseSearchController:" + System.currentTimeMillis()); return hits; }
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;//from ww w.jav a2 s. c om 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:net.cbtltd.rest.AbstractReservation.java
/** * Gets the search products.//from w ww.j av a 2 s. com * * @param locationid the locationid * @param fromdate the fromdate * @param todate the todate * @param pos the pos * @param currency the currency * @param terms the terms * @param xsl the xsl * @return the quotes */ public static synchronized SearchResponse getSearchProducts(String locationid, String fromdate, String todate, String productid, String guests, Boolean exactmatch, Boolean inquireonly, Boolean commission, String pos, String currency, Boolean terms, Boolean amenities, String page, String perpage, String xsl) { Date timestamp = new Date(); LocalDate currentDate = new LocalDate(); String message = "/search/quotes/" + locationid + "/" + fromdate + "/" + todate + "?pos=" + pos + "¤cy=" + currency + "&terms=" + terms + "&amenity" + amenities + "&page" + page + "&perpage" + perpage + "&xsl=" + xsl; //LOG.debug(message); SqlSession sqlSession = RazorServer.openSession(); SearchResponse response = new SearchResponse(); SearchQuotes result = null; List<Quote> filteredQuotes = null; List<Quote> listQuotes = null; Integer guestCount = 0; try { String[] locationids = locationid.split(","); if (!guests.isEmpty()) { guestCount = Integer.parseInt(guests); } LocalDate parsedFromDate = new LocalDate(Constants.parseDate(fromdate)); if (parsedFromDate.isBefore(currentDate)) { throw new Exception("Invalid from date parameter."); } if (locationids != null && locationids.length > 0) { ArrayList<String> itemsWithPrice = null; if (inquireonly) { itemsWithPrice = sqlSession.getMapper(ProductMapper.class) .inquireonlyidsbyparentlocationandprice(locationids[0], fromdate, todate); } else { itemsWithPrice = sqlSession.getMapper(ProductMapper.class) .idsbyparentlocationandprice(locationids[0], fromdate, todate); } ArrayList<String> itemsWithCollision = sqlSession.getMapper(ProductMapper.class) .idswithreservationcollision(locationids[0], fromdate, todate); if (itemsWithPrice != null) { itemsWithPrice.removeAll(itemsWithCollision); if (itemsWithPrice.size() > 0) { if (!productid.isEmpty()) { listQuotes = new ArrayList<Quote>(); if (itemsWithPrice.contains(productid)) { ArrayList<String> product = new ArrayList<String>(); product.add(productid); listQuotes = getProductsQuotes(sqlSession, pos, product, fromdate, todate, guestCount, exactmatch, currency, terms); } } else { listQuotes = getProductsQuotes(sqlSession, pos, itemsWithPrice, fromdate, todate, guestCount, exactmatch, currency, terms); } } if (listQuotes != null) { if (!page.isEmpty() && !perpage.isEmpty()) { Integer pageInt = Integer.parseInt(page); Integer perPageInt = Integer.parseInt(perpage); Integer offset = (pageInt - 1) * perPageInt; if (offset > listQuotes.size()) { throw new Exception("Invalid page number."); } Integer endOffset = ((listQuotes.size() - offset) > perPageInt) ? offset + perPageInt : listQuotes.size(); filteredQuotes = listQuotes.subList(offset, endOffset); } else { filteredQuotes = listQuotes; } Map<String, Quote> quotesMap = new HashMap<String, Quote>(); for (Quote item : filteredQuotes) { if (!commission) { item.setAgentCommission(null); item.setAgentCommissionValue(null); } quotesMap.put(item.getProductid(), item); item.getAttributes().add(""); } if (!quotesMap.keySet().isEmpty()) { if (amenities) { List<Relation> attributes = sqlSession.getMapper(RelationMapper.class) .headidsattributes(new ArrayList<String>(quotesMap.keySet())); if (attributes != null && !attributes.isEmpty()) { for (Relation relation : attributes) { String attribute = relation.getLineid(); Quote quote = quotesMap.get(relation.getHeadid()); if (attribute.startsWith("PCT") && StringUtils.isEmpty(quote.getProductClassType())) { quote.setProductClassType(attribute); } else { quote.getAttributes().add(attribute); } } } } else { List<Relation> productTypes = sqlSession.getMapper(RelationMapper.class) .productsclasstype(new ArrayList<String>(quotesMap.keySet())); if (productTypes != null && !productTypes.isEmpty()) { String attribute = productTypes.get(0).getLineid(); Quote quote = quotesMap.get(productTypes.get(0).getHeadid()); if (quote != null) { quote.setProductClassType(attribute); } } } } } result = new SearchQuotes(null, locationid, null, filteredQuotes, xsl); if (listQuotes != null) { result.setQuotesCount(String.valueOf(listQuotes.size())); } else { result.setQuotesCount("0"); } result.setQuotesPerPage(perpage); result.setPageNumber(page); } } } catch (Throwable x) { LOG.error(message + "\n" + x.getMessage()); result = new SearchQuotes(null, locationid, message + " " + x.getMessage(), null, xsl); response.setErrorMessage(x.getMessage()); } finally { sqlSession.close(); } LOG.debug(result); MonitorService.monitor(message, timestamp); response.setSearchQuotes(result); return response; }
From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java
private void init(int how) throws GSSException, SSLException { /*DEL/*from ww w .j a v a 2 s . c om*/ short [] cs; if (this.encryption) { // always make sure to add NULL cipher at the end short [] ciphers = this.policy.getCipherSuites(); short [] newCiphers = new short[ciphers.length + 1]; System.arraycopy(ciphers, 0, newCiphers, 0, ciphers.length); newCiphers[ciphers.length] = SSLPolicyInt.TLS_RSA_WITH_NULL_MD5; cs = newCiphers; } else { // encryption not requested - accept only one cipher // XXX: in the future might want to iterate through // all cipher and enable only the null encryption ones cs = NO_ENCRYPTION; } this.policy.setCipherSuites(cs); this.policy.requireClientAuth(this.requireClientAuth.booleanValue()); this.policy.setAcceptNoClientCert(this.acceptNoClientCerts.booleanValue()); setTrustedCertificates(); this.in = new TokenInputStream(); this.out = new ByteArrayOutputStream(); try { this.conn = new SSLConn(null, this.in, this.out, this.context, how); } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.conn.init(); */ try { // set trust parameters in SSLConfigurator if (this.tc == null) { KeyStore trustStore = Stores.getDefaultTrustStore(); sslConfigurator.setTrustAnchorStore(trustStore); CertStore crlStore = Stores.getDefaultCRLStore(); sslConfigurator.setCrlStore(crlStore); ResourceSigningPolicyStore sigPolStore = Stores.getDefaultSigningPolicyStore(); sslConfigurator.setPolicyStore(sigPolStore); } this.sslConfigurator.setRejectLimitProxy(rejectLimitedProxy); if (proxyPolicyHandlers != null) sslConfigurator.setHandlers(proxyPolicyHandlers); this.sslContext = this.sslConfigurator.getSSLContext(); this.sslEngine = this.sslContext.createSSLEngine(); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } if (this.forceSSLv3AndConstrainCipherSuitesForGram.booleanValue()) this.sslEngine.setEnabledProtocols(GRAM_PROTOCOLS); else this.sslEngine.setEnabledProtocols(ENABLED_PROTOCOLS); logger.debug("SUPPORTED PROTOCOLS: " + Arrays.toString(this.sslEngine.getSupportedProtocols()) + "; ENABLED PROTOCOLS: " + Arrays.toString(this.sslEngine.getEnabledProtocols())); ArrayList<String> cs = new ArrayList(); if (this.encryption) { if (this.forceSSLv3AndConstrainCipherSuitesForGram.booleanValue()) for (String cipherSuite : GRAM_ENCRYPTION_CIPHER_SUITES) cs.add(cipherSuite); else // Simply retain the default-enabled Cipher Suites cs.addAll(Arrays.asList(this.sslEngine.getEnabledCipherSuites())); } else { if (this.forceSSLv3AndConstrainCipherSuitesForGram.booleanValue()) for (String cipherSuite : GRAM_NO_ENCRYPTION_CIPHER_SUITES) cs.add(cipherSuite); else { for (String cipherSuite : NO_ENCRYPTION) cs.add(cipherSuite); cs.addAll(Arrays.asList(this.sslEngine.getEnabledCipherSuites())); } } cs.removeAll(Arrays.asList(bannedCiphers)); String[] testSuite = new String[0]; this.sslEngine.setEnabledCipherSuites(cs.toArray(testSuite)); logger.debug("CIPHER SUITE IS: " + Arrays.toString(this.sslEngine.getEnabledCipherSuites())); // TODO: Document the following behavior // NOTE: requireClientAuth Vs. acceptNoClientCerts // which one takes precedence? for now err on the side of security if (this.requireClientAuth.booleanValue() == Boolean.TRUE) { this.sslEngine.setNeedClientAuth(this.requireClientAuth.booleanValue()); } else this.sslEngine.setWantClientAuth(!this.acceptNoClientCerts.booleanValue()); this.sslEngine.setUseClientMode(how == INITIATE); this.certFactory = BouncyCastleCertProcessingFactory.getDefault(); this.state = HANDSHAKE; int appSize = sslEngine.getSession().getApplicationBufferSize(); this.outByteBuff = ByteBuffer.allocate(appSize); this.sslEngine.beginHandshake(); }
From source file:structuredoutputcbr.adaptation.Adaptation.java
/** * Fill the planning with a given set of exercises * @param type The type of a planning split or full body * @param new_exercise_set the set of exercises to use * @param new_planning a reference to the planning *//*from w ww. ja v a 2 s . co m*/ private void fillPlanning(String type, ArrayList<CaseBlock> new_exercise_set, ArrayList<CaseBlock> new_planning) { //Hash map that stores the days where are assigned the primary zone exercises in the case of full body HashMap<OntologyElement, Integer> primary_exercise_days = new HashMap(); Collections.sort(new_exercise_set, new CompareCaseBlocks()); ArrayList<OntologyElement> used_muscular_groups = new ArrayList(); used_muscular_groups.add(StructuredOutputCBR.ontology.getElement("pectorales")); used_muscular_groups.addAll(StructuredOutputCBR.ontology.getElement("espalda").getDirectChildren()); used_muscular_groups.addAll(StructuredOutputCBR.ontology.getElement("piernas").getDirectChildren()); Collections.shuffle(used_muscular_groups, new Random(42)); for (CaseBlock exercise_cb : new_exercise_set) { OntologyElement exercise = exercise_cb.getAttributeOntology(this.exercise_key, 0); used_muscular_groups = (ArrayList<OntologyElement>) CollectionUtils.union(used_muscular_groups, exercise.getRelationValues("muscular groups")); } Collections.sort(used_muscular_groups, new ComparatorMuscles()); Collections.sort(used_muscular_groups, new ComparePrimary()); //Fill the planning if is type split if (type.equalsIgnoreCase("split")) { for (OntologyElement group : used_muscular_groups) { int prefered_day = this.getIndexDayWithLessExercises(new_planning); OntologyElement primary = this.isPrimary(group); if (primary == null) { ArrayList<CaseBlock> specific_exercises = this .getAllExercisesFromMuscularGroup(new_exercise_set, group); for (CaseBlock specific_ex : specific_exercises) { if (!this.isAPrimaryGroupExercise(specific_ex)) { new_planning.get(prefered_day).addAttributeContent(this.program_key, specific_ex); new_exercise_set.remove(specific_ex); } } } else { if (primary_exercise_days.keySet().contains(primary)) { prefered_day = primary_exercise_days.get(primary); } else { boolean otherPrimaryDay = true; while (otherPrimaryDay) { prefered_day = (prefered_day + 1) % new_planning.size(); otherPrimaryDay = false; for (OntologyElement key : primary_exercise_days.keySet()) { if (primary_exercise_days.get(key) == prefered_day) { otherPrimaryDay = true; } } } } ArrayList<CaseBlock> exercises_primary = this.getAllExercisesFromMuscularGroup(new_exercise_set, group); new_planning.get(prefered_day).addAttributeContent(this.program_key, exercises_primary); new_exercise_set.removeAll(this.getAllExercisesFromMuscularGroup(new_exercise_set, group)); primary_exercise_days.put(primary, prefered_day); } } //fill the planning if is type split } else { Random rnd = new Random(42); for (OntologyElement group : used_muscular_groups) { ArrayList<CaseBlock> specific_exercises = this.getAllExercisesFromMuscularGroup(new_exercise_set, group); ArrayList<Integer> days = this.new_case.getDescription().getAttributeIntegers(this.shedule_key); Collections.shuffle(days, rnd); while (!specific_exercises.isEmpty()) { for (Integer day : days) { if (specific_exercises.isEmpty()) { break; } CaseBlock exercise = specific_exercises.remove(0); this.new_case.getSolution().getAttributeComponents(this.planning_key).get(day) .addAttributeContent(this.program_key, exercise); new_exercise_set.remove(exercise); } } } } }
From source file:pltag.corpus.ConnectionPathCalculator.java
/** * Calculates which prediction trees need to be generated from the set of connectionNodes. * And combines prediction trees if possible. * /*from w w w . j a va 2 s .c o m*/ * @param currentLeafNumber * @param lexicon * @return */ @SuppressWarnings("unchecked") // cast to Collection<String> private List<PredictionStringTree> generatePredictionTrees(int currentLeafNumber, List<StringTree> lexicon) {//, String leaf) { //if (currentLeafNumber.equals("6")) //System.out.print(""); MultiValueMap predictionTreeNodeMap = findNodesWithGreaterLeafnumbers(currentLeafNumber); ArrayList<PredictionStringTree> localPredictedTrees = new ArrayList<PredictionStringTree>(); int sourcetreeno = 0; ArrayList<PredictionStringTree> unhelpfulpredtrees = new ArrayList<PredictionStringTree>(); HashMap<Integer, Integer> translations = new HashMap<Integer, Integer>(); //System.out.println("prediction tree to connect leaf " + currentLeafNumber + " number of pred trees needed: "+ predictionTreeNodeMap.size()); //System.out.println("nodes needed: "+predictionTreeNodeMap); for (Integer predictionTreeOrigin : (Collection<Integer>) predictionTreeNodeMap.keySet()) { ElementaryStringTree originalStringTree = (ElementaryStringTree) sentenceWordLex[predictionTreeOrigin]; // ElementaryStringTree originalStringTree = (ElementaryStringTree) sentenceWordLex[Integer.parseInt(predictionTreeOrigin)]; if (originalStringTree == null) { continue; } originalStringTree.makeLexiconEntry(); if (originalStringTree.categories[originalStringTree.root] != null) // if (originalStringTree.categories[Integer.parseInt(originalStringTree.root)] != null) { translations.putAll(originalStringTree.removeUnaryNodes(originalStringTree.root)); } else { translations.putAll(originalStringTree.removeUnaryNodes(originalStringTree.coordanchor)); } if (originalStringTree.getAnchor() == Integer.MIN_VALUE && originalStringTree.treeString.startsWith("*")) // if (originalStringTree.getAnchor().equals("") && originalStringTree.treeString.startsWith("*")) { continue; } Collection<Integer> cn = predictionTreeNodeMap.getCollection(predictionTreeOrigin); PredictionStringTree predictionTree = buildPredictionTree(originalStringTree, cn, currentLeafNumber); // PredictionStringTree predictionTree = buildPredictionTree(originalStringTree, cn, Integer.parseInt(currentLeafNumber)); predictionTree.cutTail(cn); if (predictionTree.hasUsefulNodes(cn, translations)) { predictionTree = buildPredictionTree(originalStringTree, cn, currentLeafNumber); // predictionTree = buildPredictionTree(originalStringTree, cn, Integer.parseInt(currentLeafNumber)); sourcetreeno++; //System.out.println(predictionTree.print()); ArrayList<PredictionStringTree> newlist = new ArrayList<PredictionStringTree>(); ArrayList<PredictionStringTree> removelist = new ArrayList<PredictionStringTree>(); // combine prediction trees (trees can always be combined! I think.) for (PredictionStringTree otherTree : localPredictedTrees) { PredictionStringTree ct = combinePredTrees(predictionTree, otherTree, predictionTreeNodeMap.values(), translations);//.copyPred(); if (ct != null) { removelist.add(otherTree); removelist.add(predictionTree); newlist.remove(predictionTree); newlist.add(ct); predictionTree = ct; } } if (predictionTree.isAuxtree()) { localPredictedTrees.add(predictionTree); } else { localPredictedTrees.add(0, predictionTree); } localPredictedTrees.removeAll(removelist); // might add too much here. for (PredictionStringTree npt : newlist) { if (predictionTree.isAuxtree()) { localPredictedTrees.add(npt); } else { localPredictedTrees.add(0, npt); } } } else { predictionTree = buildPredictionTree(originalStringTree, cn, currentLeafNumber); // predictionTree = buildPredictionTree(originalStringTree, cn, Integer.parseInt(currentLeafNumber)); unhelpfulpredtrees.add(predictionTree); } } if (localPredictedTrees.isEmpty() & unhelpfulpredtrees.size() > 0) { PredictionStringTree first = null; int min = Integer.MAX_VALUE; // String others = ""; for (PredictionStringTree pt : unhelpfulpredtrees) { if (pt.isAuxtree()) { continue; } int anchorpos = pt.getAnchorList().get(0); // int anchorpos = Integer.parseInt(pt.getAnchorList().get(0)); if (anchorpos < min) { min = anchorpos; if (first != null) // others += " @ "+first.toString(); { first = pt; } } // else{ // if (first !=null) // others += " @ "+first.toString(); // } } if (first != null) { // System.out.println(first+"\t"+others); localPredictedTrees.add(first); } } //*/ if (localPredictedTrees.size() > 1) { PredictionStringTree predictionTree = localPredictedTrees.get(0); ArrayList<PredictionStringTree> newlist = new ArrayList<PredictionStringTree>(); ArrayList<PredictionStringTree> removelist = new ArrayList<PredictionStringTree>(); for (int i = 1; i < localPredictedTrees.size(); i++) { PredictionStringTree otherTree = localPredictedTrees.get(i); PredictionStringTree ct = combinePredTrees(predictionTree, otherTree, predictionTreeNodeMap.values(), translations);//.copyPred(); if (ct != null) { removelist.add(otherTree); removelist.add(predictionTree); newlist.remove(predictionTree); newlist.add(ct); predictionTree = ct; } } if (predictionTree.isAuxtree()) { localPredictedTrees.add(predictionTree); } else { localPredictedTrees.add(0, predictionTree); } localPredictedTrees.removeAll(removelist); // might add too much here. for (PredictionStringTree npt : newlist) { if (predictionTree.isAuxtree()) { localPredictedTrees.add(npt); } else { localPredictedTrees.add(0, npt); } } } for (PredictionStringTree pst : localPredictedTrees) { pst.cutTail(predictionTreeNodeMap.values()); } if (localPredictedTrees.size() > 1) { LogInfo.error("unaccounted case! combination of prediction trees; number of trees: " + sourcetreeno + " to connect leaf " + currentLeafNumber); } // noOfSources.put(sourcetreeno + "", noOfSources.get(sourcetreeno + "").intValue() + 1); noOfSources.put(sourcetreeno, noOfSources.get(sourcetreeno) + 1); return localPredictedTrees; }
From source file:org.opendatakit.security.server.SecurityServiceUtil.java
/** * Method to enforce an access configuration constraining only registered users, authenticated * users and anonymous access./*www . jav a 2s .c om*/ * * Add additional checks of the incoming parameters and patch things up if the incoming list of * users omits the super-user. * * @param users * @param anonGrants * @param allGroups * @param cc * @throws DatastoreFailureException * @throws AccessDeniedException */ public static final void setStandardSiteAccessConfiguration(ArrayList<UserSecurityInfo> users, ArrayList<GrantedAuthorityName> allGroups, CallingContext cc) throws DatastoreFailureException, AccessDeniedException { // remove anonymousUser from the set of users and collect its // permissions (anonGrantStrings) which will be placed in // the granted authority hierarchy table. List<String> anonGrantStrings = new ArrayList<String>(); { UserSecurityInfo anonUser = null; for (UserSecurityInfo i : users) { if (i.getType() == UserType.ANONYMOUS) { anonUser = i; // clean up grants for anonymousUser -- // ignore anonAuth (the grant under which we will place things) // and forbid Site Admin for (GrantedAuthorityName a : i.getAssignedUserGroups()) { if (anonAuth.getAuthority().equals(a.name())) continue; // avoid circularity... // only allow ROLE_ATTACHMENT_VIEWER and GROUP_ assignments. if (!a.name().startsWith(GrantedAuthorityName.GROUP_PREFIX)) { continue; } // do not allow Site Admin assignments for Anonymous -- // or Tables super-user or Tables Administrator. // those all give access to the full set of users on the system // and giving that information to Anonymous is a security // risk. if (GrantedAuthorityName.GROUP_SITE_ADMINS.equals(a) || GrantedAuthorityName.GROUP_ADMINISTER_TABLES.equals(a) || GrantedAuthorityName.GROUP_SUPER_USER_TABLES.equals(a)) { continue; } anonGrantStrings.add(a.name()); } break; } } if (anonUser != null) { users.remove(anonUser); } } // scan through the users and remove any entries under assigned user groups // that do not begin with GROUP_. // // Additionally, if the user is an e-mail, remove the GROUP_DATA_COLLECTORS // permission since ODK Collect does not support oauth2 authentication. { TreeSet<GrantedAuthorityName> toRemove = new TreeSet<GrantedAuthorityName>(); for (UserSecurityInfo i : users) { // only working with registered users if (i.getType() != UserType.REGISTERED) { continue; } // get the list of assigned groups // -- this is not a copy -- we can directly manipulate this. TreeSet<GrantedAuthorityName> assignedGroups = i.getAssignedUserGroups(); // scan the set of assigned groups and remove any that don't begin with GROUP_ toRemove.clear(); for (GrantedAuthorityName name : assignedGroups) { if (!name.name().startsWith(GrantedAuthorityName.GROUP_PREFIX)) { toRemove.add(name); } } if (!toRemove.isEmpty()) { assignedGroups.removeAll(toRemove); } // for e-mail accounts, remove the Data Collector permission since ODK Collect // does not support an oauth2 authentication mechanism. if (i.getEmail() != null) { assignedGroups.remove(GrantedAuthorityName.GROUP_DATA_COLLECTORS); } } } // find the entry(entries) for the designated super-user(s) String superUserUsername = cc.getUserService().getSuperUserUsername(); int expectedSize = ((superUserUsername != null) ? 1 : 0); ArrayList<UserSecurityInfo> superUsers = new ArrayList<UserSecurityInfo>(); for (UserSecurityInfo i : users) { if (i.getType() == UserType.REGISTERED) { if (i.getUsername() != null && superUserUsername != null && i.getUsername().equals(superUserUsername)) { superUsers.add(i); } } } if (superUsers.size() != expectedSize) { // we are missing one or both super-users. // remove any we have and recreate them from scratch. users.removeAll(superUsers); superUsers.clear(); // Synthesize a UserSecurityInfo object for the super-user(s) // and add it(them) to the list. try { List<RegisteredUsersTable> tList = RegisteredUsersTable.assertSuperUsers(cc); for (RegisteredUsersTable t : tList) { UserSecurityInfo i = new UserSecurityInfo(t.getUsername(), t.getFullName(), t.getEmail(), UserSecurityInfo.UserType.REGISTERED); superUsers.add(i); users.add(i); } } catch (ODKDatastoreException e) { e.printStackTrace(); throw new DatastoreFailureException("Incomplete update"); } } // reset super-user privileges to have (just) site admin privileges // even if caller attempts to change, add, or remove them. for (UserSecurityInfo i : superUsers) { TreeSet<GrantedAuthorityName> grants = new TreeSet<GrantedAuthorityName>(); grants.add(GrantedAuthorityName.GROUP_SITE_ADMINS); grants.add(GrantedAuthorityName.ROLE_SITE_ACCESS_ADMIN); // override whatever the user gave us. i.setAssignedUserGroups(grants); } try { // enforce our fixed set of groups and their inclusion hierarchy. // this is generally a no-op during normal operations. GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(siteAuth, SecurityServiceUtil.siteAdministratorGrants, cc); GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(administerTablesAuth, SecurityServiceUtil.administerTablesGrants, cc); GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(superUserTablesAuth, SecurityServiceUtil.superUserTablesGrants, cc); GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(synchronizeTablesAuth, SecurityServiceUtil.synchronizeTablesGrants, cc); GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(dataOwnerAuth, SecurityServiceUtil.dataOwnerGrants, cc); GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(dataViewerAuth, SecurityServiceUtil.dataViewerGrants, cc); GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(dataCollectorAuth, SecurityServiceUtil.dataCollectorGrants, cc); // place the anonymous user's permissions in the granted authority table. GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(anonAuth, anonGrantStrings, cc); // get all granted authority names TreeSet<String> authorities = GrantedAuthorityHierarchyTable .getAllPermissionsAssignableGrantedAuthorities(cc.getDatastore(), cc.getCurrentUser()); // remove the groups that have structure (i.e., those defined above). authorities.remove(siteAuth.getAuthority()); authorities.remove(administerTablesAuth.getAuthority()); authorities.remove(superUserTablesAuth.getAuthority()); authorities.remove(synchronizeTablesAuth.getAuthority()); authorities.remove(dataOwnerAuth.getAuthority()); authorities.remove(dataViewerAuth.getAuthority()); authorities.remove(dataCollectorAuth.getAuthority()); authorities.remove(anonAuth.getAuthority()); // delete all hierarchy structures under anything else. // i.e., if somehow USER_IS_REGISTERED had been granted GROUP_FORM_MANAGER // then this loop would leave USER_IS_REGISTERED without any grants. // (it repairs the database to conform to our privilege hierarchy expectations). List<String> empty = Collections.emptyList(); for (String s : authorities) { GrantedAuthorityHierarchyTable.assertGrantedAuthorityHierarchy(new SimpleGrantedAuthority(s), empty, cc); } // declare all the users (and remove users that are not in this set) Map<UserSecurityInfo, String> pkMap = setUsers(users, cc); // now, for each GROUP_..., update the user granted authority // table with the users that have that GROUP_... assignment. setUsersOfGrantedAuthority(pkMap, siteAuth, cc); setUsersOfGrantedAuthority(pkMap, administerTablesAuth, cc); setUsersOfGrantedAuthority(pkMap, superUserTablesAuth, cc); setUsersOfGrantedAuthority(pkMap, synchronizeTablesAuth, cc); setUsersOfGrantedAuthority(pkMap, dataOwnerAuth, cc); setUsersOfGrantedAuthority(pkMap, dataViewerAuth, cc); setUsersOfGrantedAuthority(pkMap, dataCollectorAuth, cc); // all super-users would already have their site admin role and // we leave that unchanged. The key is to ensure that the // super users are in the users list so they don't get // accidentally removed and that they have siteAuth group // membership. I.e., we don't need to manage ROLE_SITE_ACCESS_ADMIN // here. it is done elsewhere. } catch (ODKDatastoreException e) { e.printStackTrace(); throw new DatastoreFailureException("Incomplete update"); } finally { Datastore ds = cc.getDatastore(); User user = cc.getCurrentUser(); try { SecurityRevisionsTable.setLastRegisteredUsersRevisionDate(ds, user); } catch (ODKDatastoreException e) { // if it fails, use RELOAD_INTERVAL to force reload. e.printStackTrace(); } try { SecurityRevisionsTable.setLastRoleHierarchyRevisionDate(ds, user); } catch (ODKDatastoreException e) { // if it fails, use RELOAD_INTERVAL to force reload. e.printStackTrace(); } } }
From source file:ac.robinson.mediaphone.MediaPhoneActivity.java
protected Runnable getMediaCleanupRunnable() { return new Runnable() { @Override// w ww . j a v a2s . c o m public void run() { ContentResolver contentResolver = getContentResolver(); // find narratives and templates marked as deleted ArrayList<String> deletedNarratives = NarrativesManager.findDeletedNarratives(contentResolver); ArrayList<String> deletedTemplates = NarrativesManager.findDeletedTemplates(contentResolver); deletedNarratives.addAll(deletedTemplates); // templates can be handled at the same time as narratives // find frames marked as deleted, and also frames whose parent narrative/template is marked as deleted ArrayList<String> deletedFrames = FramesManager.findDeletedFrames(contentResolver); for (String narrativeId : deletedNarratives) { deletedFrames.addAll(FramesManager.findFrameIdsByParentId(contentResolver, narrativeId)); } // find media marked as deleted, and also media whose parent frame is marked as deleted ArrayList<String> deletedMedia = MediaManager.findDeletedMedia(contentResolver); for (String frameId : deletedFrames) { deletedMedia.addAll(MediaManager.findMediaIdsByParentId(contentResolver, frameId)); } // delete the actual media items on disk and from the database int deletedMediaCount = 0; for (String mediaId : deletedMedia) { final MediaItem mediaToDelete = MediaManager.findMediaByInternalId(contentResolver, mediaId); if (mediaToDelete != null) { final File fileToDelete = mediaToDelete.getFile(); if (fileToDelete != null && fileToDelete.exists()) { if (fileToDelete.delete()) { deletedMediaCount += 1; } } MediaManager.deleteMediaFromBackgroundTask(contentResolver, mediaId); } } // delete the actual frame items on disk and from the database int deletedFrameCount = 0; for (String frameId : deletedFrames) { final FrameItem frameToDelete = FramesManager.findFrameByInternalId(contentResolver, frameId); if (frameToDelete != null) { final File directoryToDelete = frameToDelete.getStorageDirectory(); if (directoryToDelete != null && directoryToDelete.exists()) { if (IOUtilities.deleteRecursive(directoryToDelete)) { deletedFrameCount += 1; } } FramesManager.deleteFrameFromBackgroundTask(contentResolver, frameId); } } // finally, delete the narratives/templates themselves (must do separately) deletedNarratives.removeAll(deletedTemplates); for (String narrativeId : deletedNarratives) { NarrativesManager.deleteNarrativeFromBackgroundTask(contentResolver, narrativeId); } for (String templateId : deletedTemplates) { NarrativesManager.deleteTemplateFromBackgroundTask(contentResolver, templateId); } // report progress Log.i(DebugUtilities.getLogTag(this), "Media cleanup: removed " + deletedNarratives.size() + "/" + deletedTemplates.size() + " narratives/templates, " + deletedFrames.size() + " (" + deletedFrameCount + ") frames, and " + deletedMedia.size() + " (" + deletedMediaCount + ") media items"); } }; }
From source file:edu.eurac.commul.pepperModules.mmax2.MMAX22SaltMapper.java
/** * Maps a {@link SaltExtendedDocument} document to an {@link SDocument} sDocument * @param document The {@link SaltExtendedDocument} document to map * @param sDocument the {@link SDocument} to which the data is being mapped to *///from w ww . j a va2 s .c o m public void mapSDocument(SaltExtendedDocument document, SDocument sDocument) { this.sNodesHash = new Hashtable<SaltExtendedMarkable, SNode>(); this.sRelationsHash = new Hashtable<SaltExtendedMarkable, SRelation>(); this.sLayerHash = new Hashtable<String, SLayer>(); this.sTextualDsOfset = new Hashtable<STextualDS, Integer>(); this.sTokensHash = new Hashtable<String, SToken>(); this.saltExtendedMarkableHash = new Hashtable<String, Hashtable<String, SaltExtendedMarkable>>(); this.sTextualDsBaseDataUnitCorrespondance = new Hashtable<String, STextualDS>(); this.claimSContainer = new Hashtable<SaltExtendedMarkable, SaltExtendedMarkable>(); this.saltIds = new Hashtable<String, IdentifiableElement>(); this.saltIdsCpt = new Hashtable<String, Integer>(); SDocumentGraph sDocumentGraph = sDocument.getDocumentGraph(); sDocumentGraph.setName(document.getDocumentId() + "_graph"); ArrayList<SaltExtendedMarkable> markables = document.getAllSaltExtendedMarkables(); Hashtable<String, SaltExtendedMarkable> baseDataUnitInTextualDS = new Hashtable<String, SaltExtendedMarkable>(); for (SaltExtendedMarkable markable : markables) { if (markable.hasSaltInformation() && (markable.getSType().equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_STEXTUALDS))) { String[] markableSpans = markable.getSpan().split(","); for (int i = 0; i < markableSpans.length; i++) { ArrayList<String> baseDataUnits = getBaseUnitIds(markableSpans[i]); for (String baseDataUnit : baseDataUnits) { if (baseDataUnitInTextualDS.containsKey(baseDataUnit)) { throw new PepperModuleDataException(this, "Two textualDS covers one same basedata unit: markables '" + markable.getId() + "' and '" + baseDataUnitInTextualDS.get(baseDataUnit).getId() + "' both covers '" + baseDataUnit + "'"); } else { baseDataUnitInTextualDS.put(baseDataUnit, markable); } } } } } int nbBaseDataUnits = 0; Hashtable<String, int[]> indicesTokens = new Hashtable<String, int[]>(); Hashtable<SaltExtendedMarkable, ArrayList<BaseDataUnit>> sTextualDSBaseDataUnits = new Hashtable<SaltExtendedMarkable, ArrayList<BaseDataUnit>>(); SaltExtendedMarkable lastTextualDsMarkable = null; ArrayList<BaseDataUnit> bufferBaseDataUnit = new ArrayList<BaseDataUnit>(); ArrayList<BaseDataUnit> baseDataUnits = document.getBaseDataUnits(); { int indice = 0; Hashtable<SaltExtendedMarkable, String> previouslySeenTextualDs = new Hashtable<SaltExtendedMarkable, String>(); nbBaseDataUnits = baseDataUnits.size(); for (BaseDataUnit baseDataUnit : baseDataUnits) { int newIndice = indice + baseDataUnit.getText().length(); int[] indices = { indice, newIndice }; indicesTokens.put(baseDataUnit.getId(), indices); indice = newIndice; bufferBaseDataUnit.add(baseDataUnit); if (baseDataUnitInTextualDS.containsKey(baseDataUnit.getId())) { SaltExtendedMarkable textualDsMarkable = baseDataUnitInTextualDS.get(baseDataUnit.getId()); if ((textualDsMarkable != lastTextualDsMarkable) && (previouslySeenTextualDs.containsKey(textualDsMarkable))) { throw new PepperModuleDataException(this, "The spans of textualDs markables '" + textualDsMarkable.getId() + "' and '" + lastTextualDsMarkable + "' overlap one another."); } lastTextualDsMarkable = textualDsMarkable; previouslySeenTextualDs.put(lastTextualDsMarkable, ""); ArrayList<BaseDataUnit> localBaseDataUnits = sTextualDSBaseDataUnits.get(lastTextualDsMarkable); if (localBaseDataUnits == null) { localBaseDataUnits = new ArrayList<BaseDataUnit>(); sTextualDSBaseDataUnits.put(lastTextualDsMarkable, localBaseDataUnits); } localBaseDataUnits.addAll(bufferBaseDataUnit); bufferBaseDataUnit = new ArrayList<BaseDataUnit>(); } } } if (bufferBaseDataUnit.size() != 0) { if (lastTextualDsMarkable != null) { sTextualDSBaseDataUnits.get(lastTextualDsMarkable).addAll(bufferBaseDataUnit); } else { createSTextualDS(sDocumentGraph, null, bufferBaseDataUnit, indicesTokens); } } ArrayList<SSpanningRelation> sSpanRelNodes = new ArrayList<SSpanningRelation>(); ArrayList<SaltExtendedMarkable> sSpanRelMarkables = new ArrayList<SaltExtendedMarkable>(); ArrayList<SDominanceRelation> sDomRelNodes = new ArrayList<SDominanceRelation>(); ArrayList<SaltExtendedMarkable> sDomRelMarkables = new ArrayList<SaltExtendedMarkable>(); ArrayList<STextualRelation> sTextRelNodes = new ArrayList<STextualRelation>(); ArrayList<SaltExtendedMarkable> sTextRelMarkables = new ArrayList<SaltExtendedMarkable>(); ArrayList<SPointingRelation> sPointerNodes = new ArrayList<SPointingRelation>(); ArrayList<SaltExtendedMarkable> sPointerMarkables = new ArrayList<SaltExtendedMarkable>(); ArrayList<SaltExtendedMarkable> sContainerMarkables = new ArrayList<SaltExtendedMarkable>(); ArrayList<SaltExtendedMarkable> sAnnotationMarkables = new ArrayList<SaltExtendedMarkable>(); Hashtable<String, SAnnotationContainer> correspondanceSAnnotations = new Hashtable<String, SAnnotationContainer>(); ArrayList<SaltExtendedMarkable> sMetaAnnotationMarkables = new ArrayList<SaltExtendedMarkable>(); Hashtable<String, SAnnotationContainer> correspondanceSMetaAnnotations = new Hashtable<String, SAnnotationContainer>(); ArrayList<SaltExtendedMarkable> sLayerLinkMarkables = new ArrayList<SaltExtendedMarkable>(); ArrayList<SaltExtendedMarkable> sTypeLinkMarkables = new ArrayList<SaltExtendedMarkable>(); Hashtable<Scheme, ArrayList<SaltExtendedMarkable>> newMarkables = new Hashtable<Scheme, ArrayList<SaltExtendedMarkable>>(); SaltExtendedMarkable sDocumentMarkable = null; SaltExtendedMarkable sDocumentGraphMarkable = null; for (SaltExtendedMarkable markable : markables) { registerMarkable(markable); if (!markable.hasSaltInformation()) { // new markable originally produced with Mmax2 ArrayList<SaltExtendedMarkable> markableOfScheme = newMarkables .get(markable.getFactory().getScheme()); if (markableOfScheme == null) { markableOfScheme = new ArrayList<SaltExtendedMarkable>(); newMarkables.put(markable.getFactory().getScheme(), markableOfScheme); } markableOfScheme.add(markable); } else { // markables originally produced (exported) from SAlt String sType = markable.getSType(); String key = markable.getSId(); if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SDOCUMENT)) { if (sDocumentMarkable != null) { throw new PepperModuleDataException(this, "Two SDocument markable have been found: markables '" + markable.getId() + "' and '" + sDocumentMarkable.getId() + "'"); } sDocumentMarkable = markable; correspondanceSAnnotations.put(key, sDocument); correspondanceSMetaAnnotations.put(key, sDocument); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SDOCUMENT_GRAPH)) { if (sDocumentGraphMarkable != null) { throw new PepperModuleDataException(this, "Two SDocumentGraph markable have been found: markables '" + markable.getId() + "' and '" + sDocumentGraphMarkable.getId() + "'"); } sDocumentGraphMarkable = markable; correspondanceSAnnotations.put(key, sDocumentGraph); correspondanceSMetaAnnotations.put(key, sDocumentGraph); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SLAYER)) { SLayer sLayer = createSLayer(sDocumentGraph, markable); correspondanceSAnnotations.put(key, sLayer); correspondanceSMetaAnnotations.put(key, sLayer); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_STEXTUALDS)) { STextualDS sTextualDS = createSTextualDS(sDocumentGraph, markable, sTextualDSBaseDataUnits.get(markable), indicesTokens); correspondanceSAnnotations.put(key, sTextualDS); correspondanceSMetaAnnotations.put(key, sTextualDS); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_STOKEN)) { SToken sToken = createSToken(sDocumentGraph, markable); correspondanceSAnnotations.put(key, sToken); correspondanceSMetaAnnotations.put(key, sToken); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SSTRUCT)) { SStructure sStruct = createSStruct(sDocumentGraph, markable); correspondanceSAnnotations.put(key, sStruct); correspondanceSMetaAnnotations.put(key, sStruct); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SSPAN)) { SSpan sSpan = createSSPan(sDocumentGraph, markable); correspondanceSAnnotations.put(key, sSpan); correspondanceSMetaAnnotations.put(key, sSpan); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_STEXTUAL_REL)) { sTextRelMarkables.add(markable); STextualRelation sTextualRelation = createSTextualRelation(sDocumentGraph, markable); sTextRelNodes.add(sTextualRelation); correspondanceSAnnotations.put(key, sTextualRelation); correspondanceSMetaAnnotations.put(key, sTextualRelation); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SSPANNING_REL)) { sSpanRelMarkables.add(markable); SSpanningRelation sSpanningRelation = createSSpanningRelation(sDocumentGraph, markable); sSpanRelNodes.add(sSpanningRelation); correspondanceSAnnotations.put(key, sSpanningRelation); correspondanceSMetaAnnotations.put(key, sSpanningRelation); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SDOMINANCE_REL)) { sDomRelMarkables.add(markable); SDominanceRelation sDomRel = createSDomRel(sDocumentGraph, markable); sDomRelNodes.add(sDomRel); correspondanceSAnnotations.put(key, sDomRel); correspondanceSMetaAnnotations.put(key, sDomRel); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SPOINTING_REL)) { sPointerMarkables.add(markable); SPointingRelation sPointer = createSPointer(sDocumentGraph, markable); sPointerNodes.add(sPointer); correspondanceSAnnotations.put(key, sPointer); correspondanceSMetaAnnotations.put(key, sPointer); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SANNOTATION)) { sAnnotationMarkables.add(markable); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SMETAANNOTATION)) { sMetaAnnotationMarkables.add(markable); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SLAYER_LINK)) { sLayerLinkMarkables.add(markable); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_STYPE_LINK)) { sTypeLinkMarkables.add(markable); } else if (sType.equals(SaltExtendedMmax2Infos.SALT_INFO_TYPE_SCONTAINER)) { sContainerMarkables.add(markable); } else { throw new PepperModuleException("Developper error:Unknown type '" + sType + "'"); } } } if (sDocumentMarkable != null) { sDocument.setName(sDocumentMarkable.getSName()); } if (sDocumentGraphMarkable != null) { sDocumentGraph.setName(sDocumentGraphMarkable.getSName()); } for (SaltExtendedMarkable markable : sContainerMarkables) { handleSContainer(markable); } /* Setting up the SAnnotations and SMetaAnnotations on the nodes and edges */ for (SaltExtendedMarkable markable : sAnnotationMarkables) { createSAnnotation(sDocumentGraph, correspondanceSAnnotations.get(markable.getSId()), markable); } for (SaltExtendedMarkable markable : sMetaAnnotationMarkables) { createSMetaAnnotation(sDocumentGraph, correspondanceSMetaAnnotations.get(markable.getSId()), markable); } for (SaltExtendedMarkable markable : sLayerLinkMarkables) { createSLayerLink(sDocumentGraph, markable); } /* linking all nodes and edges together */ for (int i = 0; i < sTextRelNodes.size(); i++) { completeSTextualRelation(sTextRelNodes.get(i), sTextRelMarkables.get(i), indicesTokens); } for (int i = 0; i < sDomRelNodes.size(); i++) { completeSDomRel(sDomRelNodes.get(i), sDomRelMarkables.get(i)); } for (int i = 0; i < sSpanRelNodes.size(); i++) { completeSPanningRelation(sSpanRelNodes.get(i), sSpanRelMarkables.get(i)); } for (int i = 0; i < sPointerNodes.size(); i++) { completeSPointer(sPointerNodes.get(i), sPointerMarkables.get(i)); } for (SaltExtendedMarkable markable : sTypeLinkMarkables) { createSTypeLink(markable); } /* Creating new SSpans */ SLayer mmaxSLayer = null; if (newMarkables.keySet().size() != 0) { // => means "new Markables created since export from salt" for (SLayer sLayer : this.sLayerHash.values()) { if (sLayer.getName().equals("Mmax2_SLayer")) { mmaxSLayer = sLayer; break; } } if (mmaxSLayer == null) { mmaxSLayer = SaltFactory.createSLayer(); mmaxSLayer.setName("Mmax2_SLayer"); mmaxSLayer.setId("Mmax2_SLayer"); sDocumentGraph.addLayer(mmaxSLayer); } for (Scheme scheme : newMarkables.keySet()) { String schemeName = scheme.getName(); ArrayList<SaltExtendedMarkable> markablesToIgnore = new ArrayList<SaltExtendedMarkable>(); ArrayList<SaltExtendedMarkable> schemeMarkables = newMarkables.get(scheme); for (SaltExtendedMarkable markable : schemeMarkables) { String span = markable.getSpan(); String[] spans = span.split(","); ArrayList<String> baseDateUnitIds = new ArrayList<String>(); for (int i = 0; i < spans.length; i++) { baseDateUnitIds.addAll(getBaseUnitIds(spans[i])); } boolean containsNoPointers = true; for (MarkableAttribute markableAttribute : markable.getAttributes()) { String attributeType = markableAttribute.getFactory().getAttributeType(); if (attributeType.equals(MarkablePointerAttributeFactory.pointerType)) { containsNoPointers = false; } } boolean isMetaMarkable = false; if (containsNoPointers) { if (baseDateUnitIds.size() >= nbBaseDataUnits - 1) {// To remove someday... isMetaMarkable = true; } } if (isMetaMarkable == false) { SSpan sSpan = SaltFactory.createSSpan(); sSpan.setName(schemeName); sSpan.setId(getNewSid(schemeName)); sDocumentGraph.addNode(sSpan); registerSNode(markable, sSpan); SAnnotation sAnnotation = SaltFactory.createSAnnotation(); sAnnotation.setNamespace("Mmax2"); sAnnotation.setName("markable_scheme"); sAnnotation.setValue(schemeName); sSpan.addAnnotation(sAnnotation); mmaxSLayer.addNode(sSpan); for (String baseDataUnitId : baseDateUnitIds) { SToken sToken = getSToken(baseDataUnitId, indicesTokens); SSpanningRelation sSpanRel = SaltFactory.createSSpanningRelation(); sSpanRel.setSource(sSpan); sSpanRel.setTarget(sToken); sDocumentGraph.addRelation(sSpanRel); mmaxSLayer.addRelation(sSpanRel); } } else { for (MarkableAttribute markableAttribute : markable.getAttributes()) { SMetaAnnotation sMetaAnnotation = SaltFactory.createSMetaAnnotation(); sMetaAnnotation.setName(markableAttribute.getName()); sMetaAnnotation.setNamespace("Mmax2"); String value = markableAttribute.getValue(); value = value.replaceAll("\n", ""); sMetaAnnotation.setValue(value); sDocument.addMetaAnnotation(sMetaAnnotation); markablesToIgnore.add(markable); } } } schemeMarkables.removeAll(markablesToIgnore); } } /* handling all attributes on newly produced (i.e non-exported) markables */ if (newMarkables.keySet().size() != 0) { // => means "new Markables created since export from salt" for (Scheme scheme : newMarkables.keySet()) { for (SaltExtendedMarkable markable : newMarkables.get(scheme)) { SSpan sSpan = (SSpan) getSNode(markable); for (MarkableAttribute markableAttribute : markable.getAttributes()) { String attributeType = markableAttribute.getFactory().getAttributeType(); if (attributeType.equals(MarkableFreetextAttributeFactory.freetextType) || attributeType.equals(MarkableNominalAttributeFactory.nominalType) || attributeType.equals(MarkableSetAttributeFactory.setType)) { SAnnotation sAnnotation = SaltFactory.createSAnnotation(); String value = markableAttribute.getValue(); value = value.replaceAll("\n", ""); if (markableAttribute.getName().equals("markable_sheme")) { sAnnotation.setName(value); } else { sAnnotation.setName(scheme.getName() + "_" + markableAttribute.getName()); } sAnnotation.setNamespace("Mmax2"); sAnnotation.setValue(value); sSpan.addAnnotation(sAnnotation); } else if (attributeType.equals(MarkablePointerAttributeFactory.pointerType)) { MarkablePointerAttributeFactory factory = (MarkablePointerAttributeFactory) markableAttribute .getFactory(); String markablePointerValue = markableAttribute.getValue(); String[] markablePointerValues = markablePointerValue.split(";"); if (markablePointerValues.length == 0) { throw new PepperModuleDataException(this, "The target of the pointer '" + markableAttribute.getName() + "' within markable '" + markable + "' is empty..."); } for (int i = 0; i < markablePointerValues.length; i++) { SPointingRelation sPointingRelation = SaltFactory.createSPointingRelation(); sPointingRelation.setName(markableAttribute.getName()); sDocumentGraph.addRelation(sPointingRelation); sPointingRelation.setType(markableAttribute.getName()); sPointingRelation.setSource(sSpan); SaltExtendedMarkable targetMarkable = getMarkable(markablePointerValues[i], factory.getTargetSchemeName()); if (targetMarkable == null) throw new PepperModuleDataException(this, "An unknown markable of id '" + markablePointerValues[i] + "' belonging to scheme '" + factory.getTargetSchemeName() + "' is referenced as the target of the pointer '" + markableAttribute.getName() + "' within markable '" + markable + "'"); SNode sTarget = getSNode(targetMarkable); sPointingRelation.setTarget((SStructuredNode) sTarget); mmaxSLayer.addRelation(sPointingRelation); sPointingRelation.getLayers().add(mmaxSLayer); } } else { throw new PepperModuleException("Developper error: unknown type of markable attribute '" + attributeType + "'..."); } } } } } // to force creation of STokens for all Base Data units for (BaseDataUnit baseDataUnit : baseDataUnits) { getSToken(baseDataUnit.getId(), indicesTokens); } }
From source file:sbu.srl.rolextract.ArgumentClassifier.java
public void performedFeatureAddition(String outputDir, int crossValidation) throws FileNotFoundException, IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InterruptedException { List<String> ablationFeatures = getAblationFeatures("./configSBUProcRel/features.ablation"); ArrayList<String> stepwiseFeatures = new ArrayList<String>(); for (int idxAblation = 0; idxAblation < ablationFeatures.size(); idxAblation++) { double maxF1 = Double.MIN_VALUE; ArrayList<String> currentBestFeat = new ArrayList<String>(); String[] metricsBest = null; for (int idxFeat = 0; idxFeat < ablationFeatures.size(); idxFeat++) { Thread.sleep(3000);//from w ww . j a va 2s.co m ArrayList<String> addedFeatures = new ArrayList<String>(); addedFeatures.addAll(Arrays.asList(ablationFeatures.get(idxFeat).split(","))); //(ArrayList<String>) Arrays.asList(ablationFeatures.get(idxAblation).split(",")); boolean triedFeatures = false; for (int i = 0; i < addedFeatures.size(); i++) { if (stepwiseFeatures.contains(addedFeatures.get(i))) { triedFeatures = true; } } if (triedFeatures) { continue; } System.out.println("Adding features : " + ablationFeatures.get(idxFeat)); stepwiseFeatures.addAll(addedFeatures); FileUtil.dumpToFile(stepwiseFeatures, "./configSBUProcRel/features"); for (int idxFold = 1; idxFold <= crossValidation; idxFold++) { File trainFoldDir = new File(outputDir.concat("/fold-").concat("" + idxFold).concat("/train")); File testFoldDir = new File(outputDir.concat("/fold-").concat("" + idxFold).concat("/test")); SBURoleTrain trainer = new SBURoleTrain(trainFoldDir.getAbsolutePath().concat("/train.ser"), isMultiClass); trainer.train(trainFoldDir.getAbsolutePath()); SBURolePredict predict = new SBURolePredict(trainFoldDir.getAbsolutePath(), testFoldDir.getAbsolutePath().concat("/test.arggold.ser"), isMultiClass); predict.performPrediction(testFoldDir.getAbsolutePath().concat("/test.arggold.ser")); ArrayList<Sentence> predictedSentences = (ArrayList<Sentence>) FileUtil .deserializeFromFile(testFoldDir.getAbsolutePath().concat("/test.argpredict.ser")); Map<String, List<Sentence>> groupByProcess = predictedSentences.stream() .collect(Collectors.groupingBy(Sentence::getProcessName)); ArrayList<JSONData> jsonData = SentenceUtil.generateJSONData(groupByProcess); SentenceUtil.flushDataToJSON(jsonData, testFoldDir.getAbsolutePath().concat("/test.srlout.json"), false); SentenceUtil.flushDataToJSON(jsonData, testFoldDir.getAbsolutePath().concat("/test.srlpredict.json"), true); SentenceUtil.flushDataToJSON(jsonData, testFoldDir.getAbsolutePath().concat("/test.ilppredict.json"), true); // dummy SentenceUtil.flushDataToJSON(jsonData, testFoldDir.getAbsolutePath().concat("/test.semaforpredict.json"), true);// dummy SentenceUtil.flushDataToJSON(jsonData, testFoldDir.getAbsolutePath().concat("/test.easysrlpredict.json"), true);// dummy SentenceUtil.flushDataToJSON(jsonData, testFoldDir.getAbsolutePath().concat("/test.fgpredict.json"), true);// dummy } // copy all data to ILP's data folder // cp -r outputDir /home/slouvan/NetBeansProjects/ILP/data/ copyAndEval(outputDir); String[] lines = FileUtil.readLinesFromFile("/home/slouvan/NetBeansProjects/ILP/stats.txt"); double currentF1 = Double.parseDouble(lines[0].split("\t")[2]); if (currentF1 > maxF1) { maxF1 = currentF1; currentBestFeat = addedFeatures; metricsBest = lines; } stepwiseFeatures.removeAll(addedFeatures); } PrintWriter out = new PrintWriter( new BufferedWriter(new FileWriter(GlobalV.PROJECT_DIR + "/additionNew.txt", true))); out.println((new Date()).toString() + " Best features at this stage is " + currentBestFeat); out.println("Eval : " + Arrays.toString(metricsBest)); stepwiseFeatures.addAll(currentBestFeat); out.println("All current features :" + stepwiseFeatures); out.close(); } }