List of usage examples for java.util HashSet forEach
default void forEach(Consumer<? super T> action)
From source file:no.ntnu.okse.web.controller.TopicController.java
/** * This method deletes all topics registered in the TopicService * * @return A JSON serialized string/*from w ww. jav a 2 s . co m*/ */ @RequestMapping(method = RequestMethod.DELETE, value = DELETE_ALL_TOPICS) public @ResponseBody String deleteAllTopics() { log.info("Deleting all topics"); TopicService ts = TopicService.getInstance(); HashSet<Topic> allRootTopics = ts.getAllRootTopics(); allRootTopics.forEach(t -> ts.deleteTopic(t.getFullTopicString())); return "{ \"messages\" :\"The topic were successfully deleted\" }"; }
From source file:com.hurence.logisland.processor.MatchIP.java
@Override protected Collection<Record> internalProcess(ProcessContext context, Collection<Record> records) { // convert all numeric fields to double to get numeric range working ... final List<Record> outRecords = new ArrayList<>(); final List<InputDocument> inputDocs = new ArrayList<>(); final Map<String, Record> inputRecords = new HashMap<>(); for (final Record record : records) { final InputDocument.Builder docbuilder = InputDocument.builder(record.getId()); for (final String fieldName : record.getAllFieldNames()) { if (luceneAttrsToQuery.contains(fieldName) && record.getField(fieldName).getRawValue() != null) { String ip = record.getField(fieldName).asString(); // Check the value is an IPv4 address or ignore Matcher checkIp = ipPattern.matcher(ip); if (checkIp.lookingAt()) { long ipLong = ipToLong(ip); docbuilder.addField(fieldName, String.valueOf(ipLong), keywordAnalyzer); }//w ww . j av a 2s . c o m } } inputDocs.add(docbuilder.build()); inputRecords.put(record.getId(), record); } // match a batch of documents Matches<QueryMatch> matches; try { matches = monitor.match(DocumentBatch.of(inputDocs), SimpleMatcher.FACTORY); } catch (IOException e) { getLogger().error("Could not match documents", e); return outRecords; } MatchHandlers.MatchHandler _matchHandler = null; if (onMatchPolicy == OnMatchPolicy.first && onMissPolicy == OnMissPolicy.discard) { // Legacy behaviour _matchHandler = new MatchHandlers.LegacyMatchHandler(); } else if (onMissPolicy == OnMissPolicy.discard) { // Ignore non matching records. Concat all query information (name, value) instead of first one only. _matchHandler = new MatchHandlers.ConcatMatchHandler(); } else { // All records in, all records out. Concat all query information (name, value) instead of first one only. _matchHandler = new MatchHandlers.AllInAllOutMatchHandler(records, this.onMatchPolicy); } final MatchHandlers.MatchHandler matchHandler = _matchHandler; for (DocumentMatches<QueryMatch> docMatch : matches) { docMatch.getMatches() .forEach(queryMatch -> matchHandler.handleMatch(inputRecords.get(docMatch.getDocId()), context, matchingRules.get(queryMatch.getQueryId()), recordTypeUpdatePolicy)); } if (ipRegexps != null && ipRegexps.size() > 0) { inputRecords.keySet().forEach((k) -> { // Only consider records that have not matched any IP rules yet int count = matches.getMatchCount(k); if (count == 0) { // Apply regexp rules if any available for (String ipAttrName : ipRegexps.keySet()) { if (inputRecords.get(k).hasField(ipAttrName) && (inputRecords.get(k).getField(ipAttrName).getRawValue() != null)) { HashSet<Pair<String, Pattern>> ipRegexHashset = ipRegexps.get(ipAttrName); ipRegexHashset.forEach(p -> { String ruleName = p.getLeft(); Pattern ipRegexPattern = p.getRight(); String attrValueToMatch = inputRecords.get(k).getField(ipAttrName).asString(); Matcher ipMatcher = ipRegexPattern.matcher(attrValueToMatch); if (ipMatcher.lookingAt()) { // This is a match ! matchHandler.handleMatch(inputRecords.get(k), context, regexpMatchingRules.get(ruleName), recordTypeUpdatePolicy); } }); } } } }); } return matchHandler.outputRecords(); }
From source file:com.flipkart.flux.resource.StateMachineResource.java
private FsmGraph getGraphData(Long fsmId) throws IOException { StateMachine stateMachine = stateMachinesDAO.findById(fsmId); if (stateMachine == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); }/*from w ww. ja v a 2 s .co m*/ final FsmGraph fsmGraph = new FsmGraph(); Map<String, Event> stateMachineEvents = eventsDAO.findBySMInstanceId(fsmId).stream() .collect(Collectors.<Event, String, Event>toMap(Event::getName, (event -> event))); Set<String> allOutputEventNames = new HashSet<>(); final RAMContext ramContext = new RAMContext(System.currentTimeMillis(), null, stateMachine); /* After this operation, we'll have nodes for each state and its corresponding output event along with the output event's dependencies mapped out*/ for (State state : stateMachine.getStates()) { if (state.getOutputEvent() != null) { EventDefinition eventDefinition = objectMapper.readValue(state.getOutputEvent(), EventDefinition.class); final Event outputEvent = stateMachineEvents.get(eventDefinition.getName()); final FsmGraphVertex vertex = new FsmGraphVertex(state.getId(), getDisplayName(state.getName())); fsmGraph.addVertex(vertex, new FsmGraphEdge(getDisplayName(outputEvent.getName()), outputEvent.getStatus().name(), outputEvent.getEventSource())); final Set<State> dependantStates = ramContext.getDependantStates(outputEvent.getName()); dependantStates.forEach((aState) -> fsmGraph.addOutgoingEdge(vertex, aState.getId())); allOutputEventNames.add(outputEvent.getName()); // we collect all output event names and use them below. } else { fsmGraph.addVertex(new FsmGraphVertex(state.getId(), this.getDisplayName(state.getName())), null); } } /* Handle states with no dependencies, i.e the states that can be triggered as soon as we execute the state machine */ final Set<State> initialStates = ramContext.getInitialStates(Collections.emptySet());// hackety hack. We're fooling the context to give us only events that depend on nothing if (!initialStates.isEmpty()) { final FsmGraphEdge initEdge = new FsmGraphEdge(TRIGGER, Event.EventStatus.triggered.name(), TRIGGER); initialStates.forEach((state) -> { initEdge.addOutgoingVertex(state.getId()); }); fsmGraph.addInitStateEdge(initEdge); } /* Now we handle events that were not "output-ed" by any state, which means that they were given to the workflow at the time of invocation or supplied externally*/ final HashSet<String> eventsGivenOnWorkflowTrigger = new HashSet<>(stateMachineEvents.keySet()); eventsGivenOnWorkflowTrigger.removeAll(allOutputEventNames); eventsGivenOnWorkflowTrigger.forEach((workflowTriggeredEventName) -> { final Event correspondingEvent = stateMachineEvents.get(workflowTriggeredEventName); final FsmGraphEdge initEdge = new FsmGraphEdge(this.getDisplayName(workflowTriggeredEventName), correspondingEvent.getStatus().name(), correspondingEvent.getEventSource()); final Set<State> dependantStates = ramContext.getDependantStates(workflowTriggeredEventName); dependantStates.forEach((state) -> initEdge.addOutgoingVertex(state.getId())); fsmGraph.addInitStateEdge(initEdge); }); return fsmGraph; }
From source file:org.apache.samza.execution.JobNodeConfigurationGenerator.java
/** * Serializes the {@link Serde} instances for operators, adds them to the provided config, and * sets the serde configuration for the input/output/intermediate streams appropriately. * * We try to preserve the number of Serde instances before and after serialization. However we don't * guarantee that references shared between these serdes instances (e.g. an Jackson ObjectMapper shared * between two json serdes) are shared after deserialization too. * * Ideally all the user defined objects in the application should be serialized and de-serialized in one pass * from the same output/input stream so that we can maintain reference sharing relationships. * * @param configs the configs to add serialized serde instances and stream serde configs to *//*from w ww. j av a2s .c o m*/ private void configureSerdes(Map<String, String> configs, Map<String, StreamEdge> inEdges, Map<String, StreamEdge> outEdges, List<StoreDescriptor> stores, Collection<String> tables, JobNode jobNode) { // collect all key and msg serde instances for streams Map<String, Serde> streamKeySerdes = new HashMap<>(); Map<String, Serde> streamMsgSerdes = new HashMap<>(); inEdges.keySet().forEach(streamId -> addSerdes(jobNode.getInputSerdes(streamId), streamId, streamKeySerdes, streamMsgSerdes)); outEdges.keySet().forEach(streamId -> addSerdes(jobNode.getOutputSerde(streamId), streamId, streamKeySerdes, streamMsgSerdes)); Map<String, Serde> storeKeySerdes = new HashMap<>(); Map<String, Serde> storeMsgSerdes = new HashMap<>(); stores.forEach(storeDescriptor -> { storeKeySerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getKeySerde()); storeMsgSerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getMsgSerde()); }); Map<String, Serde> tableKeySerdes = new HashMap<>(); Map<String, Serde> tableMsgSerdes = new HashMap<>(); tables.forEach(tableId -> { addSerdes(jobNode.getTableSerdes(tableId), tableId, tableKeySerdes, tableMsgSerdes); }); // for each unique stream or store serde instance, generate a unique name and serialize to config HashSet<Serde> serdes = new HashSet<>(streamKeySerdes.values()); serdes.addAll(streamMsgSerdes.values()); serdes.addAll(storeKeySerdes.values()); serdes.addAll(storeMsgSerdes.values()); serdes.addAll(tableKeySerdes.values()); serdes.addAll(tableMsgSerdes.values()); SerializableSerde<Serde> serializableSerde = new SerializableSerde<>(); Base64.Encoder base64Encoder = Base64.getEncoder(); Map<Serde, String> serdeUUIDs = new HashMap<>(); serdes.forEach(serde -> { String serdeName = serdeUUIDs.computeIfAbsent(serde, s -> serde.getClass().getSimpleName() + "-" + UUID.randomUUID().toString()); configs.putIfAbsent(String.format(SerializerConfig.SERDE_SERIALIZED_INSTANCE(), serdeName), base64Encoder.encodeToString(serializableSerde.toBytes(serde))); }); // set key and msg serdes for streams to the serde names generated above streamKeySerdes.forEach((streamId, serde) -> { String streamIdPrefix = String.format(StreamConfig.STREAM_ID_PREFIX(), streamId); String keySerdeConfigKey = streamIdPrefix + StreamConfig.KEY_SERDE(); configs.put(keySerdeConfigKey, serdeUUIDs.get(serde)); }); streamMsgSerdes.forEach((streamId, serde) -> { String streamIdPrefix = String.format(StreamConfig.STREAM_ID_PREFIX(), streamId); String valueSerdeConfigKey = streamIdPrefix + StreamConfig.MSG_SERDE(); configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde)); }); // set key and msg serdes for stores to the serde names generated above storeKeySerdes.forEach((storeName, serde) -> { String keySerdeConfigKey = String.format(StorageConfig.KEY_SERDE, storeName); configs.put(keySerdeConfigKey, serdeUUIDs.get(serde)); }); storeMsgSerdes.forEach((storeName, serde) -> { String msgSerdeConfigKey = String.format(StorageConfig.MSG_SERDE, storeName); configs.put(msgSerdeConfigKey, serdeUUIDs.get(serde)); }); // set key and msg serdes for stores to the serde names generated above tableKeySerdes.forEach((tableId, serde) -> { String keySerdeConfigKey = String.format(JavaTableConfig.STORE_KEY_SERDE, tableId); configs.put(keySerdeConfigKey, serdeUUIDs.get(serde)); }); tableMsgSerdes.forEach((tableId, serde) -> { String valueSerdeConfigKey = String.format(JavaTableConfig.STORE_MSG_SERDE, tableId); configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde)); }); }
From source file:org.apache.samza.execution.JobNode.java
/** * Serializes the {@link Serde} instances for operators, adds them to the provided config, and * sets the serde configuration for the input/output/intermediate streams appropriately. * * We try to preserve the number of Serde instances before and after serialization. However we don't * guarantee that references shared between these serdes instances (e.g. an Jackson ObjectMapper shared * between two json serdes) are shared after deserialization too. * * Ideally all the user defined objects in the application should be serialized and de-serialized in one pass * from the same output/input stream so that we can maintain reference sharing relationships. * * @param configs the configs to add serialized serde instances and stream serde configs to *//*from w w w . j a v a2 s . c om*/ void addSerdeConfigs(Map<String, String> configs) { // collect all key and msg serde instances for streams Map<String, Serde> streamKeySerdes = new HashMap<>(); Map<String, Serde> streamMsgSerdes = new HashMap<>(); Map<StreamSpec, InputOperatorSpec> inputOperators = streamGraph.getInputOperators(); inEdges.forEach(edge -> { String streamId = edge.getStreamSpec().getId(); InputOperatorSpec inputOperatorSpec = inputOperators.get(edge.getStreamSpec()); streamKeySerdes.put(streamId, inputOperatorSpec.getKeySerde()); streamMsgSerdes.put(streamId, inputOperatorSpec.getValueSerde()); }); Map<StreamSpec, OutputStreamImpl> outputStreams = streamGraph.getOutputStreams(); outEdges.forEach(edge -> { String streamId = edge.getStreamSpec().getId(); OutputStreamImpl outputStream = outputStreams.get(edge.getStreamSpec()); streamKeySerdes.put(streamId, outputStream.getKeySerde()); streamMsgSerdes.put(streamId, outputStream.getValueSerde()); }); // collect all key and msg serde instances for stores Map<String, Serde> storeKeySerdes = new HashMap<>(); Map<String, Serde> storeMsgSerdes = new HashMap<>(); streamGraph.getAllOperatorSpecs().forEach(opSpec -> { if (opSpec instanceof StatefulOperatorSpec) { ((StatefulOperatorSpec) opSpec).getStoreDescriptors().forEach(storeDescriptor -> { storeKeySerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getKeySerde()); storeMsgSerdes.put(storeDescriptor.getStoreName(), storeDescriptor.getMsgSerde()); }); } }); // collect all key and msg serde instances for tables Map<String, Serde> tableKeySerdes = new HashMap<>(); Map<String, Serde> tableValueSerdes = new HashMap<>(); tables.forEach(tableSpec -> { tableKeySerdes.put(tableSpec.getId(), tableSpec.getSerde().getKeySerde()); tableValueSerdes.put(tableSpec.getId(), tableSpec.getSerde().getValueSerde()); }); // for each unique stream or store serde instance, generate a unique name and serialize to config HashSet<Serde> serdes = new HashSet<>(streamKeySerdes.values()); serdes.addAll(streamMsgSerdes.values()); serdes.addAll(storeKeySerdes.values()); serdes.addAll(storeMsgSerdes.values()); serdes.addAll(tableKeySerdes.values()); serdes.addAll(tableValueSerdes.values()); SerializableSerde<Serde> serializableSerde = new SerializableSerde<>(); Base64.Encoder base64Encoder = Base64.getEncoder(); Map<Serde, String> serdeUUIDs = new HashMap<>(); serdes.forEach(serde -> { String serdeName = serdeUUIDs.computeIfAbsent(serde, s -> serde.getClass().getSimpleName() + "-" + UUID.randomUUID().toString()); configs.putIfAbsent(String.format(SerializerConfig.SERDE_SERIALIZED_INSTANCE(), serdeName), base64Encoder.encodeToString(serializableSerde.toBytes(serde))); }); // set key and msg serdes for streams to the serde names generated above streamKeySerdes.forEach((streamId, serde) -> { String streamIdPrefix = String.format(StreamConfig.STREAM_ID_PREFIX(), streamId); String keySerdeConfigKey = streamIdPrefix + StreamConfig.KEY_SERDE(); configs.put(keySerdeConfigKey, serdeUUIDs.get(serde)); }); streamMsgSerdes.forEach((streamId, serde) -> { String streamIdPrefix = String.format(StreamConfig.STREAM_ID_PREFIX(), streamId); String valueSerdeConfigKey = streamIdPrefix + StreamConfig.MSG_SERDE(); configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde)); }); // set key and msg serdes for stores to the serde names generated above storeKeySerdes.forEach((storeName, serde) -> { String keySerdeConfigKey = String.format(StorageConfig.KEY_SERDE(), storeName); configs.put(keySerdeConfigKey, serdeUUIDs.get(serde)); }); storeMsgSerdes.forEach((storeName, serde) -> { String msgSerdeConfigKey = String.format(StorageConfig.MSG_SERDE(), storeName); configs.put(msgSerdeConfigKey, serdeUUIDs.get(serde)); }); // set key and msg serdes for tables to the serde names generated above tableKeySerdes.forEach((tableId, serde) -> { String keySerdeConfigKey = String.format(JavaTableConfig.TABLE_KEY_SERDE, tableId); configs.put(keySerdeConfigKey, serdeUUIDs.get(serde)); }); tableValueSerdes.forEach((tableId, serde) -> { String valueSerdeConfigKey = String.format(JavaTableConfig.TABLE_VALUE_SERDE, tableId); configs.put(valueSerdeConfigKey, serdeUUIDs.get(serde)); }); }
From source file:com.example.app.profile.ui.user.ProfileMembershipManagement.java
@Override public void init() { super.init(); setValidator(CompositeValidator.of((component, notifiable) -> validateSupporters(notifiable), (component, notifiable) -> { if (_requiredMembershipTypes.isEmpty()) return true; final HashSet<MembershipType> toCheck = new HashSet<>(_requiredMembershipTypes); getProfile().getMembershipSet() .forEach(membership -> toCheck.remove(membership.getMembershipType())); toCheck.forEach(mt -> { NotificationImpl notification = new NotificationImpl(NotificationType.ERROR, createText(CommonValidationText.ARG0_IS_REQUIRED, mt.getName())); notification.setSource(this); notifiable.sendNotification(notification); });/*from ww w. j ava 2s.co m*/ return toCheck.isEmpty(); })); User currentUser = _userDAO.getAssertedCurrentUser(); Hibernate.initialize(currentUser); Hibernate.initialize(currentUser.getPrincipal()); Hibernate.initialize(currentUser.getPrincipal().getContact()); final Profile adminProfile = getProfile(); final TimeZone timeZone = getSession().getTimeZone(); boolean isAdminish = _profileDAO.canOperate(currentUser, adminProfile, timeZone, _mop.modifyCompany()); if (!_profileDAO.canOperate(currentUser, adminProfile, timeZone, _mop.modifyUserRoles())) { Label label = new Label(INSUFFICIENT_PERMISSIONS(MEMBERSHIP())).withHTMLElement(HTMLElement.h3); setDefaultComponent(label); return; } final SimpleDateFormat dateFormat = getDateFormat(getLocaleContext().getLocale()); dateFormat.setTimeZone(getSession().getTimeZone()); final DateFormatLabel dateRenderer = new DateFormatLabel(dateFormat) { @Override public Component getTableCellRendererComponent(Table table, Object cellValue, boolean isSelected, boolean hasFocus, int row, int column) { Date value = (Date) cellValue; value = toDate(convertFromPersisted(value, getSession().getTimeZone())); return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } }; final NamedObjectComparator nocComparator = new NamedObjectComparator(getLocaleContext()); FixedValueColumn actionColumn = new FixedValueColumn(); actionColumn.setColumnName(CommonColumnText.ACTIONS); PropertyColumn userColumn = new PropertyColumn(Membership.class, Membership.USER_PROP); userColumn.setColumnName(CommonColumnText.USER); userColumn.setComparator(nocComparator); PropertyColumn membershipTypeColumn = new PropertyColumn(Membership.class, Membership.MEMBERSHIP_TYPE_PROP); membershipTypeColumn.setColumnName(MEMBERSHIP_TYPE()); membershipTypeColumn.setComparator(nocComparator); PropertyColumn membershipDStartColumn = new PropertyColumn(Membership.class, Membership.START_DATE_PROP); membershipDStartColumn.setColumnName(START_DATE()); membershipDStartColumn.setComparator(ComparableComparator.getInstance()); PropertyColumn membershipDEndColumn = new PropertyColumn(Membership.class, Membership.END_DATE_PROP); membershipDEndColumn.setComparator(ComparableComparator.getInstance()); membershipDEndColumn.setColumnName(END_DATE()); _membershipTable = isAllowEditActive() ? new DataColumnTable<>(actionColumn, userColumn, membershipTypeColumn, membershipDStartColumn, membershipDEndColumn) : new DataColumnTable<>(actionColumn, userColumn, membershipTypeColumn); _membershipTable.setTableCellRenderer(dateRenderer, Date.class); _membershipTable.getDefaultModel().setAutoReattachEntities(false); _membershipTable.setRowModel(new RowModelImpl() { @Override public Row getRow(Table table, int row) { final Row r = super.getRow(table, row); final Membership membership = _membershipTable.getDefaultModel().getRow(row); if (membership.isActive()) { r.removeClassName("member-inactive"); r.addClassName("member-active"); } else { r.addClassName("member-inactive"); r.removeClassName("member-active"); } return r; } }); QLResolverOptions resolverOptions = new QLResolverOptions(); resolverOptions.setFetchSize(1); resolverOptions.setCacheRegion(ProjectCacheRegions.MEMBER_QUERY); PushButton editOperationsBtn = new PushButton(BUTTON_TEXT_MODIFY()) { @Override public Component getTableCellRendererComponent(Table table, @Nullable Object value, boolean isSelected, boolean hasFocus, int row, int column) { Membership mem = (Membership) value; boolean hasOperations = false; if (mem != null) { final QLBuilderImpl qb = new QLBuilderImpl(ProfileType.class, "ptAlias"); qb.setQLResolverOptions(resolverOptions); qb.appendCriteria("id", PropertyConstraint.Operator.eq, mem.getProfile().getProfileType().getId()); final JoinedQLBuilder mtQB = qb.createInnerJoin(ProfileType.MEMBERSHIP_TYPES_PROP); final JoinedQLBuilder opQB = mtQB.createInnerJoin(MembershipType.DEFAULT_OPERATIONS_PROP); qb.setProjection("COUNT(DISTINCT %s)", opQB.getAlias()); try (CloseableIterator<?> it = qb.getQueryResolver().iterate()) { if (it.hasNext()) { final Number next = (Number) it.next(); hasOperations = next.intValue() > 0; } } } setVisible(hasOperations && isAdminish); return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } }; editOperationsBtn.addActionListener(eev -> doOperationEdit(_membershipTable.getLeadSelection())); PushButton editActivationDatesBtn = new PushButton(ACTION_EDIT_DATES()); editActivationDatesBtn.setTooltip(TOOLTIP_EDIT_DATES(MEMBERSHIP())); editActivationDatesBtn.addActionListener(eev -> doDatesEdit(_membershipTable.getLeadSelection())); PushButton deactivateBtn = new PushButton(ACTION_DEACTIVATE()) { @Override public Component getTableCellRendererComponent(Table table, @Nullable Object value, boolean isSelected, boolean hasFocus, int row, int column) { Membership m = (Membership) value; assert m != null; setVisible(m.getEndDate() == null); return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } }; deactivateBtn.setTooltip(TOOLTIP_DEACTIVATE()); deactivateBtn.addActionListener(ev -> { final Membership membership = _membershipTable.getLeadSelection(); assert membership != null; final Date now = convertForPersistence( getZonedDateTimeForComparison(timeZone).minus(1, ChronoUnit.DAYS)); membership.setEndDate(now); showHideConstraints(); }); PushButton deleteBtn = CommonActions.DELETE.push(); deleteBtn.getButtonDisplay().setConfirmText(DELETE_CONFIRM_TEXT_FMT(MEMBERSHIP())); deleteBtn.addActionListener(dev -> { final Membership membership = _membershipTable.getLeadSelection(); assert membership != null; membership.getProfile().getMembershipSet().remove(membership); reloadTableData(); }); Container actions = of("actions", editOperationsBtn); if (isAllowEditActive()) { actions.add(editActivationDatesBtn); actions.add(deactivateBtn); } if (isAdminish) actions.add(deleteBtn); final Column uiColumn = _membershipTable.getUIColumn(actionColumn); assert uiColumn != null; uiColumn.setDisplayClass("action-column"); _membershipTable.setUICellRenderer(actionColumn, actions); Menu menu = new Menu(CommonButtonText.ADD); menu.setTooltip(ConcatTextSource.create(CommonButtonText.ADD, MEMBERSHIP_TYPE()).withSpaceSeparator()); enableTooltip(menu); menu.addClassName("entity-action"); LocaleContext lc = getLocaleContext(); getProfile().getProfileType().getMembershipTypeSet().stream() .filter(membershipType -> !_excludedMembershipTypes.contains(membershipType)) .sorted(new NamedObjectComparator(lc)).forEach(mt -> { TextSource menuItemText = mt.getName(); MenuItem mi = new MenuItem(menuItemText); mi.addActionListener(ev -> doSelectUserAndCreateMembership(mt)); menu.add(mi); }); _activeConstraint.setSelectedObject(ACTIVE()); _activeConstraint.addActionListener(this::reloadTableData); setDefaultComponent(of("search-wrapper profile-role-search", of("entity-actions actions", menu), of("search-bar", _activeConstraint), new Pager(_membershipTable.addClassName("search-results")))); reloadTableData(); }
From source file:pathwaynet.PathwayCalculator.java
private <E> TestResultForList testForGivenListWilcoxBased(Graph<E, String> graph, Collection<E> componentsInGroup, Collection<E> componentsConsidered, boolean onlyFromSource) { double p = Double.NaN; double meanInGroup = Double.NaN; double meanOutGroup = Double.NaN; // calculate and cache all distances DijkstraDistance<E, String> distances = new DijkstraDistance<>(graph); HashMap<E, Map<E, Number>> distancesMap = new HashMap<>(); graph.getVertices().stream().forEach((component) -> { Map<E, Number> distancesFromThis = distances.getDistanceMap(component); distancesMap.put(component, distancesFromThis); });//www. j a v a 2 s .c o m // generate in-group list and out-group list HashSet<E> componentsInGroupAvailable = new HashSet<>(); HashSet<E> componentsOutGroupAvailable = new HashSet<>(); componentsInGroupAvailable.addAll(graph.getVertices()); componentsOutGroupAvailable.addAll(graph.getVertices()); componentsInGroupAvailable.retainAll(componentsConsidered); componentsOutGroupAvailable.retainAll(componentsConsidered); componentsInGroupAvailable.retainAll(componentsInGroup); componentsOutGroupAvailable.removeAll(componentsInGroup); // store within-group distances for the given list, as well as distances between components in the list and ones out of the list ArrayList<Double> distInGroup = new ArrayList<>(); ArrayList<Double> distOutGroup = new ArrayList<>(); componentsInGroupAvailable.forEach((component1) -> { componentsInGroupAvailable.forEach((component2) -> { Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource); if (!component1.equals(component2) && minDist != null) { distInGroup.add(minDist.doubleValue()); } }); componentsOutGroupAvailable.forEach((component2) -> { Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource); if (!component1.equals(component2) && minDist != null) { distOutGroup.add(minDist.doubleValue()); } }); }); if (distInGroup.size() >= 2 && distOutGroup.size() >= 2) { double[] distInGroupVector = new double[distInGroup.size()]; double[] distOutGroupVector = new double[distOutGroup.size()]; for (int i = 0; i < distInGroup.size(); i++) distInGroupVector[i] = distInGroup.get(i); for (int i = 0; i < distOutGroup.size(); i++) distOutGroupVector[i] = distOutGroup.get(i); p = new MannWhitneyUTest().mannWhitneyUTest(distInGroupVector, distOutGroupVector); //System.err.println(distInGroup+"\t"+distOutGroup); meanInGroup = new Mean().evaluate(distInGroupVector); meanOutGroup = new Mean().evaluate(distOutGroupVector); } else { System.err.println("Error: please check your list: too few components involving in the pathway"); } return new TestResultForList(p, meanInGroup, meanOutGroup); }
From source file:pathwaynet.PathwayCalculator.java
private <E> TestResultForList testForGivenListPermutationBased(Graph<E, String> graph, Collection<E> componentsInGroup, Collection<E> componentsConsidered, boolean onlyFromSource) { // calculate and cache all distances DijkstraDistance<E, String> distances = new DijkstraDistance<>(graph); HashMap<E, Map<E, Number>> distancesMap = new HashMap<>(); graph.getVertices().stream().forEach((component) -> { Map<E, Number> distancesFromThis = distances.getDistanceMap(component); distancesMap.put(component, distancesFromThis); });/* w w w . j a v a2 s .c o m*/ // generate in-group list and all-available list HashSet<E> componentsInGroupAvailable = new HashSet<>(); componentsInGroupAvailable.addAll(graph.getVertices()); componentsInGroupAvailable.retainAll(componentsConsidered); componentsInGroupAvailable.retainAll(componentsInGroup); HashSet<E> componentsAvailable = new HashSet<>(); componentsAvailable.addAll(graph.getVertices()); componentsAvailable.retainAll(componentsConsidered); // store within-group distances for the given list if (componentsInGroupAvailable.size() < 2 || componentsInGroupAvailable.size() > componentsAvailable.size() - 2) { System.err.println( "ERROE! Please check your component list: too few or too many components in the list."); return new TestResultForList(Double.NaN, Double.NaN, Double.NaN); } ArrayList<Double> distInGroup = new ArrayList<>(); componentsInGroupAvailable.forEach((component1) -> { componentsInGroupAvailable.forEach((component2) -> { Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource); if (!component1.equals(component2) && minDist != null) { distInGroup.add(minDist.doubleValue()); } }); }); double[] distInGroupVector = new double[distInGroup.size()]; for (int i = 0; i < distInGroup.size(); i++) distInGroupVector[i] = distInGroup.get(i); double meanInGroup = new Mean().evaluate(distInGroupVector); // permutations ArrayList<Double> meansInPermutGroups = new ArrayList<>(); ArrayList<HashSet<E>> permutatedGroups = generatePermutatedGroups(componentsAvailable, componentsInGroupAvailable.size()); permutatedGroups.forEach((componentsInPermutatedGroup) -> { ArrayList<Double> distInPermutGroup = new ArrayList<>(); componentsInPermutatedGroup.forEach((component1) -> { componentsInPermutatedGroup.forEach((component2) -> { Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource); if (!component1.equals(component2) && minDist != null) { distInPermutGroup.add(minDist.doubleValue()); } }); }); double[] distInPermutGroupVector = new double[distInPermutGroup.size()]; for (int i = 0; i < distInPermutGroup.size(); i++) distInPermutGroupVector[i] = distInPermutGroup.get(i); meansInPermutGroups.add(new Mean().evaluate(distInPermutGroupVector)); }); double[] meansInPermutGroupsVector = new double[meansInPermutGroups.size()]; for (int i = 0; i < meansInPermutGroups.size(); i++) meansInPermutGroupsVector[i] = meansInPermutGroups.get(i); double medianPermut = new Median().evaluate(meansInPermutGroupsVector); double p = ((double) meansInPermutGroups.stream().filter(notGreaterThan(meanInGroup)).count()) / meansInPermutGroups.size(); return new TestResultForList(p, meanInGroup, medianPermut); }
From source file:pathwaynet.PathwayCalculator.java
private <E> HashMap<E, TestResultForEachVertex> testForEachComponent(Graph<E, String> graph, Collection<E> componentsInGroup, Collection<E> componentsConsidered, boolean onlyFromSource) { HashMap<E, TestResultForEachVertex> significance = new HashMap<>(); // calculate and cache all distances DijkstraDistance<E, String> distances = new DijkstraDistance<>(graph); HashMap<E, Map<E, Number>> distancesMap = new HashMap<>(); graph.getVertices().stream().forEach((component) -> { Map<E, Number> distancesFromThis = distances.getDistanceMap(component); distancesMap.put(component, distancesFromThis); });//from w w w . j a v a2 s . c o m // calculate real in-group and out-group distances HashMap<E, Map<E, Number>> distancesInsideGroup = getDistancesWithGroup(distancesMap, componentsInGroup, componentsConsidered, onlyFromSource, true); HashMap<E, Map<E, Number>> distancesOutsideGroup = getDistancesWithGroup(distancesMap, componentsInGroup, componentsConsidered, onlyFromSource, false); if (distancesInsideGroup.isEmpty() || distancesOutsideGroup.isEmpty()) { System.err.println("WARNING: Please double check the enzyme list!"); } else { HashMap<E, ArrayList<Double>> differencesProp = new HashMap<>(); distancesInsideGroup.keySet().stream().forEach((component) -> { ArrayList<Double> diffIncreaseProp = estimateDifferenceOfProportionAtDistances( distancesInsideGroup.get(component).values(), distancesOutsideGroup.get(component).values()); differencesProp.put(component, diffIncreaseProp); //System.err.println(enzyme.getID()+"\t"+diffIncreaseProp); }); // for each enzyme in the given group, estimate its significance of neighbor enrichment of enzymes in the group //System.err.println(); distancesInsideGroup.keySet().stream().forEach((component) -> { // do permutation (for numPermutations times) to generate random group with the same size and with this enzyme HashSet<E> allComponentsAvailable = new HashSet<>(); allComponentsAvailable.addAll(graph.getVertices()); allComponentsAvailable.retainAll(componentsConsidered); ArrayList<HashSet<E>> componentsInGroupPermutations = generatePermutatedGroupsWithFixedNode( component, allComponentsAvailable, distancesInsideGroup.size()); // for each permutation, calculate the differences of proportion between within-group and between-group path at each path length ArrayList<ArrayList<Double>> differencesPropPermutations = new ArrayList<>(); componentsInGroupPermutations.stream().forEach((componentsInGroupThisPermutation) -> { HashSet<E> componentsOutGroupThisPermutation = new HashSet<>(); componentsOutGroupThisPermutation.addAll(graph.getVertices()); componentsOutGroupThisPermutation.removeAll(componentsInGroupThisPermutation); HashMap<E, Number> distancesInPermut = new HashMap<>(); HashMap<E, Number> distancesOutPermut = new HashMap<>(); allComponentsAvailable.forEach((component2) -> { Number minDist = getShortestDistance(distancesMap, component, component2, onlyFromSource); if (componentsInGroupThisPermutation.contains(component2) && (!component.equals(component2)) && minDist != null) distancesInPermut.put(component2, minDist); else if (componentsOutGroupThisPermutation.contains(component2) && minDist != null) distancesOutPermut.put(component2, minDist); }); differencesPropPermutations.add(estimateDifferenceOfProportionAtDistances( distancesInPermut.values(), distancesOutPermut.values())); }); // calculate the significance // P: based on Pearson's correlation between differences of proportions and distances // domain: based on the quantile of difference at each distance //System.err.println(component); double p = calculatePValue(differencesProp.get(component), differencesPropPermutations); int radius = estimateDomainRadius(differencesProp.get(component), differencesPropPermutations, 0.9); significance.put(component, new TestResultForEachVertex(p, radius)); if (cache) { } }); } return significance; }