com.google.common.collect.Multimap Java Examples

The following examples show how to use com.google.common.collect.Multimap. 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: FormControllerTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlashify() {
    // given
    String data = "this is my [email protected]";
    Multimap<String, String> parameter = ArrayListMultimap.create();
    parameter.put("name", "this is my name");
    parameter.put("email", "[email protected]");
    
    // when
    TestResponse response = TestRequest.post("/submit")
            .withContentType(MediaType.FORM_DATA.withoutParameters().toString())
            .withForm(parameter)
            .execute();

    // then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo(data));
}
 
Example #2
Source File: SubscriberRegistry.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Registers all subscriber methods on the given listener object.
 */
void register(Object listener) {
  Multimap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener);

  for (Map.Entry<Class<?>, Collection<Subscriber>> entry : listenerMethods.asMap().entrySet()) {
    Class<?> eventType = entry.getKey();
    Collection<Subscriber> eventMethodsInListener = entry.getValue();

    CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType);

    if (eventSubscribers == null) {
      CopyOnWriteArraySet<Subscriber> newSet = new CopyOnWriteArraySet<Subscriber>();
      eventSubscribers =
          MoreObjects.firstNonNull(subscribers.putIfAbsent(eventType, newSet), newSet);
    }

    eventSubscribers.addAll(eventMethodsInListener);
  }
}
 
Example #3
Source File: ConstraintChecker.java    From datawave with Apache License 2.0 6 votes vote down vote up
/**
 * Factory method to create a new ConstraintChecker from a Configuration.
 *
 * @param conf
 * @return constraint checker
 */
public static ConstraintChecker create(Configuration conf) {
    
    Multimap<Text,VisibilityConstraint> constraints = null;
    
    String[] initializerClasses = conf.getStrings(INITIALIZERS);
    
    if (initializerClasses != null) {
        for (String initializerClass : initializerClasses) {
            if (constraints == null) {
                constraints = HashMultimap.create();
            }
            
            try {
                ConstraintInitializer initializer = Class.forName(initializerClass).asSubclass(ConstraintInitializer.class).newInstance();
                initializer.addConstraints(conf, constraints);
                
            } catch (Exception e) {
                log.error("Could invoke ConstraintInitializer: " + initializerClass, e);
                throw new RuntimeException("Could invoke ConstraintInitializer: " + initializerClass, e);
            }
        }
    }
    
    return new ConstraintChecker(constraints);
}
 
Example #4
Source File: AnalysisUtils.java    From bazel with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
public static Multimap<BuildConfiguration, DependencyKey> targetsToDeps(
    Collection<TargetAndConfiguration> nodes, ConfiguredRuleClassProvider ruleClassProvider) {
  Multimap<BuildConfiguration, DependencyKey> asDeps = ArrayListMultimap.create();
  for (TargetAndConfiguration targetAndConfig : nodes) {
    ConfigurationTransition transition =
        TransitionResolver.evaluateTransition(
            targetAndConfig.getConfiguration(),
            NoTransition.INSTANCE,
            targetAndConfig.getTarget(),
            ruleClassProvider.getTrimmingTransitionFactory());
    if (targetAndConfig.getConfiguration() != null) {
      // TODO(bazel-team): support top-level aspects
      asDeps.put(
          targetAndConfig.getConfiguration(),
          DependencyKey.builder()
              .setLabel(targetAndConfig.getLabel())
              .setTransition(transition)
              .build());
    }
  }
  return asDeps;
}
 
Example #5
Source File: ExtendedContentDataTypeHelper.java    From datawave with Apache License 2.0 6 votes vote down vote up
/**
 * Populates the provided metadata parser map from the configuration. This allows different metadata parser maps to be populated based on different
 * configuration keys.
 * 
 * @param conf
 *            Configuration
 * @param keySuffix
 *            The configuration key suffix
 * @param metadataParserMap
 *            The metadata parser map to populate.
 */
