Example usage for org.apache.commons.collections15 Predicate Predicate

List of usage examples for org.apache.commons.collections15 Predicate Predicate

Introduction

In this page you can find the example usage for org.apache.commons.collections15 Predicate Predicate.

Prototype

Predicate

Source Link

Usage

From source file:gov.nih.nci.cabig.caaers.domain.report.ReportDefinition.java

/**
 * Will return the ReportMandatoryFieldDefinition that are associated to rules.
 *
 * @return the all rule based mandatory fields
 *///w  w w  . ja  v  a  2 s  . co m
@Transient
public Collection<ReportMandatoryFieldDefinition> getAllRuleBasedMandatoryFields() {
    return CollectionUtils.select(getMandatoryFields(), new Predicate<ReportMandatoryFieldDefinition>() {
        public boolean evaluate(ReportMandatoryFieldDefinition rd) {
            return rd.isRuleBased();
        }
    });
}

From source file:gov.nih.nci.cabig.caaers.web.security.FabricatedAuthenticationFilter.java

/**
 * @param authorities/*  www  .j  av  a2 s.c  o  m*/
 * @param request
 * @return
 * @throws ClassNotFoundException
 */
private GrantedAuthority[] filterAuthorities(GrantedAuthority[] authorities, HttpServletRequest request) {

    List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
    if (authorities != null) {
        list.addAll(Arrays.asList(authorities));
        URLToEntityIdMapEntry entry = getURLToEntityIdEntryFromRequest(request);
        if (entry != null) {
            // protection element info found. Possibly need to restrict the
            // set of granted authorities.
            if (RESEARCH_STAFF.equalsIgnoreCase(entry.getClassName())) {
                int staffId = entry.getObjectId();
                filterAuthoritiesByResearchStaff(list, staffId);
            } else if (INVESTIGATOR.equalsIgnoreCase(entry.getClassName())) {
                int investigatorId = entry.getObjectId();
                filterAuthoritiesByInvestigator(list, investigatorId);
            } else if (STUDY.equalsIgnoreCase(entry.getClassName())) {
                int studyId = entry.getObjectId();
                filterAuthoritiesByStudy(list, studyId);
            } else if (ORGANIZATION.equalsIgnoreCase(entry.getClassName())) {
                int orgId = entry.getObjectId();
                filterAuthoritiesByOrganization(list, orgId);
            }
        } else {
            final URLToRoleListMapEntry rolesEntry = getURLToRolesEntryFromRequest(request);
            if (rolesEntry != null) {
                // simply return the disjunction of roles.
                org.apache.commons.collections15.CollectionUtils.filter(list,
                        new Predicate<GrantedAuthority>() {
                            public boolean evaluate(GrantedAuthority ga) {
                                return rolesEntry.getRoleNames().contains(ga.getAuthority());
                            }
                        });
            }
        }
    }
    return list.toArray(new GrantedAuthority[0]);
}

From source file:com.javaid.bolaky.domain.pools.entity.Pool.java

public void completed() {

    if (this.poolStatus.equals(PoolStatus.DRAFT) || this.poolStatus.equals(PoolStatus.ACTIVE)) {

        final Set<PoolsError> poolsErrors = this.validate();
        final String startingDateFutureErrorCode = "P120";
        final String endDateFutureErrorCode = "P171";

        Predicate<PoolsError> startingDateErrorCodePredicate = new Predicate<PoolsError>() {

            public boolean evaluate(PoolsError poolsError) {
                return poolsError.getErrorCode().equalsIgnoreCase(startingDateFutureErrorCode);
            }/*from   w w w .j  a va  2s. c o m*/
        };

        Predicate<PoolsError> endDateErrorCodePredicate = new Predicate<PoolsError>() {

            public boolean evaluate(PoolsError poolsError) {
                return poolsError.getErrorCode().equalsIgnoreCase(endDateFutureErrorCode);
            }
        };

        if (CollectionUtils.exists(poolsErrors, startingDateErrorCodePredicate)
                && CollectionUtils.exists(poolsErrors, endDateErrorCodePredicate)) {

            this.poolStatus = PoolStatus.COMPLETED;
        }
    }
}

