com.google.common.collect.Collections2 Java Examples

The following examples show how to use com.google.common.collect.Collections2. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AlertUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Helper to convert a collection of email strings into {@code InternetAddress} instances, filtering
 * out invalid addresses and nulls.
 *
 * @param emailCollection collection of email address strings
 * @return filtered collection of InternetAddress objects
 */
public static Collection<InternetAddress> toAddress(Collection<String> emailCollection) {
  if (CollectionUtils.isEmpty(emailCollection)) {
    return Collections.emptySet();
  }
  return Collections2.filter(Collections2.transform(emailCollection,
      new Function<String, InternetAddress>() {
        @Override
        public InternetAddress apply(String s) {
          try {
            return InternetAddress.parse(s)[0];
          } catch (Exception e) {
            return null;
          }
        }
      }),
      new Predicate<InternetAddress>() {
        @Override
        public boolean apply(InternetAddress internetAddress) {
          return internetAddress != null;
        }
      });
}
 
Example #2
Source File: ColumnarMemoryStorePersister.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private Dictionary<String> buildDictionary(TblColRef dim, List<Object> inputValues) throws IOException {
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.start();
    final Collection<String> values = Collections2.transform(Sets.newHashSet(inputValues),
            new Function<Object, String>() {
                @Nullable
                @Override
                public String apply(Object input) {
                    String value = (String) input;
                    return value;
                }
            });
    final Dictionary<String> dict = DictionaryGenerator.buildDictionary(dim.getType(),
            new IterableDictionaryValueEnumerator(values));
    stopwatch.stop();
    if (logger.isDebugEnabled()) {
        logger.debug("BuildDictionary for column : " + dim.getName() + " took : " + stopwatch.elapsedMillis()
                + " ms ");
    }
    return dict;
}
 
Example #3
Source File: ConfigurationsForTargetsTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the configured deps for a given configured target under the given attribute.
 *
 * <p>Throws an exception if the attribute can't be found.
 */
protected List<ConfiguredTarget> getConfiguredDeps(ConfiguredTarget target, String attrName)
    throws Exception {
  String targetLabel = AliasProvider.getDependencyLabel(target).toString();
  Multimap<DependencyKind, ConfiguredTargetAndData> allDeps = getConfiguredDeps(target);
  for (DependencyKind kind : allDeps.keySet()) {
    Attribute attribute = kind.getAttribute();
    if (attribute.getName().equals(attrName)) {
      return ImmutableList.copyOf(
          Collections2.transform(
              allDeps.get(kind), ConfiguredTargetAndData::getConfiguredTarget));
    }
  }
  throw new AssertionError(
      String.format("Couldn't find attribute %s for label %s", attrName, targetLabel));
}
 
Example #4
Source File: WeekendConfigurationPage.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
private CalendarOption createCalendarOption(final GPCalendar calendar) {
  AlwaysWorkingTimeCalendarImpl emptyCalendar = new AlwaysWorkingTimeCalendarImpl();
  emptyCalendar.setName(GanttLanguage.getInstance().getText("none"));
  List<GPCalendar> allCalendars = append(GPCalendarProvider.getInstance().getCalendars(), emptyCalendar, myCustomCalendar);
  CalendarOption result = new CalendarOption(calendar, allCalendars);
  if (calendar.getBaseCalendarID() != null) {
    Collection<GPCalendar> filtered = Collections2.filter(allCalendars, new Predicate<GPCalendar>() {
      public boolean apply(GPCalendar cal) {
        return cal.getID().equals(calendar.getBaseCalendarID());
      }
    });
    if (!filtered.isEmpty()) {
      GPCalendar baseCalendar = filtered.iterator().next();
      if (Sets.newHashSet(baseCalendar.getPublicHolidays()).equals(Sets.newHashSet(calendar.getPublicHolidays()))) {
        result.setSelectedValue(baseCalendar);
      } else {
        fillCustomCalendar(Lists.newArrayList(calendar.getPublicHolidays()), baseCalendar);
        result.setSelectedValue(myCustomCalendar);
        updateBasedOnLabel(baseCalendar);
      }
    }
  }
  return result;
}
 