protected void putMetadataParsers(Configuration conf, String keySuffix, Multimap<String,MetadataIdParser> metadataParserMap) {
    String prefix;
    Map<String,String> keyParsers;
    prefix = this.getType().typeName() + keySuffix;
    keyParsers = getValues(conf, prefix);
    for (Map.Entry<String,String> entry : keyParsers.entrySet()) {
        String field = entry.getKey();
        if (field.length() <= (prefix.length() + 1)) {
            throw new IllegalArgumentException("Field metadata parser key is invalid: missing fieldname: " + field);
        }
        field = field.substring(prefix.length() + 1);
        int index = field.indexOf('.');
        if (index >= 0) {
            field = field.substring(0, index);
        }
        if (field.isEmpty()) {
            throw new IllegalArgumentException("Field metadata parser key is invalid: missing fieldname: " + field);
        }
        metadataParserMap.put(field, MetadataIdParser.createParser(entry.getValue()));
    }
}
 
Example #6
Source File: ToolMetaItem.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Multimap<String, AttributeModifier> getAttributeModifiers(EntityEquipmentSlot slot, ItemStack stack) {
    T metaValueItem = getItem(stack);
    HashMultimap<String, AttributeModifier> modifiers = HashMultimap.create();
    modifiers.putAll(super.getAttributeModifiers(slot, stack));
    if (metaValueItem != null && slot == EntityEquipmentSlot.MAINHAND) {
        IToolStats toolStats = metaValueItem.getToolStats();
        if (toolStats == null) {
            return HashMultimap.create();
        }
        float attackDamage = getToolAttackDamage(stack);
        float attackSpeed = toolStats.getAttackSpeed(stack);

        modifiers.put(SharedMonsterAttributes.ATTACK_DAMAGE.getName(), new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Weapon modifier", attackDamage, 0));
        modifiers.put(SharedMonsterAttributes.ATTACK_SPEED.getName(), new AttributeModifier(ATTACK_SPEED_MODIFIER, "Weapon modifier", attackSpeed, 0));
    }
    return modifiers;
}
 
Example #7
Source File: NotificationControllerTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  controller = new NotificationController(watchKeysUtil, releaseMessageService, entityManagerUtil, namespaceUtil);

  someAppId = "someAppId";
  someCluster = "someCluster";
  defaultNamespace = ConfigConsts.NAMESPACE_APPLICATION;
  someDataCenter = "someDC";
  someNotificationId = 1;
  someClientIp = "someClientIp";

  when(namespaceUtil.filterNamespaceName(defaultNamespace)).thenReturn(defaultNamespace);

  deferredResults =
      (Multimap<String, DeferredResult<ResponseEntity<ApolloConfigNotification>>>) ReflectionTestUtils
          .getField(controller, "deferredResults");
}
 
Example #8
Source File: RoutingBuilder.java    From crate with Apache License 2.0 6 votes vote down vote up
ReaderAllocations buildReaderAllocations() {
    Multimap<RelationName, String> indicesByTable = HashMultimap.create();
    IndexBaseBuilder indexBaseBuilder = new IndexBaseBuilder();
    Map<String, Map<Integer, String>> shardNodes = new HashMap<>();

    for (final Map.Entry<RelationName, List<Routing>> tableRoutingEntry : routingListByTable.entrySet()) {
        RelationName table = tableRoutingEntry.getKey();
        List<Routing> routingList = tableRoutingEntry.getValue();
        for (Routing routing : routingList) {
            allocateRoutingNodes(shardNodes, routing.locations());

            for (Map.Entry<String, Map<String, IntIndexedContainer>> entry : routing.locations().entrySet()) {
                Map<String, IntIndexedContainer> shardsByIndex = entry.getValue();
                indicesByTable.putAll(table, shardsByIndex.keySet());

                for (Map.Entry<String, IntIndexedContainer> shardsByIndexEntry : shardsByIndex.entrySet()) {
                    indexBaseBuilder.allocate(shardsByIndexEntry.getKey(), shardsByIndexEntry.getValue());
                }
            }
        }
    }
    routingListByTable.clear();
    return new ReaderAllocations(indexBaseBuilder.build(), shardNodes, indicesByTable);
}
 
