List of usage examples for java.util Collection retainAll
boolean retainAll(Collection<?> c);
From source file:org.apache.hyracks.algebricks.core.algebra.operators.logical.visitors.EnforceVariablesVisitor.java
@Override public ILogicalOperator visitExternalDataLookupOperator(ExternalDataLookupOperator op, Collection<LogicalVariable> varsToRecover) throws AlgebricksException { Set<LogicalVariable> liveVars = new HashSet<>(); VariableUtilities.getLiveVariables(op, liveVars); varsToRecover.retainAll(liveVars); if (!varsToRecover.isEmpty()) { op.setPropagateInput(true);//from w ww. jav a 2 s . c om return visitsInputs(op, varsToRecover); } return op; }
From source file:org.wso2.extension.siddhi.store.solr.SolrTable.java
private void upsertSolrDocuments(List<Map<String, Object>> updateConditionParameterMaps, CompiledCondition compiledCondition, List<Map<String, Object>> updateSetParameterMaps, Map<String, CompiledExpression> updateSetCompiledExpressionMap, List<Object[]> addingRecords) throws SolrClientServiceException, SolrServerException, IOException { List<SiddhiSolrDocument> addDocs = new ArrayList<>(); for (int index = 0; index < updateConditionParameterMaps.size(); index++) { Map<String, Object> updateConditionParameterMap = updateConditionParameterMaps.get(index); SolrRecordIterator solrRecordIterator = findRecords(updateConditionParameterMap, compiledCondition); if (solrRecordIterator.hasNext()) { List<String> deleteDocIds = new ArrayList<>(); List<SiddhiSolrDocument> updateDocs = new ArrayList<>(); Map<String, Object> updateSetParameterMap = updateSetParameterMaps.get(index); Map<String, Object> updateFields = new HashMap<>(); for (Map.Entry<String, CompiledExpression> entry : updateSetCompiledExpressionMap.entrySet()) { updateFields.put(entry.getKey(), SolrTableUtils.resolveCondition((SolrCompiledCondition) entry.getValue(), updateSetParameterMap, collectionConfig.getCollectionName())); }//from w w w . j a v a 2 s . c o m Collection<String> updatablePrimaryKeys = updateFields.keySet(); if (primaryKeys != null && !primaryKeys.isEmpty()) { updatablePrimaryKeys.retainAll(primaryKeys); } while (solrRecordIterator.hasNext()) { SiddhiSolrDocument inputDocument = new SiddhiSolrDocument(); SolrDocument document = solrRecordIterator.nextDocument(); addUpdateFieldsToSolrDocument(updateFields, inputDocument); if (!updatablePrimaryKeys.isEmpty() && primaryKeys != null && !primaryKeys.isEmpty()) { deleteDocIds.add(inputDocument.getFieldValue(SolrSchemaField.FIELD_ID).toString()); inputDocument.setField(SolrSchemaField.FIELD_ID, SolrTableUtils.generateRecordIdFromPrimaryKeyValues(inputDocument, primaryKeys)); } else { inputDocument.setField(SolrSchemaField.FIELD_ID, document.getFieldValue(SolrSchemaField.FIELD_ID)); } updateDocs.add(inputDocument); if (updateDocs.size() == updateBatchSize) { solrClientService.insertDocuments(collectionConfig.getCollectionName(), updateDocs, commitAsync); solrClientService.deleteDocuments(collectionConfig.getCollectionName(), deleteDocIds, commitAsync); updateDocs = new ArrayList<>(); deleteDocIds = new ArrayList<>(); } } if (!deleteDocIds.isEmpty()) { solrClientService.deleteDocuments(collectionConfig.getCollectionName(), deleteDocIds, commitAsync); } if (!updateDocs.isEmpty()) { solrClientService.insertDocuments(collectionConfig.getCollectionName(), updateDocs, commitAsync); } } else { addDocs = getNewSolrDocuments(addingRecords, index); } if (!addDocs.isEmpty()) { solrClientService.insertDocuments(collectionConfig.getCollectionName(), addDocs, commitAsync); } } }
From source file:nl.strohalm.cyclos.services.ads.AdServiceSecurity.java
private boolean applyQueryRestrictions(final AbstractAdQuery query) { Collection<MemberGroup> visibleGroups = adService.visibleGroupsForAds(); if (CollectionUtils.isEmpty(visibleGroups)) { return false; }//w w w . j av a 2s .c om if (CollectionUtils.isNotEmpty(query.getGroupFilters())) { // When there are group filters, make sure only visible groups of those group filters will be used Collection<MemberGroup> groups = new HashSet<MemberGroup>(); List<GroupFilter> groupFilters = fetchService.fetch(query.getGroupFilters(), GroupFilter.Relationships.GROUPS); for (GroupFilter groupFilter : groupFilters) { groups.addAll(groupFilter.getGroups()); } groups.retainAll(visibleGroups); query.setGroupFilters(null); if (CollectionUtils.isEmpty(query.getGroups())) { query.setGroups(groups); } else { query.getGroups().retainAll(groups); } } query.setGroups(PermissionHelper.checkSelection(visibleGroups, query.getGroups())); Member owner = fetchService.fetch(query.getOwner(), Element.Relationships.GROUP); if (owner != null && !visibleGroups.contains(owner.getGroup())) { return false; } if (owner != null && !permissionService.manages(owner)) { // Non-managers can only see active ads query.setStatus(ACTIVE); } return true; }
From source file:org.phenotips.data.similarity.internal.DefaultPatientSimilarityView.java
/** * Finds the best term match, removes these terms, and return the JSON for that match. * * @param refTerms the terms in the reference * @param matchTerms the terms in the match * @param matchFeatureLookup a mapping from VocabularyTerm IDs back to the original Features in the match patient * @param refFeatureLookup a mapping from VocabularyTerm IDs back to the original Features in the reference patient * @return the FeatureClusterView of the best-matching features from refTerms and matchTerms (removes the matched * terms from the passed lists) or null if the terms are not a good match (the term collections are then * unchanged)/*from ww w . j ava 2s. com*/ */ private FeatureClusterView popBestFeatureCluster(Collection<VocabularyTerm> matchTerms, Collection<VocabularyTerm> refTerms, Map<String, Feature> matchFeatureLookup, Map<String, Feature> refFeatureLookup) { Collection<VocabularyTerm> sharedAncestors = getAncestors(refTerms); sharedAncestors.retainAll(getAncestors(matchTerms)); // Find ancestor with highest (normalized) information content VocabularyTerm ancestor = null; double ancestorScore = Double.NEGATIVE_INFINITY; for (VocabularyTerm term : sharedAncestors) { Double termIC = termICs.get(term); if (termIC == null) { termIC = 0.0; } double termScore = termIC / maxIC; if (termScore > ancestorScore) { ancestorScore = termScore; ancestor = term; } } // If the top-scoring ancestor is the root (or phenotype root), report everything remaining as unmatched if (ancestor == null || HP_ROOT.equals(ancestor.getId()) || PHENOTYPE_ROOT.equals(ancestor.getId())) { return null; } // Find, remove, and return all ref and match terms under the selected ancestor Collection<VocabularyTerm> matchMatched = popTermsWithAncestor(matchTerms, ancestor); Collection<VocabularyTerm> refMatched = popTermsWithAncestor(refTerms, ancestor); // Return match json from matched terms FeatureClusterView cluster = createFeatureClusterView(termsToFeatures(matchMatched, matchFeatureLookup), termsToFeatures(refMatched, refFeatureLookup), this.access, ancestor, ancestorScore); return cluster; }
From source file:com.google.code.facebook.graph.sna.applet.VertexCollapseDemoWithLayouts.java
public VertexCollapseDemoWithLayouts() { // create a simple graph for the demo graph = TestGraphs.getOneComponentGraph(); collapsedGraph = graph;//w ww.j a v a2 s .co m collapser = new GraphCollapser(graph); layout = new FRLayout(graph); Dimension preferredSize = new Dimension(400, 400); final VisualizationModel visualizationModel = new DefaultVisualizationModel(layout, preferredSize); vv = new VisualizationViewer(visualizationModel, preferredSize); vv.getRenderContext().setVertexShapeTransformer(new ClusterVertexShapeFunction()); final PredicatedParallelEdgeIndexFunction eif = PredicatedParallelEdgeIndexFunction.getInstance(); final Set exclusions = new HashSet(); eif.setPredicate(new Predicate() { public boolean evaluate(Object e) { return exclusions.contains(e); } }); vv.getRenderContext().setParallelEdgeIndexFunction(eif); vv.setBackground(Color.white); // add a listener for ToolTips vv.setVertexToolTipTransformer(new ToStringLabeller() { /* (non-Javadoc) * @see edu.uci.ics.jung.visualization.decorators.DefaultToolTipFunction#getToolTipText(java.lang.Object) */ @Override public String transform(Object v) { if (v instanceof Graph) { return ((Graph) v).getVertices().toString(); } return super.transform(v); } }); /** * the regular graph mouse for the normal view */ final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse(); vv.setGraphMouse(graphMouse); Container content = getContentPane(); GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv); content.add(gzsp); JComboBox modeBox = graphMouse.getModeComboBox(); modeBox.addItemListener(graphMouse.getModeListener()); graphMouse.setMode(ModalGraphMouse.Mode.PICKING); final ScalingControl scaler = new CrossoverScalingControl(); JButton plus = new JButton("+"); plus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1.1f, vv.getCenter()); } }); JButton minus = new JButton("-"); minus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1 / 1.1f, vv.getCenter()); } }); JButton collapse = new JButton("Collapse"); collapse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Collection picked = new HashSet(vv.getPickedVertexState().getPicked()); if (picked.size() > 1) { Graph inGraph = layout.getGraph(); Graph clusterGraph = collapser.getClusterGraph(inGraph, picked); Graph g = collapser.collapse(layout.getGraph(), clusterGraph); collapsedGraph = g; double sumx = 0; double sumy = 0; for (Object v : picked) { Point2D p = (Point2D) layout.transform(v); sumx += p.getX(); sumy += p.getY(); } Point2D cp = new Point2D.Double(sumx / picked.size(), sumy / picked.size()); vv.getRenderContext().getParallelEdgeIndexFunction().reset(); layout.setGraph(g); layout.setLocation(clusterGraph, cp); vv.getPickedVertexState().clear(); vv.repaint(); } } }); JButton compressEdges = new JButton("Compress Edges"); compressEdges.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Collection picked = vv.getPickedVertexState().getPicked(); if (picked.size() == 2) { Pair pair = new Pair(picked); Graph graph = layout.getGraph(); Collection edges = new HashSet(graph.getIncidentEdges(pair.getFirst())); edges.retainAll(graph.getIncidentEdges(pair.getSecond())); exclusions.addAll(edges); vv.repaint(); } } }); JButton expandEdges = new JButton("Expand Edges"); expandEdges.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Collection picked = vv.getPickedVertexState().getPicked(); if (picked.size() == 2) { Pair pair = new Pair(picked); Graph graph = layout.getGraph(); Collection edges = new HashSet(graph.getIncidentEdges(pair.getFirst())); edges.retainAll(graph.getIncidentEdges(pair.getSecond())); exclusions.removeAll(edges); vv.repaint(); } } }); JButton expand = new JButton("Expand"); expand.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Collection picked = new HashSet(vv.getPickedVertexState().getPicked()); for (Object v : picked) { if (v instanceof Graph) { Graph g = collapser.expand(layout.getGraph(), (Graph) v); vv.getRenderContext().getParallelEdgeIndexFunction().reset(); layout.setGraph(g); } vv.getPickedVertexState().clear(); vv.repaint(); } } }); JButton reset = new JButton("Reset"); reset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { layout.setGraph(graph); exclusions.clear(); vv.repaint(); } }); JButton help = new JButton("Help"); help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog((JComponent) e.getSource(), instructions, "Help", JOptionPane.PLAIN_MESSAGE); } }); Class[] combos = getCombos(); final JComboBox jcb = new JComboBox(combos); // use a renderer to shorten the layout name presentation jcb.setRenderer(new DefaultListCellRenderer() { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String valueString = value.toString(); valueString = valueString.substring(valueString.lastIndexOf('.') + 1); return super.getListCellRendererComponent(list, valueString, index, isSelected, cellHasFocus); } }); jcb.addActionListener(new LayoutChooser(jcb, vv)); jcb.setSelectedItem(FRLayout.class); JPanel controls = new JPanel(); JPanel zoomControls = new JPanel(new GridLayout(2, 1)); zoomControls.setBorder(BorderFactory.createTitledBorder("Zoom")); zoomControls.add(plus); zoomControls.add(minus); controls.add(zoomControls); JPanel collapseControls = new JPanel(new GridLayout(3, 1)); collapseControls.setBorder(BorderFactory.createTitledBorder("Picked")); collapseControls.add(collapse); collapseControls.add(expand); collapseControls.add(compressEdges); collapseControls.add(expandEdges); collapseControls.add(reset); controls.add(collapseControls); controls.add(modeBox); controls.add(help); controls.add(jcb); content.add(controls, BorderLayout.SOUTH); }
From source file:org.squashtest.tm.service.internal.requirement.CustomRequirementVersionManagerServiceImpl.java
@Override public Collection<Long> findBindedMilestonesIdForMassModif(List<Long> reqVersionIds) { Collection<Milestone> milestones = null; for (Long reqVersionId : reqVersionIds) { Set<Milestone> mil = requirementVersionDao.findOne(reqVersionId).getMilestones(); if (milestones != null) { // keep only milestone that in ALL selected requirementVersion milestones.retainAll(mil); } else {//from w w w .ja va2 s . c o m // populate the collection for the first time milestones = new ArrayList<>(mil); } } filterLockedAndPlannedStatus(milestones); return CollectionUtils.collect(milestones, new Transformer() { @Override public Object transform(Object milestone) { return ((Milestone) milestone).getId(); } }); }
From source file:com.castlemock.web.mock.rest.web.rest.controller.AbstractRestServiceController.java
/** * The method is responsible for mocking a REST service. The method will identify which mocked response * will be returned.//from w ww . j ava2 s. c om * @param restMethod The REST method which the incoming request belongs to * @return Returns a selected mocked response which will be returned to the service consumer */ protected RestResponseDto mockResponse(final RestRequestDto restRequest, final String projectId, final String applicationId, final String resourceId, final RestMethodDto restMethod) { // Extract the accept header value. final Collection<String> acceptHeaderValues = getHeaderValues(ACCEPT_HEADER, restRequest.getHttpHeaders()); // Iterate through all mocked responses and extract the ones // that are active. final List<RestMockResponseDto> enabledMockResponses = new ArrayList<RestMockResponseDto>(); for (RestMockResponseDto mockResponse : restMethod.getMockResponses()) { if (mockResponse.getStatus().equals(RestMockResponseStatus.ENABLED)) { enabledMockResponses.add(mockResponse); } } List<RestMockResponseDto> mockResponses = new ArrayList<>(); if (acceptHeaderValues != null) { // Find request that matches the accept header. for (RestMockResponseDto mockResponse : enabledMockResponses) { // The accept header has to match the content type. final Collection<String> mockResponseContentTypeValues = getHeaderValues(CONTENT_TYPE, mockResponse.getHttpHeaders()); mockResponseContentTypeValues.retainAll(acceptHeaderValues); if (!mockResponseContentTypeValues.isEmpty()) { mockResponses.add(mockResponse); } } } // If no mock responses are matching the accept header, then // any mock response will do. if (mockResponses.isEmpty()) { mockResponses.addAll(enabledMockResponses); } RestMockResponseDto mockResponse = null; if (mockResponses.isEmpty()) { throw new RestException("No mocked response created for operation " + restMethod.getName()); } else if (restMethod.getResponseStrategy().equals(RestResponseStrategy.RANDOM)) { final Integer responseIndex = RANDOM.nextInt(mockResponses.size()); mockResponse = mockResponses.get(responseIndex); } else if (restMethod.getResponseStrategy().equals(RestResponseStrategy.SEQUENCE)) { Integer currentSequenceNumber = restMethod.getCurrentResponseSequenceIndex(); if (currentSequenceNumber >= mockResponses.size()) { currentSequenceNumber = 0; } mockResponse = mockResponses.get(currentSequenceNumber); serviceProcessor.process(new UpdateCurrentRestMockResponseSequenceIndexInput(projectId, applicationId, resourceId, restMethod.getId(), currentSequenceNumber + 1)); } if (mockResponse == null) { throw new RestException("No mocked response created for operation " + restMethod.getName()); } String body = mockResponse.getBody(); if (mockResponse.isUsingExpressions()) { // Parse the text and apply expression functionality if // the mock response is configured to use expressions body = TextParser.parse(body); } final RestResponseDto response = new RestResponseDto(); response.setBody(body); response.setMockResponseName(mockResponse.getName()); response.setHttpStatusCode(mockResponse.getHttpStatusCode()); response.setHttpHeaders(mockResponse.getHttpHeaders()); return response; }
From source file:org.squashtest.tm.service.internal.requirement.CustomRequirementVersionManagerServiceImpl.java
@Override public Collection<Milestone> findAssociableMilestonesForMassModif(List<Long> reqVersionIds) { Collection<Milestone> milestones = null; for (Long reqVersionId : reqVersionIds) { List<Milestone> mil = requirementVersionDao.findOne(reqVersionId).getProject().getMilestones(); if (milestones != null) { // keep only milestone that in ALL selected requirementVersion milestones.retainAll(mil); } else {// w ww. j a v a 2 s.com // populate the collection for the first time milestones = new ArrayList<>(mil); } } filterLockedAndPlannedStatus(milestones); return milestones; }
From source file:hu.ppke.itk.nlpg.purepos.decoder.AbstractDecoder.java
protected Collection<Integer> filterTagsWithMorphology(Collection<Integer> tags, Collection<Integer> anals, ITagMapper<Integer> mapper) { Collection<Integer> common; if (anals != null) { if (mapper != null) { common = mapper.filter(anals, tags); } else {//from w w w. jav a 2 s. co m common = new HashSet<Integer>(anals); common.retainAll(tags); } if (common.size() > 0) return common; } return tags; }
From source file:de.hpi.petrinet.PetriNet.java
/** * Checks whether the net is a free choice net. * //ww w. j a v a2s.co m * @return true, if the net is free-choice */ public boolean isFreeChoiceNet() { boolean isFC = true; outer: for (Transition t1 : this.getTransitions()) { for (Transition t2 : this.getTransitions()) { if (t1.equals(t2)) continue; Collection<Node> preT1 = t1.getPrecedingNodes(); Collection<Node> preT2 = t2.getPrecedingNodes(); if (CollectionUtils.containsAny(preT1, preT2)) { preT1.retainAll(preT2); boolean tmp = (preT1.size() == preT2.size()); isFC &= tmp; if (!isFC) break outer; } } } return isFC; }