Example #5
Source File: GraphOwlVisitor.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Override
public Void visit(OWLEquivalentObjectPropertiesAxiom axiom) {
  Set<OWLObjectPropertyExpression> properties = axiom.getProperties();
  boolean anonymousPropertyExists = false;
  for (OWLObjectPropertyExpression property : properties) {
    anonymousPropertyExists = anonymousPropertyExists || property.isAnonymous();
  }

  // #217 - in case of EquivalentObjectProperties(:p ObjectInverseOf(:q))
  if (!anonymousPropertyExists) {
    Collection<Long> nodes = Collections2.transform(axiom.getObjectPropertiesInSignature(),
        new Function<OWLObjectProperty, Long>() {

          @Override
          public Long apply(OWLObjectProperty objectProperty) {
            return getOrCreateNode(getIri(objectProperty));
          }
        });

    getOrCreateRelationshipPairwise(nodes, OwlRelationships.OWL_EQUIVALENT_OBJECT_PROPERTY);
  }
  return null;
}
 
Example #6
Source File: StreamlineEventImpl.java    From streamline with Apache License 2.0 6 votes vote down vote up
@Override
public String getDataSourceId() {
    String res = dataSourceId;
    if (res == null) {
        Object dataSourceIds = header.get("dataSourceIds");
        if (dataSourceIds instanceof List) {
            res = Joiner.on(",").join(Collections2.filter((List) dataSourceIds, new Predicate() {
                @Override
                public boolean apply(Object input) {
                    return input != null;
                }
            }));
        }
    }
    return res;
}
 
Example #7
Source File: DeleteTest.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get {@link TestCaseStep} which are using an other {@link TestCaseStep}
 * from the given {@link Test} but which are NOT included into this
 * {@link Test}
 *
 * @param test the {@link Test} from which getting externally used
 * {@link TestCaseStep}s
 * @return a {@link Collection} of {@link TestCaseStep} which are using an
 * other {@link TestCaseStep} from the given {@link Test} but which are NOT
 * included into this {@link Test}
 * @throws CerberusException if an unexpected error occurred
 */
private Collection<TestCaseStep> externallyUsedTestCaseSteps(final Test test) throws CerberusException {
    // Get the associated ApplicationContext to this servlet
    final ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());

    // Get all TestCaseSteps which are using an other TestCaseSteps from given Test
    final ITestCaseStepService testCaseStepService = applicationContext.getBean(ITestCaseStepService.class);
    final List<TestCaseStep> stepsInUse = testCaseStepService.getTestCaseStepsUsingTestInParameter(test.getTest());

    // Filter the retrieved list to only retain those which are not included from the given Test
    return Collections2.filter(stepsInUse, new Predicate<TestCaseStep>() {
        @Override
        public boolean apply(@Nullable final TestCaseStep input) {
            return !input.getTest().equals(test.getTest());
        }

        @Override
        public boolean test(TestCaseStep t) {
            return Predicate.super.test(t); //To change body of generated methods, choose Tools | Templates.
        }
    });
}
 
Example #8
Source File: MapContextImpl.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
public MapContextImpl(MapInfo info, MapSource source, Collection<MapModule> modules) {
  super(info);
  this.source = checkNotNull(source);
  this.modules = ImmutableList.copyOf(checkNotNull(modules));

  for (MapModule module : this.modules) {
    this.tags.addAll(module.getTags());

    if (module instanceof TeamModule) {
      this.players.clear();
      this.players.addAll(
          Collections2.transform(((TeamModule) module).getTeams(), TeamFactory::getMaxPlayers));
    }

    if (module instanceof FreeForAllModule) {
      this.players.clear();
      this.players.add(((FreeForAllModule) module).getOptions().maxPlayers);
    }
  }

  if (getWorld().hasTerrain()) {
    this.tags.add(TERRAIN);
  }
}
 