Example #9
Source File: MsSqlQueryBuilder.java    From kafka-connect-cdc-mssql with Apache License 2.0 5 votes vote down vote up
String joinSelect(Multimap<String, String> columns) {
  List<String> selectColumns = new ArrayList<>();

  for (String table : columns.keySet()) {
    final Collection<String> keyColumns = columns.get(table);
    for (String keyColumn : keyColumns) {
      selectColumns.add(
          String.format("[%s].[%s]", table, keyColumn)
      );
    }
  }

  return Joiner.on(", ").join(selectColumns);
}
 
Example #10
Source File: BaseAWSEC2ApiTest.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override protected void assertNonPayloadHeadersEqual(HttpRequest request, String toMatch) {
   Multimap<String, String> headersToCheck = LinkedHashMultimap.create();
   for (String key : request.getHeaders().keySet()) {
      if (key.equals("X-Amz-Date")) {
         assertEquals(request.getFirstHeaderOrNull(key), "20120416T155408Z");
      } else if (key.equals("Authorization")) {
         assertThat(request.getFirstHeaderOrNull(AUTHORIZATION)).startsWith(
               "AWS4-HMAC-SHA256 Credential=identity/20120416/"
                     + "us-east-1/ec2/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=");
      } else {
         headersToCheck.putAll(key, request.getHeaders().get(key));
      }
   }
   assertEquals(sortAndConcatHeadersIntoString(headersToCheck), toMatch);
}
 
Example #11
Source File: GeneratedColumnComparisonReplacer.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private Multimap<ReferenceInfo, GeneratedReferenceInfo> extractGeneratedReferences(DocTableInfo tableInfo) {
    Multimap<ReferenceInfo, GeneratedReferenceInfo> multiMap = HashMultimap.create();

    for (GeneratedReferenceInfo referenceInfo : tableInfo.generatedColumns()) {
        if (referenceInfo.referencedReferenceInfos().size() == 1 &&
            tableInfo.partitionedByColumns().contains(referenceInfo)) {
            multiMap.put(referenceInfo.referencedReferenceInfos().get(0), referenceInfo);
        }
    }
    return multiMap;
}
 
Example #12
Source File: StructuredDataTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testConversionError() {
  setupSchema();
  Multimap<String, Object> values = ArrayListMultimap.create();
  values.put("integerProperty", "v1");
  thrown.expect(NumberFormatException.class);
  StructuredData.getStructuredData("myObject", values);
}
 
Example #13
Source File: AlertFilterUtils.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
static MergedAnomalyResultDTO makeAnomaly(Long configId, long baseTime, long start, long end,
    Map<String, String> dimensions, AnomalyFeedbackDTO feedback) {
  MergedAnomalyResultDTO anomaly = DetectionTestUtils.makeAnomaly(configId, baseTime + start, baseTime + end);
  anomaly.setType(AnomalyType.DEVIATION);
  anomaly.setChildIds(Collections.emptySet());

  Multimap<String, String> filters = HashMultimap.create();
  for (Map.Entry<String, String> dimension : dimensions.entrySet()) {
    filters.put(dimension.getKey(), dimension.getValue());
  }
  anomaly.setMetricUrn(MetricEntity.fromMetric(1.0, 1l, filters).getUrn());

  DimensionMap dimMap = new DimensionMap();
  dimMap.putAll(dimensions);
  anomaly.setDimensions(dimMap);

  anomaly.setCreatedBy("no-auth-user");
  anomaly.setUpdatedBy("no-auth-user");
  anomaly.setId(DAORegistry.getInstance().getMergedAnomalyResultDAO().save(anomaly));

  if (feedback != null) {
    anomaly.setFeedback(feedback);
    anomaly.setDimensions(null);
    DAORegistry.getInstance().getMergedAnomalyResultDAO().updateAnomalyFeedback(anomaly);
  }

  return anomaly;
}
 
Example #14
Source File: DataResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@code true} if a given anomaly passes the dimension filters {@code filters}, or
 * {@code false} otherwise. If {@code filters} contains multiple values for the same dimension
 * key, ANY match will pass the filter.
 *
 * @param anomaly anomaly to filter
 * @param filters dimension filter multimap
 * @return {@code true} if anomaly passed the filters, {@code false} otherwise
 */