From source file:gov.nih.nci.cabig.caaers.domain.report.ReportDefinition.java

/**
 * Will return the ReportMandatoryFieldDefinition that are self referenced.
 *
 * @return the self referenced rule based mandatory fields
 *///from   w  ww .  j  a  v a  2  s  . c  om
@Transient
public Collection<ReportMandatoryFieldDefinition> getSelfReferencedRuleBasedMandatoryFields() {
    return CollectionUtils.select(getMandatoryFields(), new Predicate<ReportMandatoryFieldDefinition>() {
        public boolean evaluate(ReportMandatoryFieldDefinition rd) {
            return rd.isRuleBased() && rd.isSelfReferenced();
        }
    });
}

From source file:gov.nih.nci.cabig.caaers.domain.report.ReportDefinition.java

/**
 * Will return the ReportMandatoryFieldDefinition that are not self referenced.
 *
 * @return the non self referenced rule based mandatory fields
 *///  www .  ja v  a 2s  . c  o  m
@Transient
public Collection<ReportMandatoryFieldDefinition> getNonSelfReferencedRuleBasedMandatoryFields() {
    return CollectionUtils.select(getMandatoryFields(), new Predicate<ReportMandatoryFieldDefinition>() {
        public boolean evaluate(ReportMandatoryFieldDefinition rd) {
            return rd.isRuleBased() && !rd.isSelfReferenced();
        }
    });
}

From source file:com.diversityarrays.kdxplore.field.FieldViewPanel.java

/**
 * Create a new FieldViewPanel using the caller-provided VisitOrder2D and PlotsPerGroup.
 * @param database//from  w w w  . j  a  v  a 2  s .  c om
 * @param trial
 * @param visitOrder
 * @param plotsPerGroup
 * @return
 * @throws IOException
 */
public static FieldViewPanel create(KDSmartDatabase database, Trial trial, VisitOrder2D visitOrder,
        PlotsPerGroup plotsPerGroup, SimplePlotCellRenderer plotRenderer,
        SeparatorVisibilityOption visibilityOption, Component... extras) throws IOException {
    Map<WhyMissing, List<String>> missing = new TreeMap<>();

    Closure<Pair<WhyMissing, MediaFileRecord>> reportMissing = new Closure<Pair<WhyMissing, MediaFileRecord>>() {
        @Override
        public void execute(Pair<WhyMissing, MediaFileRecord> pair) {
            WhyMissing why = pair.first;
            MediaFileRecord mfr = pair.second;
            List<String> list = missing.get(why);
            if (list == null) {
                list = new ArrayList<>();
                missing.put(why, list);
            }
            list.add(mfr.getFilePath());
        }
    };

    int trialId = trial.getTrialId();
    Map<Integer, Plot> plotById = DatabaseUtil.collectPlotsIncludingMediaFiles(database, trialId,
            "FieldViewPanel", SampleGroupChoice.ANY_SAMPLE_GROUP, reportMissing);

    List<Plot> plots = new ArrayList<>(plotById.values());

    if (!missing.isEmpty()) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                StringBuilder html = new StringBuilder("<HTML><DL>");
                for (WhyMissing why : missing.keySet()) {
                    html.append("<DT>").append(why.name()).append("</DT><DD>");
                    List<String> list = missing.get(why);
                    if (list.size() == 1) {
                        html.append(StringUtil.htmlEscape(list.get(0)));
                    } else {
                        html.append("<UL>");
                        for (String s : list) {
                            html.append("<LI>").append(StringUtil.htmlEscape(s)).append("</LI>");
                        }
                        html.append("</UL>");
                    }
                    html.append("</DD>");
                }
                html.append("</DL>");
                MsgBox.warn(null, html.toString(), "Missing Files");
            }
        });
    }

    Map<Integer, Trait> traitMap = new HashMap<>();
    database.getTrialTraits(trialId).stream().forEach(t -> traitMap.put(t.getTraitId(), t));

    List<TraitInstance> traitInstances = new ArrayList<>();
    Predicate<TraitInstance> traitInstanceVisitor = new Predicate<TraitInstance>() {
        @Override
        public boolean evaluate(TraitInstance ti) {
            traitInstances.add(ti);
            return true;
        }
    };
    database.visitTraitInstancesForTrial(trialId, KDSmartDatabase.WithTraitOption.ALL_WITH_TRAITS,
            traitInstanceVisitor);

    PlotVisitList plotVisitList = buildPlotVisitList(trial, visitOrder, plotsPerGroup, traitMap, traitInstances,
            plots);

    if (plotRenderer == null) {
        plotRenderer = new SimplePlotCellRenderer();
    }
    return new FieldViewPanel(plotVisitList, traitMap, visibilityOption, plotRenderer, extras);
}