Example #9
Source File: BaselineFillingMergeWrapper.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Override
protected List<MergedAnomalyResultDTO> retrieveAnomaliesFromDatabase(List<MergedAnomalyResultDTO> generated) {
  List<MergedAnomalyResultDTO> retrieved = super.retrieveAnomaliesFromDatabase(generated);

  Collection<MergedAnomalyResultDTO> anomalies =
      Collections2.filter(retrieved,
              mergedAnomaly -> mergedAnomaly != null &&
              !mergedAnomaly.isChild() &&
              mergedAnomaly.getAnomalyResultSource().equals(AnomalyResultSource.DEFAULT_ANOMALY_DETECTION) &&
                  // merge if only the anomaly generated by the same detector
              this.detectorComponentName.equals(mergedAnomaly.getProperties().getOrDefault(PROP_DETECTOR_COMPONENT_NAME, "")) &&
                  // merge if only the anomaly is in the same dimension
              this.metricUrn.equals(mergedAnomaly.getMetricUrn())
      );
  for (MergedAnomalyResultDTO anomaly : anomalies) {
    if(anomaly.getId() != null) this.existingAnomalies.put(anomaly.getId(), copyAnomalyInfo(anomaly, new MergedAnomalyResultDTO()));
  }
  return new ArrayList<>(anomalies);
}
 
Example #10
Source File: StreamCatalogService.java    From streamline with Apache License 2.0 6 votes vote down vote up
private Collection<TopologyProcessor> fillProcessorStreams(Collection<TopologyProcessor> processors) {
    if (processors != null) {
        for (TopologyProcessor processor : processors) {
            List<TopologyStream> topologyStreams = getOutputStreams(processor);
            processor.setOutputStreams(topologyStreams);
            processor.setOutputStreamIds(new ArrayList<>(Collections2.transform(topologyStreams, new Function<TopologyStream, Long>() {
                @Nullable
                @Override
                public Long apply(@Nullable TopologyStream input) {
                    return input.getId();
                }
            })));
        }
    }
    return processors;
}
 
Example #11
Source File: FileEndpointTest.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
private boolean waitTillStdoutIsPopulated(ByteArrayOutputStream baos, int timeout) throws InterruptedException,
  IOException
{
  long now = System.currentTimeMillis();
  Collection<String> filter = Lists.newArrayList();
  while (System.currentTimeMillis() - now < timeout) {
    baos.flush();
    String[] sout = baos.toString().split(System.lineSeparator());
    filter = Collections2.filter(Arrays.asList(sout), Predicates.containsPattern("Delta Record:"));
    if (filter.size() != 0) {
      break;
    }

    Thread.sleep(500);
  }

  return (filter.size() != 0);
}
 
Example #12
Source File: TupleExecutionPlanGenerator.java    From rya with Apache License 2.0 6 votes vote down vote up
private List<TupleExpr> getPlans(final TupleExpr te) {


        final NodeCollector nc = new NodeCollector();
        te.visit(nc);

        final Set<QueryModelNode> nodeSet = nc.getNodeSet();
        final List<Filter> filterList = nc.getFilterSet();
        final Projection projection = nc.getProjection().clone();

        final List<TupleExpr> queryPlans = Lists.newArrayList();

        final Collection<List<QueryModelNode>> plans = Collections2.permutations(nodeSet);

        for (final List<QueryModelNode> p : plans) {
            if (p.size() == 0) {
                throw new IllegalArgumentException("Tuple must contain at least one node!");
            } else if (p.size() == 1) {
                queryPlans.add(te);
            } else {
                queryPlans.add(buildTuple(p, filterList, projection));
            }
        }

        return queryPlans;
    }
 