static boolean applyAnomalyFilters(MergedAnomalyResultDTO anomaly, Multimap<String, String> filters) {
  Multimap<String, String> anomalyFilter = AnomaliesResource.generateFilterSetForTimeSeriesQuery(anomaly);
  for (String filterKey : filters.keySet()) {
    if (!anomalyFilter.containsKey(filterKey))
      return false;

    Collection<String> filterValues = filters.get(filterKey);
    if (!filterValues.containsAll(anomalyFilter.get(filterKey)))
      return false;
  }
  return true;
}
 
Example #15
Source File: PaymentChannelV2ServerState.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Multimap<State, State> getStateTransitions() {
    Multimap<State, State> result = MultimapBuilder.enumKeys(State.class).arrayListValues().build();
    result.put(State.UNINITIALISED, State.READY);
    result.put(State.UNINITIALISED, State.WAITING_FOR_MULTISIG_CONTRACT);
    result.put(State.WAITING_FOR_MULTISIG_CONTRACT, State.WAITING_FOR_MULTISIG_ACCEPTANCE);
    result.put(State.WAITING_FOR_MULTISIG_ACCEPTANCE, State.READY);
    result.put(State.READY, State.CLOSING);
    result.put(State.CLOSING, State.CLOSED);
    for (State state : State.values()) {
        result.put(state, State.ERROR);
    }
    return result;
}
 
Example #16
Source File: DefaultControllerTest.java    From yarg with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonExtractionForBand() throws IOException, URISyntaxException {
    ReportBand band = YmlDataUtil.bandFrom(FileLoader.load("extraction/fixture/default_json_report_band.yml"));

    BandData rootBand = new BandData(BandData.ROOT_BAND_NAME);
    rootBand.setData(new HashMap<>());
    rootBand.setFirstLevelBandDefinitionNames(new HashSet<>());

    Multimap<String, BandData> reportBandMap = HashMultimap.create();

    for (ReportBand definition : band.getChildren()) {
        List<BandData> data = controllerFactory.controllerBy(definition.getBandOrientation())
                .extract(contextFactory.context(definition, rootBand, ExtractionUtils.getParams(definition)));

        Assert.assertNotNull(data);

        data.forEach(b-> {
            Assert.assertNotNull(b);
            Assert.assertTrue(StringUtils.isNotEmpty(b.getName()));

            reportBandMap.put(b.getName(), b);
        });

        rootBand.addChildren(data);
        rootBand.getFirstLevelBandDefinitionNames().add(definition.getName());
    }

    checkHeader(reportBandMap.get("header"), 2, "name", "id");
    checkMasterData(reportBandMap.get("master_data"), 2, 2,
            "id", "name", "value", "user_id");
}
 
Example #17
Source File: AndroidResourceProcessor.java    From bazel with Apache License 2.0 5 votes vote down vote up
void writeDependencyPackageRJavaFiles(
    List<DependencyAndroidData> dependencyData,
    String customPackageForR,
    Path androidManifest,
    Path sourceOut)
    throws IOException {
  List<SymbolFileProvider> libraries = new ArrayList<>();
  for (DependencyAndroidData dataDep : dependencyData) {
    SymbolFileProvider library = dataDep.asSymbolFileProvider();
    libraries.add(library);
  }
  String appPackageName = customPackageForR;
  if (appPackageName == null) {
    appPackageName = VariantConfiguration.getManifestPackage(androidManifest.toFile());
  }
  Multimap<String, ResourceSymbols> libSymbolMap = ArrayListMultimap.create();
  Path primaryRTxt = sourceOut != null ? sourceOut.resolve("R.txt") : null;
  if (primaryRTxt != null && !libraries.isEmpty()) {
    ResourceSymbols fullSymbolValues =
        loadResourceSymbolTable(libraries, appPackageName, primaryRTxt, libSymbolMap);
    // Loop on all the package name, merge all the symbols to write, and write.
    for (String packageName : libSymbolMap.keySet()) {
      Collection<ResourceSymbols> symbols = libSymbolMap.get(packageName);
      fullSymbolValues.writeSourcesTo(sourceOut, packageName, symbols, /* finalFields= */ true);
    }
  }
}
 