From source file:com.diversityarrays.kdxplore.importdata.ImportSourceChoiceDialog.java

public ImportSourceChoiceDialog(SourceChoice sc, Window owner, KdxploreDatabase kdxdb, MessagePrinter mp,
        Closure<List<Trial>> onTrialsLoaded, BackgroundRunner backgroundRunner)
        throws IOException, KdxploreConfigException {
    super(owner, "Load Trial Data", ModalityType.APPLICATION_MODAL);

    this.sourceChoice = sc;
    this.kdxDatabase = kdxdb;
    this.databaseDeviceIdentifier = kdxDatabase.getDatabaseDeviceIdentifier();
    this.database = kdxDatabase.getKDXploreKSmartDatabase();
    this.backgroundRunner = backgroundRunner;
    this.messagePrinter = new CompoundMessagePrinter(mp, messagePanel);
    this.onTrialsLoaded = onTrialsLoaded;

    DevicesAndOperators devsAndOps = new DevicesAndOperators(System.getProperty("user.name")); //$NON-NLS-1$
    devAndOpPanel = new DeviceAndOperatorPanel(kdxdb, devsAndOps, true);
    devAndOpPanel.addChangeListener(devAndOpChangeListener);
    // Note: devAndOpPanel.initialise() is done in WindowListener.windowOpened() below 

    StringBuilder sb = new StringBuilder("Drag/Drop ");
    ImportType[] tmp = null;/*from   w  ww . jav  a 2s . c o m*/

    switch (sourceChoice) {
    case CSV:
        predicate = new Predicate<DeviceIdentifier>() {
            @Override
            public boolean evaluate(DeviceIdentifier devid) {
                return devid != null && DeviceIdentifier.PLEASE_SELECT_DEVICE_TYPE != devid.getDeviceType();
            }
        };
        sb.append("CSV");
        tmp = new ImportType[] { ImportType.CSV };
        break;
    case KDX:
        predicate = new Predicate<DeviceIdentifier>() {
            @Override
            public boolean evaluate(DeviceIdentifier devid) {
                if (devid == null || DeviceIdentifier.PLEASE_SELECT_DEVICE_TYPE == devid.getDeviceType()) {
                    return false;
                }
                return DeviceType.KDSMART.equals(devid.getDeviceType());
            }
        };
        sb.append(".KDX");
        tmp = new ImportType[] { ImportType.KDX };
        break;
    case XLS:
        devAndOpPanel.disableAddDevice();
        predicate = new Predicate<DeviceIdentifier>() {
            @Override
            public boolean evaluate(DeviceIdentifier devid) {
                if (devid == null || DeviceIdentifier.PLEASE_SELECT_DEVICE_TYPE == devid.getDeviceType()) {
                    return false;
                }
                return DeviceType.DATABASE.equals(devid.getDeviceType());
            }
        };
        sb.append("Excel");
        tmp = new ImportType[] { ImportType.KDXPLORE_EXCEL, ImportType.BMS_EXCEL };
        break;
    case DATABASE:
    default:
        throw new IllegalStateException("sourceChoice=" + sourceChoice.name());
    }
    importTypes = tmp;
    if (importTypes == null) {
        throw new IllegalArgumentException(sourceChoice.name());
    }

    sb.append(" files here");
    String prompt = sb.toString();

    setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

    Container cp = getContentPane();

    PromptScrollPane pscrollPane = new PromptScrollPane(fileImportTable, prompt);
    pscrollPane.setTransferHandler(flth);
    fileImportTable.setTransferHandler(flth);

    fileImportTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    //      fileImportTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    fileImportTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                updateImportAction();
            }
        }
    });

    final JSplitPane vSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pscrollPane, messagePanel);

    updateImportAction();

    Box buttons = Box.createHorizontalBox();
    buttons.add(Box.createHorizontalStrut(4));
    buttons.add(new JButton(importAction));
    buttons.add(Box.createHorizontalGlue());
    buttons.add(errorMessage);
    buttons.add(Box.createHorizontalGlue());
    buttons.add(new JButton(browseAction));
    buttons.add(Box.createHorizontalStrut(4));

    errorMessage.setForeground(Color.RED);

    JPanel top = new JPanel();
    GBH gbh = new GBH(top, 2, 2, 2, 2);
    int y = 0;

    gbh.add(0, y, 1, 1, GBH.BOTH, 1, 1, GBH.CENTER, devAndOpPanel);
    ++y;

    if (RunMode.getRunMode().isDeveloper()) {
        // Only Developer gets to see the Excel options panel (for now).
        gbh.add(0, y, 3, 1, GBH.BOTH, 2, 2, GBH.CENTER, bmsOptionsPanel);
        ++y;
    }

    gbh.add(0, y, 3, 1, GBH.HORZ, 1, 1, GBH.CENTER, buttons);
    ++y;

    cp.add(top, BorderLayout.NORTH);
    cp.add(vSplit, BorderLayout.CENTER);

    pack();

    GuiUtil.centreOnOwner(ImportSourceChoiceDialog.this);

    addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent e) {
            vSplit.setDividerLocation(0.5);

            // NO_BMS
            bmsOptionsPanel.setVisible(false /* SourceChoice.XLS == sourceChoice */);

            List<Pair<String, Exception>> errors = devAndOpPanel.initialise(predicate);
            if (errors.isEmpty()) {
                List<String> kdxFileNamesWithoutSuffix = new ArrayList<>();
                for (int rowIndex = fileImportTableModel.getRowCount(); --rowIndex >= 0;) {
                    File file = fileImportTableModel.getFileAt(rowIndex);
                    String fname = file.getName();
                    int dotpos = fname.lastIndexOf('.');
                    if (dotpos > 0) {
                        String sfx = fname.substring(dotpos);
                        if (ExportFor.KDX_SUFFIX.equalsIgnoreCase(sfx)) {
                            kdxFileNamesWithoutSuffix.add(fname.substring(0, dotpos));
                        }
                    }
                }

                if (!kdxFileNamesWithoutSuffix.isEmpty()) {
                    devAndOpPanel.selectInitialDeviceIdentifier(kdxFileNamesWithoutSuffix);
                }
            } else {
                for (Pair<String, Exception> pair : errors) {
                    messagePrinter.println(pair.first + ":");
                    messagePrinter.println(pair.second.getMessage());
                }
            }
        }

        @Override
        public void windowClosing(WindowEvent e) {
            if (busy) {
                GuiUtil.beep();
            } else {
                dispose();
            }
        }
    });
}