Example #13
Source File: ConfigurationMerger.java    From arbiter with Apache License 2.0 6 votes vote down vote up
/**
 * Merge a collection of maps where the values are themselves collections
 * Every value in the values of the resulting map is unique
 *
 * @param actionTypes The collection of ActionTypes
 * @param transformFunction The function that produces a map from an ActionType
 * @param <T> The type of values in the collection that is the value of the map
 * @return A Map representing the merger of all input maps
 */
public static <T, U extends Collection<T>> Map<String, U> mergeCollectionMaps(Collection<ActionType> actionTypes, Function<ActionType, Map<String, U>> transformFunction) {
    Collection<Map<String, U>> values = Collections2.transform(actionTypes, transformFunction);
    Map<String, U> result = new HashMap<>();

    for (Map<String, U> map : values) {
        for (Map.Entry<String, U> entry : map.entrySet()) {
            if (!result.containsKey(entry.getKey())) {
                result.put(entry.getKey(), entry.getValue());
            } else {
                result.get(entry.getKey()).addAll(entry.getValue());
            }
        }
    }

    return result;
}
 
Example #14
Source File: MetersListCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute() {

    if (!isNullOrEmpty(meterstr)) {
        meterId = MeterId.meterId(Long.parseLong(meterstr));
    }

    MeterService service = get(MeterService.class);

    if (meterId != null && uri != null) {
        Meter m = service.getMeter(DeviceId.deviceId(uri), meterId);
        if (m != null) {
            print("%s", m);
        } else {
            error("Meter %s not found for device %s", meterId, uri);
        }
    } else {
        Collection<Meter> meters = service.getAllMeters();
        if (uri == null) {
            printMeters(meters);
        } else {
            printMeters(Collections2.filter(meters,
                    m -> m.deviceId().equals(DeviceId.deviceId(uri))));
        }
    }
}
 
Example #15
Source File: ApDependency.java    From atlas with Apache License 2.0 6 votes vote down vote up
private File getBaseApFile(Project project, TBuildType tBuildType) {
    File apBaseFile;
    File buildTypeBaseApFile = tBuildType.getBaseApFile();
    if (null != buildTypeBaseApFile && buildTypeBaseApFile.exists()) {
        apBaseFile = buildTypeBaseApFile;
    } else if (!isNullOrEmpty(tBuildType.getBaseApDependency())) {
        String apDependency = tBuildType.getBaseApDependency();
        // Preconditions.checkNotNull(apDependency,
        //                            "You have to specify the baseApFile property or the baseApDependency
        // dependency");
        Dependency dependency = project.getDependencies().create(apDependency);
        Configuration configuration = project.getConfigurations().detachedConfiguration(dependency);
        configuration.setTransitive(false);
        apBaseFile = Iterables.getOnlyElement(Collections2.filter(configuration.getFiles(), new Predicate<File>() {
            @Override
            public boolean apply(@Nullable File file) {
                return file.getName().endsWith(".ap");
            }
        }));
    } else {
        throw new IllegalStateException("AP is missing");
    }
    return apBaseFile;
}
 
Example #16
Source File: Query.java    From db with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Creates a query for inserting a collection of records of the specified type
 * @param ds name of datastore
 * @param collection name of collection
 * @param records a collection of records that are to be inserted
 * @param recordType the @link {@link RecordType} indicating the format engine to use for data
 * @return the generated query in JSON format
 */
public Query insertQuery(final String ds, final String collection, List<Record> records, final RecordType recordType) {
    queryJson.put(QueryParams.QUERY.getParam(), QueryType.INSERT.getQueryCode());
    queryJson.put(QueryParams.DATASTORE.getParam(), ds);
    queryJson.put(QueryParams.COLLECTION.getParam(), collection);

    JSONObject payloadJson = new JSONObject();
    payloadJson.put(QueryParams.TYPE.getParam(), recordType.getTypeCode());
    payloadJson.put(QueryParams.DATA.getParam(), new JSONArray(Collections2.transform(records, new Function<Record, JSONObject>() {
        public JSONObject apply(Record record) {
            return record.asJson();
        }
    })));

    queryJson.put(QueryParams.PAYLOAD.getParam(), payloadJson);
    return this;
}
 