Example #18
Source File: HTTPMethod.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get all Request headers as a map of name to list of values.
 * A value may be null.
 *
 * @return Map, may be empty but not null.
 */
public Multimap<String, String> getRequestHeaders() {
  if (this.lastrequest == null)
    return ImmutableMultimap.of();

  ArrayListMultimap<String, String> multimap = ArrayListMultimap.create();
  for (Header header : this.lastrequest.getAllHeaders()) {
    for (HeaderElement element : header.getElements()) {
      multimap.put(element.getName(), element.getValue());
    }
  }
  return multimap;
}
 
Example #19
Source File: CollectorUtilsTest.java    From bundletool with Apache License 2.0 5 votes vote down vote up
@Test
public void groupingBySortedKeys() {
  Multimap<Integer, String> map =
      Stream.of("this", "is", "a", "test", "for", "that", "method")
          .collect(CollectorUtils.groupingBySortedKeys(String::length));

  assertThat(map)
      .containsExactly(1, "a", 2, "is", 3, "for", 4, "this", 4, "test", 4, "that", 6, "method")
      .inOrder();
}
 
Example #20
Source File: TmfFilterHelperTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private static Predicate<Multimap<String, Object>> getRegex(ITmfFilter filter, String expected) {
    String regex = TmfFilterHelper.getRegexFromFilter(filter);
    assertEquals(expected, regex);
    FilterCu compile = FilterCu.compile(regex);
    assertNotNull(compile);
    Predicate<Multimap<String, Object>> predicate = compile.generate();
    return predicate;
}
 
Example #21
Source File: ComplexGrammaticalForm.java    From grammaticus with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * For possessive languages, it makes sense to keep an enum map around for that
 */
public static <A extends NounForm> EnumMap<LanguagePossessive,NounFormMap<A>> getPossessiveSpecificMap(Collection<? extends A> forms) {
    Multimap<LanguagePossessive,A> mm = ArrayListMultimap.create();
    for (A form : forms) {
        mm.put(form.getPossessive(), form);
    }
    EnumMap<LanguagePossessive,NounFormMap<A>> result = new EnumMap<LanguagePossessive,NounFormMap<A>>(LanguagePossessive.class);
    for (LanguagePossessive poss : LanguagePossessive.values()) {
        result.put(poss, new NounFormMap<A>(mm.get(poss)));
    }
    return result;
}
 
Example #22
Source File: ContentIndexingColumnBasedHandlerTest.java    From datawave with Apache License 2.0 5 votes vote down vote up
private Collection<Value> getCorrespondingValue(Multimap<BulkIngestKey,Value> entries, BulkIngestKey expectedBulkIngestKey) {
    for (BulkIngestKey actualBulkIngestKey : entries.keySet()) {
        if (actualBulkIngestKey.getTableName().equals(expectedBulkIngestKey.getTableName())
                        && actualBulkIngestKey.getKey().equals(expectedBulkIngestKey.getKey(), PartialKey.ROW_COLFAM_COLQUAL_COLVIS)) {
            return entries.get(actualBulkIngestKey);
        }
    }
    return null;
}
 
Example #23
Source File: PojoOuterJoinTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Test
public void PojoFullOuterJoinTestWithMap()
{
  String[] leftKeys = {"uId", "uName"};
  String[] rightKeys = {"uId", "uNickName"};
  Map<String,KeyValPair<AbstractPojoJoin.STREAM, String>> outputInputMap = new HashMap<>();
  outputInputMap.put("uId",new KeyValPair<>(AbstractPojoJoin.STREAM.LEFT,"uId"));
  outputInputMap.put("age",new KeyValPair<>(AbstractPojoJoin.STREAM.RIGHT,"age"));
  PojoFullOuterJoin<TestPojo1, TestPojo3> pij = new PojoFullOuterJoin<>(TestOutClass.class, leftKeys, rightKeys, outputInputMap);

  List<Multimap<List<Object>, Object>> accu = pij.defaultAccumulatedValue();

  Assert.assertEquals(2, accu.size());

  accu = pij.accumulate(accu, new TestPojo1(1, "Josh"));
  accu = pij.accumulate(accu, new TestPojo1(2, "Bob"));

  accu = pij.accumulate2(accu, new TestPojo3(1, "Josh", 12));
  accu = pij.accumulate2(accu, new TestPojo3(3, "Bob", 13));

  Assert.assertEquals(3, pij.getOutput(accu).size());
  Set<Integer> checkMap = new HashSet<>();
  for ( int i = 0; i < 3; i++ ) {
    Object o = pij.getOutput(accu).get(i);
    Assert.assertTrue(o instanceof TestOutClass);
    TestOutClass testOutClass = (TestOutClass)o;
    int uId = testOutClass.getUId();
    checkMap.add(uId);
  }
  Assert.assertEquals(3,checkMap.size());
}
 