From source file:com.diversityarrays.kdxplore.curate.CurationTableModel.java

public void setTemporaryValue(CurationCellId ccid, Comparable<?> value) {

    Predicate<PlotOrSpecimen> predicate = new Predicate<PlotOrSpecimen>() {
        @Override/*w  ww  . ja  v a 2s .  com*/
        public boolean evaluate(PlotOrSpecimen pos) {
            return ccid.specimenNumber == pos.getSpecimenNumber() && ccid.plotId == pos.getPlotId();
        }

    };

    int foundRow = -1;
    for (int row = 0; row < plotOrSpecimens.size(); ++row) {
        PlotOrSpecimen pos = plotOrSpecimens.get(row);
        if (predicate.evaluate(pos)) {
            foundRow = row;
            break;
        }
    }

    if (foundRow >= 0) {
        Integer column = getColumnIndexForTraitInstance(ccid.traitInstance);
        if (column != null) {
            Point pt = new Point(column, foundRow);
            if (value == null) {
                temporaryValues.remove(pt);
            } else {
                temporaryValues.put(pt, value);
            }

            this.fireTableCellUpdated(foundRow, column);
        }
    }
}

From source file:com.diversityarrays.kdxplore.trials.TrialOverviewPanel.java

private void refreshTrialTableModel(KdxploreDatabase kdxdb) {
    //TODO ListSelectionModel Everywhere in this file Manil
    //      ListSelectionModel lsm = trialTreeTableModel.getSelectionModel();
    try {/*from ww  w .ja va2 s .c  o m*/
        //         lsm.setValueIsAdjusting(true);
        //         trialsTable.clearSelection();

        if (kdxdb == null) {
            kdxdb = offlineData.getKdxploreDatabase();
        }

        Map<Trial, List<SampleGroup>> trialsAndSampleGroups = kdxdb
                .getTrialsAndSampleGroups(KdxploreDatabase.WithSamplesOption.WITHOUT_SAMPLES);
        trialTableModel.setTrialsAndSampleGroups(trialsAndSampleGroups);

        KDSmartDatabase kdsdb = kdxdb.getKDXploreKSmartDatabase();

        Map<Trial, Map<Trait, Integer>> traitSsoByTrial = new HashMap<>();

        for (Trial trial : trialsAndSampleGroups.keySet()) {

            Predicate<TraitInstance> traitInstanceVisitor = new Predicate<TraitInstance>() {
                @Override
                public boolean evaluate(TraitInstance ti) {
                    Map<Trait, Integer> map = traitSsoByTrial.get(trial);
                    if (map == null) {
                        map = new HashMap<>();
                        traitSsoByTrial.put(trial, map);
                    }
                    map.put(ti.trait, ti.getScoringSortOrder());
                    return Boolean.TRUE;
                }
            };

            kdsdb.visitTraitInstancesForTrial(trial.getTrialId(), WithTraitOption.ALL_WITH_TRAITS,
                    traitInstanceVisitor);
        }

        trialTraitsTableModel.setTraitsByTrial(traitSsoByTrial);

    } catch (IOException e) {
        MsgBox.error(TrialOverviewPanel.this, e.getMessage(), "Problem Getting Trials");
    } finally {
        //         lsm.clearSelection();
        //
        //         int modelRow = trialTreeTableModel.indexOfTrial(selectedTrial);
        //         if (modelRow >= 0) {
        //            int viewRow = trialTreeTableModel.convertRowIndexToView(modelRow);
        //            if (viewRow >= 0) {
        //               lsm.setSelectionInterval(viewRow, viewRow);
        //            }
        //         }

    }
    //      
    //               lsm.setValueIsAdjusting(false);
}