Example #17
Source File: AbstractSqlQuery.java    From registry with Apache License 2.0 5 votes vote down vote up
/**
 * if formatter != null applies the formatter to the column names. Examples of output are:
 * <br>
 * formatter == null ==&gt; [colName1, colName2]
 * <br>
 * formatter == "%s = ?" ==&gt; [colName1 = ?, colName2 = ?]
 */
protected Collection<String> getColumnNames(Collection<Schema.Field> columns, final String formatter) {
    return Collections2.transform(columns, new Function<Schema.Field, String>() {
        @Override
        public String apply(Schema.Field field) {
            return formatter == null ? field.getName() : String.format(formatter, field.getName());
        }
    });
}
 
Example #18
Source File: KcaExpeditionTableViewAdpater.java    From kcanotify with GNU General Public License v3.0 5 votes vote down vote up
public void setListViewItemList(JsonArray ship_list, final int area_no) {
    Type listType = new TypeToken<List<JsonObject>>() {}.getType();
    listViewItemList = new Gson().fromJson(ship_list, listType);
    listViewItemList = new ArrayList<>(Collections2.filter(listViewItemList, new Predicate<JsonObject>() {
        @Override
        public boolean apply(JsonObject input) {
            return (area_no == 0 || input.get("area").getAsInt() == area_no);
        }
    }));
}
 
Example #19
Source File: AbstractModifiedNodeBasedCandidateNode.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Collection<DataTreeCandidateNode> getChildNodes() {
    switch (mod.getModificationType()) {
        case APPEARED:
        case DISAPPEARED:
        case SUBTREE_MODIFIED:
            return Collections2.transform(mod.getChildren(), this::childNode);
        case UNMODIFIED:
            // Unmodified node, but we still need to resolve potential children. canHaveChildren returns
            // false if both arguments are null.
            if (!canHaveChildren(oldMeta, newMeta)) {
                return ImmutableList.of();
            }

            return Collections2.transform(getContainer(newMeta != null ? newMeta : oldMeta).getValue(),
                DataTreeCandidateNodes::unmodified);
        case DELETE:
        case WRITE:
            // This is unusual, the user is requesting we follow into an otherwise-terminal node.
            // We need to fudge things based on before/after data to correctly fake the expectations.
            if (!canHaveChildren(oldMeta, newMeta)) {
                return ImmutableList.of();
            }
            return DataTreeCandidateNodes.containerDelta(getContainer(oldMeta), getContainer(newMeta));
        default:
            throw new IllegalArgumentException("Unhandled modification type " + mod.getModificationType());
    }
}
 
Example #20
Source File: GuavaFilterTransformCollectionsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenFilterUsingMultiplePredicates_thenFiltered() {
    final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
    final Collection<String> result = Collections2.filter(names, Predicates.or(Predicates.containsPattern("J"), Predicates.not(Predicates.containsPattern("a"))));

    assertEquals(3, result.size());
    assertThat(result, containsInAnyOrder("John", "Jane", "Tom"));
}
 
Example #21
Source File: MapSideDataCollectOperation.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private Collection<Runnable> collectors2Runnables(Collection<CrateCollector> collectors) {
    return Collections2.transform(collectors, new Function<CrateCollector, Runnable>() {
        @Override
        public Runnable apply(final CrateCollector collector) {
            return new Runnable() {
                @Override
                public void run() {
                    collector.doCollect();
                }
            };
        }
    });
}
 