Example #24
Source File: Closure_103_DisambiguateProperties_t.java    From coming with MIT License 5 votes vote down vote up
/** Returns a map from field name to types for which it will be renamed. */
Multimap<String, Collection<T>> getRenamedTypesForTesting() {
  Multimap<String, Collection<T>> ret = HashMultimap.create();
  for (Map.Entry<String, Property> entry: properties.entrySet()) {
    Property prop = entry.getValue();
    if (!prop.skipRenaming) {
      for (Collection<T> c : prop.getTypes().allEquivalenceClasses()) {
        if (!c.isEmpty() && !prop.typesToSkip.contains(c.iterator().next())) {
          ret.put(entry.getKey(), c);
        }
      }
    }
  }
  return ret;
}
 
Example #25
Source File: JiraContentFormatter.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private String buildSummary(Map<String, Object> templateValues, Multimap<String, String> dimensionFilters) {
  String issueSummary =
      BaseNotificationContent.makeSubject(super.getSubjectType(alertClientConfig), this.subsConfig, templateValues);

  // Append dimensional info to summary
  StringBuilder dimensions = new StringBuilder();
  for (Map.Entry<String, Collection<String>> dimFilter : dimensionFilters.asMap().entrySet()) {
    dimensions.append(", ").append(dimFilter.getKey()).append("=").append(String.join(",", dimFilter.getValue()));
  }
  issueSummary = issueSummary + dimensions.toString();

  // Truncate summary due to jira character limit
  return StringUtils.abbreviate(issueSummary, MAX_JIRA_SUMMARY_LENGTH);
}
 
Example #26
Source File: MongoDBQueryEngine.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public CloseableIteration<? extends Entry<RyaStatement, BindingSet>, RyaDAOException> queryWithBindingSet(
        final Collection<Entry<RyaStatement, BindingSet>> stmts,
        final StatefulMongoDBRdfConfiguration conf) throws RyaDAOException {
    checkNotNull(stmts);
    checkNotNull(conf);

    final Multimap<RyaStatement, BindingSet> rangeMap = HashMultimap.create();

    //TODO: cannot span multiple tables here
    try {
        for (final Map.Entry<RyaStatement, BindingSet> stmtbs : stmts) {
            final RyaStatement stmt = stmtbs.getKey();
            final BindingSet bs = stmtbs.getValue();
            rangeMap.put(stmt, bs);
        }

        // TODO not sure what to do about regex ranges?
        final RyaStatementBindingSetCursorIterator iterator = new RyaStatementBindingSetCursorIterator(
                getCollection(conf), rangeMap, strategy, conf.getAuthorizations());

        return iterator;
    } catch (final Exception e) {
        throw new RyaDAOException(e);
    }

}
 