From source file:net.java.treaty.viz.ContractView.java

private void configureRenderer(RenderContext context) {
    context.setVertexLabelTransformer(new Transformer<Object, String>() {
        @Override/*from  www.  ja  v a  2s .co  m*/
        public String transform(Object v) {
            if (v instanceof CompositionNode) {
                CompositionNode c = (CompositionNode) v;
                return asHTMLLabel(c.type.toString(), 3);
            } else if (v instanceof EndNode) {
                EndNode en = (EndNode) v;
                return asHTMLLabel(en.type.toString(), 4);
            } else if (v instanceof ResourceNode) {
                ResourceNode en = (ResourceNode) v;
                if (en.isVirtual())
                    return "<virtual node>";
                Resource r = en.resource;
                return asHTMLLabel(r.getId(), 2);
            } else if (v instanceof RelationshipConditionNode) {
                RelationshipConditionNode en = (RelationshipConditionNode) v;
                String uri = en.condition.getRelationship().toString();
                String l = null;
                if (showConditionURINS) {
                    l = uri;
                } else {
                    int pos = uri.indexOf("#");
                    l = pos > -1 ? uri.substring(pos + 1) : uri;
                }
                return asHTMLLabel(l, 4);
            } else if (v instanceof ExistsConditionNode) {
                return asHTMLLabel("must exist", 4);
            } else if (v instanceof PropertyConditionNode) {
                PropertyConditionNode p = (PropertyConditionNode) v;
                String uri = p.condition.getOperator().toString();
                String l = null;
                if (showConditionURINS) {
                    l = uri;
                } else {
                    int pos = uri.indexOf("#");
                    l = pos > -1 ? uri.substring(pos + 1) : uri;
                }
                return asHTMLLabel(l + " " + p.condition.getValue(), 4);
            } else
                return v.getClass().getName();

        }

        private String asHTMLLabel(String s, int l) {
            StringBuffer b = new StringBuffer();
            b.append("<html>");
            for (int i = 0; i < l; i++) {
                b.append("<br/>");
            }
            b.append(s);
            b.append("</html>");
            return b.toString();
        }

        private String asHTMLLabel(String s) {
            return asHTMLLabel(s, 1);
        }
    });
    context.setVertexIconTransformer(new Transformer<Object, Icon>() {

        @Override
        public Icon transform(Object v) {
            if (v instanceof CompositionNode) {
                CompositionNode n = (CompositionNode) v;
                return getIcon(n.type);
            } else if (v instanceof EndNode) {
                EndNode en = (EndNode) v;
                return getIcon(en.connector, en.type);
            } else if (v instanceof ResourceNode) {
                ResourceNode en = (ResourceNode) v;
                if (en.isVirtual())
                    return null;
                return getIcon(en.resource);
            } else if (v instanceof RelationshipConditionNode) {
                return getIcon(((RelationshipConditionNode) v).condition);
            } else if (v instanceof PropertyConditionNode) {
                return getIcon(((PropertyConditionNode) v).condition);
            } else if (v instanceof ExistsConditionNode) {
                return getIcon(((ExistsConditionNode) v).condition);
            }
            return null;
        }
    });

    context.setEdgeIncludePredicate(new Predicate<Context<Object, Edge>>() {
        @Override
        public boolean evaluate(Context<Object, Edge> edge) {
            return !isVirtualEdge(edge.element);
        }
    });
    context.setVertexIncludePredicate(new Predicate<Context>() {

        @Override
        public boolean evaluate(Context vertex) {
            Object element = vertex.element;
            if (element instanceof Node) {
                return !isVirtualNode((Node) element);
            }
            return true;
        }

    });

    context.setEdgeArrowPredicate(new Predicate() {
        @Override
        public boolean evaluate(Object o) {
            return false;
        }
    });

    context.setEdgeDrawPaintTransformer(new Transformer<Edge, Paint>() {
        @Override
        public Paint transform(Edge e) {
            return getEdgePaint(graph.getSource(e), graph.getDest(e));
        }
    });

    context.setEdgeStrokeTransformer(new Transformer<Edge, Stroke>() {
        @Override
        public Stroke transform(Edge e) {
            return getEdgeStroke(graph.getSource(e), graph.getDest(e));
        }
    });

    // context.setEdgeShapeTransformer(new EdgeShape.Wedge<Object,Edge>(1));
    context.setEdgeShapeTransformer(new EdgeShape.Line<Object, Edge>());
}