Example #22
Source File: TableOverrideSchema.java    From morf with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a {@link TableOverrideSchema} which is identical to <var>baseSchema</var>
 * save for its having <var>overridingTable</var> in place of its namesake.
 *
 * @param baseSchema base schema to adapt via a single table override.
 * @param overridingTable table to take the place of its namesake in <var>baseSchema</var>.
 */
public TableOverrideSchema(final Schema baseSchema, final Table overridingTable) {
  super(
    Lists.newArrayList(Iterables.concat(
      // all except the overridden table
      Collections2.filter(baseSchema.tables(), not(new Predicate<Table>() {
        @Override
        public boolean apply(Table table) {
          return table.getName().toUpperCase().equals(overridingTable.getName().toUpperCase());
        }
      })),
      // plus the override
      Arrays.asList(new Table[] {overridingTable})
    )));
}
 
Example #23
Source File: PsiClassUtil.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
/**
 * Workaround to get all of original Methods of the psiClass, without calling PsiAugmentProvider infinitely
 *
 * @param psiClass psiClass to collect all of methods from
 * @return all intern methods of the class
 */
@NotNull
public static Collection<PsiMethod> collectClassMethodsIntern(@NotNull PsiClass psiClass) {
  if (psiClass instanceof PsiExtensibleClass) {
    return ((PsiExtensibleClass) psiClass).getOwnMethods();
  } else {
    return Collections2.transform(
        Collections2.filter(Lists.newArrayList(psiClass.getChildren()), Predicates.instanceOf(PsiMethod.class)),
        PSI_ELEMENT_TO_METHOD_FUNCTION);
  }
}
 
Example #24
Source File: LanguagesChoiceProvider.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void query(final String term, int page, Response<String> response) {
    response.addAll(Strings.isEmpty(term)
    		
    			?ISO_LANGUAGES
    			:Collections2.filter(ISO_LANGUAGES, new Predicate<String>() {
            @Override
            public boolean apply(String s) {
                return s.startsWith(term);
            }
        }));
}
 
Example #25
Source File: MySQL5InventoryDAO.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean store(List<Item> items, Integer playerId, Integer accountId, Integer legionId) {
	Collection<Item> itemsToUpdate = Collections2.filter(items, itemsToUpdatePredicate);
	Collection<Item> itemsToInsert = Collections2.filter(items, itemsToInsertPredicate);
	Collection<Item> itemsToDelete = Collections2.filter(items, itemsToDeletePredicate);

	boolean deleteResult = false;
	boolean insertResult = false;
	boolean updateResult = false;

	Connection con = null;
	try {
		con = DatabaseFactory.getConnection();
		con.setAutoCommit(false);
		deleteResult = deleteItems(con, itemsToDelete);
		insertResult = insertItems(con, itemsToInsert, playerId, accountId, legionId);
		updateResult = updateItems(con, itemsToUpdate, playerId, accountId, legionId);
	}
	catch (SQLException e) {
		log.error("Can't open connection to save player inventory: " + playerId);
	}
	finally {
		DatabaseFactory.close(con);
	}

	for (Item item : items) {
		item.setPersistentState(PersistentState.UPDATED);
	}

	if (!itemsToDelete.isEmpty() && deleteResult) {
		ItemService.releaseItemIds(itemsToDelete);
	}

	return deleteResult && insertResult && updateResult;
}
 
Example #26
Source File: INotificationsManifest.java    From CameraV with GNU General Public License v3.0 5 votes vote down vote up
public INotification getById(final String _id) {
	Collection<INotification> notifications_ = Collections2.filter(notifications, new Predicate<INotification>() {
		@Override
		public boolean apply(INotification notification) {
			return notification._id.equals(_id);
		}
	});
	
	try {
		return notifications_.iterator().next();
	} catch(NullPointerException e) {
		Logger.e(LOG, e);
		return null;
	}
}
 