Example #27
Source File: ZipFilterAction.java    From bazel with Apache License 2.0 5 votes vote down vote up
static int run(String[] args) throws IOException {
  Options options = new Options();
  new JCommander(options).parse(args);
  logger.fine(
      String.format(
          "Creating filter from entries of type %s, in zip files %s.",
          options.filterTypes, options.filterZips));

  final Stopwatch timer = Stopwatch.createStarted();
  Multimap<String, Long> entriesToOmit =
      getEntriesToOmit(options.filterZips, options.filterTypes);
  final String explicitFilter =
      options.explicitFilters.isEmpty()
          ? ""
          : String.format(".*(%s).*", Joiner.on("|").join(options.explicitFilters));
  logger.fine(String.format("Filter created in %dms", timer.elapsed(TimeUnit.MILLISECONDS)));

  ImmutableMap.Builder<String, Long> inputEntries = ImmutableMap.builder();
  try (ZipReader input = new ZipReader(options.inputZip.toFile())) {
    for (ZipFileEntry entry : input.entries()) {
      inputEntries.put(entry.getName(), entry.getCrc());
    }
  }

  // TODO(jingwen): Remove --errorOnHashMismatch when Blaze release with --checkHashMismatch
  // is checked in.
  if (options.errorOnHashMismatch) {
    options.hashMismatchCheckMode = HashMismatchCheckMode.ERROR;
  }
  ZipFilterEntryFilter entryFilter =
      new ZipFilterEntryFilter(
          explicitFilter, entriesToOmit, inputEntries.build(), options.hashMismatchCheckMode);

  try (OutputStream out = Files.newOutputStream(options.outputZip);
      ZipCombiner combiner = new ZipCombiner(options.outputMode, entryFilter, out)) {
    combiner.addZip(options.inputZip.toFile());
  }
  logger.fine(String.format("Filtering completed in %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
  return entryFilter.sawErrors() ? 1 : 0;
}
 
Example #28
Source File: OntologyTagServiceTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testGetTagsForAttribute() {
  EntityType emd = entityTypeFactory.create("org.molgenis.SNP");
  Attribute attribute = attrFactory.create().setName("Chr");
  attribute.setTags(asList(chromosomeNameTagEntity, geneAnnotationTagEntity));

  Relation instanceOf = Relation.valueOf("instanceOf");

  Ontology edamOntology =
      Ontology.create("EDAM", "http://edamontology.org", "The EDAM ontology.");
  OntologyTerm chromosomeName =
      OntologyTerm.create(
          "http://edamontology.org/data_0987", "Chromosome name", "Name of a chromosome.");
  OntologyTerm geneAnnotation =
      OntologyTerm.create(
          "http://edamontology.org/data_0919",
          "Gene annotation (chromosome)",
          "This includes basic information. e.g. chromosome number...");

  when(ontologyService.getOntology("http://edamontology.org")).thenReturn(edamOntology);
  when(ontologyService.getOntologyTerm("http://edamontology.org/data_0987"))
      .thenReturn(chromosomeName);
  when(ontologyService.getOntologyTerm("http://edamontology.org/data_0919"))
      .thenReturn(geneAnnotation);

  Multimap<Relation, OntologyTerm> expected = LinkedHashMultimap.create();
  expected.put(instanceOf, chromosomeName);
  expected.put(instanceOf, geneAnnotation);

  assertEquals(expected, ontologyTagService.getTagsForAttribute(emd, attribute));
}
 
Example #29
Source File: ResolvedFeatures.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void computeAllOperationsFromSuperTypes(JvmDeclaredType type, Multimap<String, AbstractResolvedOperation> processedOperations,
		Set<JvmType> processedTypes) {
	for (JvmTypeReference superType: type.getSuperTypes()) {
		JvmType rawSuperType = superType.getType();
		if (rawSuperType instanceof JvmDeclaredType && !rawSuperType.eIsProxy() && processedTypes.add(rawSuperType)) {
			computeAllOperations((JvmDeclaredType) rawSuperType, processedOperations);
			computeAllOperationsFromSuperTypes((JvmDeclaredType) rawSuperType, processedOperations, processedTypes);
		}
	}
}
 
Example #30
Source File: MultiOrganizeImportsHandler.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void collectRelevantFiles(IPackageFragment element, Multimap<IProject, IFile> result)
		throws JavaModelException {
	if (!element.isDefaultPackage()) {
		collectIFiles(result, element.getNonJavaResources());
	} else if (element.getResource() instanceof IFolder) {
		IFolder folder = (IFolder) element.getResource();
		try {
			collectIFiles(result, folder.members());
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}