Example #27
Source File: AbstractSnapshotBase.java    From fluo with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Map<Column, String>> gets(Collection<? extends CharSequence> rows,
    Set<Column> columns) {
  Map<Bytes, Map<Column, Bytes>> rcvs = get(Collections2.transform(rows, this::s2bConv), columns);
  Map<String, Map<Column, String>> ret = new HashMap<>(rcvs.size());

  for (Entry<Bytes, Map<Column, Bytes>> entry : rcvs.entrySet()) {
    ret.put(entry.getKey().toString(), Maps.transformValues(entry.getValue(), b -> b.toString()));
  }
  return ret;
}
 
Example #28
Source File: OClassIntrospector.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public List<OProperty> getDisplayableProperties(OClass oClass) {
	Collection<OProperty> properties =  oClass.properties();
	IFilterPredicateFactory factory = OrienteerWebApplication.get().getServiceInstance(IFilterPredicateFactory.class);
	Collection<OProperty> filteredProperties = Collections2.filter(properties, factory.getGuicePredicateForTableProperties());
	if(filteredProperties==null || filteredProperties.isEmpty()) filteredProperties = properties;
	return ORDER_PROPERTIES_BY_ORDER.sortedCopy(filteredProperties);
}
 
Example #29
Source File: NormalizedNodeDataTreeCandidateNode.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Collection<DataTreeCandidateNode> getChildNodes() {
    if (data instanceof NormalizedNodeContainer) {
        return Collections2.transform(((NormalizedNodeContainer<?, ?, ?>) data).getValue(),
            input -> input == null ? null : new NormalizedNodeDataTreeCandidateNode(input));
    }
    return ImmutableList.of();
}
 
Example #30
Source File: AnomalyFilterWrapper.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the nested pipelines and calls the isQualified method in the anomaly filter stage to check if an anomaly passes the filter.
 * @return the detection pipeline result
 * @throws Exception
 */
@Override
public final DetectionPipelineResult run() throws Exception {
  List<MergedAnomalyResultDTO> candidates = new ArrayList<>();
  List<PredictionResult> predictionResults = new ArrayList<>();
  Map<String, Object> diagnostics = new HashMap<>();
  List<EvaluationDTO> evaluations = new ArrayList<>();

  Set<Long> lastTimeStamps = new HashSet<>();
  for (Map<String, Object> properties : this.nestedProperties) {
    DetectionConfigDTO nestedConfig = new DetectionConfigDTO();

    Preconditions.checkArgument(properties.containsKey(PROP_CLASS_NAME), "Nested missing " + PROP_CLASS_NAME);
    HashMap<String, Object> nestedProp = new HashMap<>(properties);
    if (this.metricUrn != null){
      nestedProp.put(PROP_METRIC_URN, this.metricUrn);
    }
    nestedConfig.setId(this.config.getId());
    nestedConfig.setName(this.config.getName());
    nestedConfig.setDescription(this.config.getDescription());
    nestedConfig.setProperties(nestedProp);
    nestedConfig.setComponents(this.config.getComponents());
    DetectionPipeline pipeline = this.provider.loadPipeline(nestedConfig, this.startTime, this.endTime);

    DetectionPipelineResult intermediate = pipeline.run();
    lastTimeStamps.add(intermediate.getLastTimestamp());
    diagnostics.putAll(intermediate.getDiagnostics());
    evaluations.addAll(intermediate.getEvaluations());
    predictionResults.addAll(intermediate.getPredictions());
    candidates.addAll(intermediate.getAnomalies());
  }

  Collection<MergedAnomalyResultDTO> anomalies =
      Collections2.filter(candidates, mergedAnomaly -> mergedAnomaly != null && !mergedAnomaly.isChild() && anomalyFilter.isQualified(mergedAnomaly));

  return new DetectionPipelineResult(new ArrayList<>(anomalies), DetectionUtils.consolidateNestedLastTimeStamps(lastTimeStamps),
      predictionResults, evaluations).setDiagnostics(diagnostics);
}