com.google.common.collect.HashMultimap Java Examples

The following examples show how to use com.google.common.collect.HashMultimap. 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: AnnotationPublisher.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Populate existing issues for type.
 *
 * @param ruleParam the rule param
 * @throws Exception the exception
 */
public void populateExistingIssuesForType(Map<String, String> ruleParam) throws Exception {

    String esUrl = ESUtils.getEsUrl();
    String ruleId = ruleParam.get(PacmanSdkConstants.RULE_ID);
    String indexName = CommonUtils.getIndexNameFromRuleParam(ruleParam);
    Map<String, Object> mustFilter = new HashMap<>();
    String attributeToQuery = ESUtils.convertAttributetoKeyword(PacmanSdkConstants.RULE_ID); //actual attribute will be  tokenized hence querying on keyword
    mustFilter.put(attributeToQuery, ruleId);
    List<String> fields = new ArrayList<String>();
    Map<String, Object> mustNotFilter = new HashMap<>();
    mustNotFilter.put("issueStatus.keyword", "closed");
    HashMultimap<String, Object> shouldFilter = HashMultimap.create();
    shouldFilter.put("type.keyword", "recommendation");
    shouldFilter.put("type.keyword", "issue");
    Long totalDocs = ESUtils.getTotalDocumentCountForIndexAndType(esUrl, indexName, null, mustFilter, mustNotFilter,
            shouldFilter);
    // get all the issues for this ruleId
    List<Map<String, String>> existingIssues = ESUtils.getDataFromES(esUrl, indexName.toLowerCase(), null,
            mustFilter, mustNotFilter, shouldFilter, fields, 0, totalDocs);
    existingIssues.stream().forEach(obj -> {
        existingIssuesMapWithAnnotationIdAsKey.put(obj.get(PacmanSdkConstants.ES_DOC_ID_KEY), obj);
    });
}
 
Example #2
Source File: UIResourceChangeRegistry.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public void readState(final InputStream in) {
  try {
    final DataInputStream reader = new DataInputStream(in);
    for (final HashMultimap<String, URI> map : Collections.<HashMultimap<String, URI>>unmodifiableList(CollectionLiterals.<HashMultimap<String, URI>>newArrayList(this.existsListeners, this.charsetListeners, this.childrenListeners, this.contentsListeners))) {
      {
        final int urisForExists = reader.readInt();
        for (int i = 0; (i < urisForExists); i++) {
          {
            final String path = reader.readUTF();
            final String uri = reader.readUTF();
            map.put(path, URI.createURI(uri));
          }
        }
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #3
Source File: CardinalityConfiguration.java    From datawave with Apache License 2.0 6 votes vote down vote up
private Set<String> getStoredProjectionFields() {
    Set<String> initialProjectionFields = new HashSet<>();
    Set<String> finalProjectionFields = new HashSet<>();
    initialProjectionFields.addAll(getAllFieldNames());
    if (cardinalityUidField != null) {
        initialProjectionFields.add(cardinalityUidField);
    }
    
    // remove fields that will not be stored with the event
    initialProjectionFields.removeAll(Arrays.asList(nonDocumentFields));
    
    // map local model names to the stored names that the tserver will find
    Multimap<String,String> forwardMap = HashMultimap.create();
    for (Map.Entry<String,String> entry : cardinalityFieldReverseMapping.entrySet()) {
        forwardMap.put(entry.getValue(), entry.getKey());
    }
    for (String f : initialProjectionFields) {
        if (forwardMap.containsKey(f)) {
            finalProjectionFields.addAll(forwardMap.get(f));
        } else {
            finalProjectionFields.add(f);
        }
    }
    return finalProjectionFields;
}
 
Example #4
Source File: ThirdEyeUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Returns or modifies a filter that can be for querying the results corresponding to the given dimension map.
 *
 * For example, if a dimension map = {country=IN,page_name=front_page}, then the two entries will be added or
 * over-written to the given filter.
 *
 * Note that if the given filter contains an entry: country=["IN", "US", "TW",...], then this entry is replaced by
 * country=IN.
 *
 * @param dimensionMap the dimension map to add to the filter
 * @param filterToDecorate if it is null, a new filter will be created; otherwise, it is modified.
 * @return a filter that is modified according to the given dimension map.
 */
public static Multimap<String, String> getFilterSetFromDimensionMap(DimensionMap dimensionMap,
    Multimap<String, String> filterToDecorate) {
  if (filterToDecorate == null) {
    filterToDecorate = HashMultimap.create();
  }

  for (Map.Entry<String, String> entry : dimensionMap.entrySet()) {
    String dimensionName = entry.getKey();
    String dimensionValue = entry.getValue();
    // If dimension value is "OTHER", then we need to get all data and calculate "OTHER" part.
    // In order to reproduce the data for "OTHER", the filter should remain as is.
    if ( !dimensionValue.equalsIgnoreCase("OTHER") ) {
      // Only add the specific dimension value to the filter because other dimension values will not be used
      filterToDecorate.removeAll(dimensionName);
      filterToDecorate.put(dimensionName, dimensionValue);
    }
  }

  return filterToDecorate;
}
 
Example #5
Source File: IndexInfo.java    From datawave with Apache License 2.0 6 votes vote down vote up
protected Set<IndexMatch> buildNodeList(HashMultimap<String,JexlNode> ids, IndexMatchType type, boolean allowsDelayed, List<JexlNode> delayedNodes) {
    Set<IndexMatch> matches = Sets.newHashSet();
    for (String uid : ids.keySet()) {
        
        Set<JexlNode> nodes = ids.get(uid);
        // make sure that we have nodes, otherwise we are pruned to nothing
        if (nodes.size() > 1 || (allowsDelayed && (nodes.size() + delayedNodes.size()) > 1)) {
            JexlNodeSet nodeSet = new JexlNodeSet();
            nodeSet.addAll(nodes);
            nodeSet.addAll(delayedNodes);
            
            IndexMatch currentMatch = new IndexMatch(Sets.newHashSet(nodeSet.getNodes()), uid, type);
            matches.add(currentMatch);
        }
    }
    return matches;
}
 
Example #6
Source File: TestTaskExecution.java    From incubator-tez with Apache License 2.0 6 votes vote down vote up
private TezTaskRunner createTaskRunner(ApplicationId appId, TezTaskUmbilicalForTest umbilical,
    TaskReporter taskReporter, ListeningExecutorService executor, byte[] processorConf)
    throws IOException {
  TezConfiguration tezConf = new TezConfiguration(defaultConf);
  UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
  Path testDir = new Path(workDir, UUID.randomUUID().toString());
  String[] localDirs = new String[] { testDir.toString() };

  TezDAGID dagId = TezDAGID.getInstance(appId, 1);
  TezVertexID vertexId = TezVertexID.getInstance(dagId, 1);
  TezTaskID taskId = TezTaskID.getInstance(vertexId, 1);
  TezTaskAttemptID taskAttemptId = TezTaskAttemptID.getInstance(taskId, 1);
  ProcessorDescriptor processorDescriptor = new ProcessorDescriptor(TestProcessor.class.getName())
      .setUserPayload(processorConf);
  TaskSpec taskSpec = new TaskSpec(taskAttemptId, "dagName", "vertexName", processorDescriptor,
      new ArrayList<InputSpec>(), new ArrayList<OutputSpec>(), null);

  TezTaskRunner taskRunner = new TezTaskRunner(tezConf, ugi, localDirs, taskSpec, umbilical, 1,
      new HashMap<String, ByteBuffer>(), HashMultimap.<String, String> create(), taskReporter,
      executor);
  return taskRunner;
}
 
Example #7
Source File: CheckPluginDependencyVersions.java    From unleash-maven-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private Multimap<ArtifactCoordinates, ArtifactCoordinates> getSnapshots(Profile profile,
    PomPropertyResolver propertyResolver) {
  this.log.debug("\t\tChecking direct plugin references of profile '" + profile.getId() + "'");
  Multimap<ArtifactCoordinates, ArtifactCoordinates> result = HashMultimap.create();
  BuildBase build = profile.getBuild();
  if (build != null) {
    for (Plugin plugin : build.getPlugins()) {
      Collection<Dependency> snapshots = Collections2.filter(plugin.getDependencies(),
          new IsSnapshotDependency(propertyResolver));
      if (!snapshots.isEmpty()) {
        result.putAll(PluginToCoordinates.INSTANCE.apply(plugin),
            Collections2.transform(snapshots, DependencyToCoordinates.INSTANCE));
      }
    }
  }
  return result;
}
 
Example #8
Source File: VinSampler.java    From log-synth with Apache License 2.0 6 votes vote down vote up
private static SetMultimap<String, String> multiMapResource(String name) throws IOException {
    final Splitter onTab = Splitter.on("\t");

    //noinspection UnstableApiUsage
    return Resources.readLines(Resources.getResource(name), Charsets.UTF_8, new LineProcessor<SetMultimap<String, String>>() {
        final SetMultimap<String, String> r = HashMultimap.create();

        @Override
        public boolean processLine(String line) {
            Iterator<String> pieces = onTab.split(line).iterator();
            String key = pieces.next();
            r.put(key, pieces.next());
            return true;
        }

        @Override
        public SetMultimap<String, String> getResult() {
            return r;
        }
    });
}
 
Example #9
Source File: ProjectLocationAwareWorkingSetManager.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private Multimap<String, IProject> initProjectLocation() {
	final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	final IProject[] projects = root.getProjects();
	final Multimap<String, IProject> locations = HashMultimap.create();

	// initialize the repository paths
	repositoryPaths = repositoriesProvider.getWorkspaceRepositories().stream()
			.map(r -> r.getDirectory().getParentFile().toPath()).collect(Collectors.toSet());

	for (final IProject project : projects) {
		if (isRemoteEditNature(project)) {
			continue;
		}
		final String pair = getWorkingSetId(project);
		locations.put(pair, project);
	}

	return locations;
}
 
Example #10
Source File: Frame.java    From OSRS-Deobfuscator with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public Frame(Execution execution, Method method)
{
	this.execution = execution;
	this.method = method;

	Code code = method.getCode();

	stack = new Stack(code.getMaxStack());
	variables = new Variables(code.getMaxLocals());
	ctx = new MethodContext(execution, method);
	nonStatic = method;

	exceptions = HashMultimap.create();
	Exceptions codeExceptions = code.getExceptions();
	for (Exception ex : codeExceptions.getExceptions())
	{
		Instruction i = ex.getStart().next();
		exceptions.put(i, ex);
	}
}
 
Example #11
Source File: WorkerQueuesTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void cpuGpuConfig_invalidProvisionEnqueued() {

  // Arrange
  WorkerQueues queues = WorkerQueueConfigurations.gpuAndFallback();

  // Act
  Operation operation = Operation.newBuilder().build();
  SetMultimap<String, String> provisions = HashMultimap.create();
  provisions.put("invalid_key", "invalid_value");
  boolean success = queues.enqueueOperation(operation, provisions);

  // Assert
  assertThat(success).isTrue();
  assertThat(queues.queueSize("GPU")).isEqualTo(0);
  assertThat(queues.queueSize("Other")).isEqualTo(1);
}
 
Example #12
Source File: ConceptTest.java    From similarity with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    Multimap<String, Concept> CONCEPTS = HashMultimap.create();
    CONCEPTS.put("打", new Concept("打", "V", "TakeOutOfWater|捞起"));
    CONCEPTS.put("打", new Concept("打", "V", "TakeOutOfWater|捞起"));
    CONCEPTS.put("打", new Concept("打", "V", "TakeOutOfWater|捞起"));
    CONCEPTS.put("打", new Concept("打", "V", "TakeOutOfWater|捞起"));

    Collection<Concept> collection = CONCEPTS.get("打");
    for (Concept c : collection) {
        System.out.println(c);

    }

    Multimap<String, Integer> map = HashMultimap.create();
    map.put("打", 1);
    map.put("打", 1);
    map.put("打", 1);
    map.put("打", 2);

    Collection<Integer> cc = map.get("打");
    for (Integer i : cc) {
        System.out.println(i);
    }
}
 
Example #13
Source File: ZKDiscoveryService.java    From twill with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs ZKDiscoveryService using the provided zookeeper client for storing service registry under namespace.
 * @param zkClient of zookeeper quorum
 * @param namespace under which the service registered would be stored in zookeeper.
 *                  If namespace is {@code null}, no namespace will be used.
 */
public ZKDiscoveryService(ZKClient zkClient, String namespace) {
  this.closed = new AtomicBoolean();
  this.discoverables = HashMultimap.create();
  this.lock = new ReentrantLock();
  this.retryExecutor = Executors.newSingleThreadScheduledExecutor(
    Threads.createDaemonThreadFactory("zk-discovery-retry"));
  this.zkClient = namespace == null ? zkClient : ZKClients.namespace(zkClient, namespace);
  this.services = CacheBuilder.newBuilder()
    .removalListener(new RemovalListener<String, ServiceDiscoveredCacheEntry>() {
      @Override
      public void onRemoval(RemovalNotification<String, ServiceDiscoveredCacheEntry> notification) {
        ServiceDiscoveredCacheEntry entry = notification.getValue();
        if (entry != null) {
          entry.cancel();
        }
      }
    })
    .build(createServiceLoader());
  this.watcherCancellable = this.zkClient.addConnectionWatcher(createConnectionWatcher());
}
 
Example #14
Source File: Http1FilterUnitTest.java    From xio with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeniedRule() throws UnknownHostException {
  List<Http1DeterministicRuleEngineConfig.Rule> blacklist = new ArrayList<>();
  HashMultimap<String, String> headers = HashMultimap.create();
  headers.put("User-Agent", "Bad-actor: 1.0");
  Http1DeterministicRuleEngineConfig.Rule bad =
      new Http1DeterministicRuleEngineConfig.Rule(
          HttpMethod.GET, "/path/to/failure", HttpVersion.HTTP_1_0, headers);
  blacklist.add(bad);
  Http1Filter http1Filter =
      new Http1Filter(new Http1FilterConfig(ImmutableList.copyOf(blacklist)));
  EmbeddedChannel chDeny = new EmbeddedChannel(http1Filter);
  DefaultHttpRequest request =
      new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/path/to/failure");
  request.headers().set("User-Agent", "Bad-actor: 1.0");
  chDeny.writeInbound(request);
  chDeny.runPendingTasks();
  assertFalse(chDeny.isActive());
  assertFalse(chDeny.isOpen());
}
 
Example #15
Source File: EventQueryDataDecoratorTransformer.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Override
public Object transform(Object o) {
    
    if (o instanceof EventBase) {
        EventBase e = (EventBase) o;
        List<? extends FieldBase> fields = e.getFields();
        Multimap<String,FieldBase> fieldMap = HashMultimap.create();
        for (FieldBase f : fields) {
            fieldMap.put(f.getName(), f);
        }
        
        for (String d : requestedDecorators) {
            
            EventQueryDataDecorator decorator = dataDecorators.get(d);
            if (decorator != null) {
                decorator.decorateData(fieldMap);
            }
        }
        e.setFields(new ArrayList<>(fieldMap.values()));
        return e;
    } else {
        return o;
    }
}
 
Example #16
Source File: AbstractNormalizer.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Override
public Multimap<String,NormalizedContentInterface> normalizeMap(Multimap<String,NormalizedContentInterface> fields) {
    Multimap<String,NormalizedContentInterface> results = HashMultimap.create();
    // if handling all fields, then we need to navigate the entire list
    for (Entry<String,NormalizedContentInterface> field : fields.entries()) {
        if (field.getValue() != null) {
            NormalizedContentInterface normalizedContent = field.getValue();
            try {
                normalizedContent = normalize(field.getValue());
            } catch (Exception e) {
                log.error("Failed to normalize " + field.getValue().getIndexedFieldName() + '=' + field.getValue().getIndexedFieldValue(), e);
                normalizedContent.setError(e);
            }
            results.put(normalizedContent.getIndexedFieldName(), normalizedContent);
        }
    }
    return results;
}
 
Example #17
Source File: SegmentRoutingManager.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns vlan port map of given device.
 *
 * @param deviceId device id
 * @return vlan-port multimap
 */
public Multimap<VlanId, PortNumber> getVlanPortMap(DeviceId deviceId) {
    HashMultimap<VlanId, PortNumber> vlanPortMap = HashMultimap.create();

    interfaceService.getInterfaces().stream()
            .filter(intf -> intf.connectPoint().deviceId().equals(deviceId))
            .forEach(intf -> {
                vlanPortMap.put(intf.vlanUntagged(), intf.connectPoint().port());
                intf.vlanTagged().forEach(vlanTagged ->
                    vlanPortMap.put(vlanTagged, intf.connectPoint().port())
                );
                vlanPortMap.put(intf.vlanNative(), intf.connectPoint().port());
            });
    vlanPortMap.removeAll(VlanId.NONE);

    return vlanPortMap;
}
 
Example #18
Source File: GraphTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testTopologicalSorting() {
  Multimap<String, String> graph = HashMultimap.create();
  graph.put("7", "11");
  graph.put("7", "8");
  graph.put("3", "8");
  graph.put("3", "10");
  graph.put("11", "2");
  graph.put("11", "9");
  graph.put("11", "10");
  graph.put("8", "8");
  graph.put("8", "9");
  graph.put("8", "10");

  List<String> sorted = Graph.create(graph).sort();
  assertSorting(graph, sorted);
}
 
Example #19
Source File: ScanResult.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@JsonCreator public ScanResult(
    @JsonProperty("scannedPackages") Collection<String> scannedPackages,
    @JsonProperty("scannedClasses") Collection<String> scannedClasses,
    @JsonProperty("scannedAnnotations") Collection<String> scannedAnnotations,
    @JsonProperty("annotatedClasses") Collection<AnnotatedClassDescriptor> annotatedClasses,
    @JsonProperty("implementations") Collection<ParentClassDescriptor> implementations) {
  this.scannedPackages = unmodifiableList(new ArrayList<>(checkNotNull(scannedPackages)));
  this.scannedClasses = unmodifiableSet(new HashSet<>(checkNotNull(scannedClasses)));
  this.scannedAnnotations = unmodifiableSet(new HashSet<>(checkNotNull(scannedAnnotations)));
  this.annotatedClasses = unmodifiableList(new ArrayList<>(checkNotNull(annotatedClasses)));
  this.implementations = unmodifiableList(new ArrayList<>(checkNotNull(implementations)));
  this.parentClassByName = new HashMap<>();
  for (ParentClassDescriptor parentClassDescriptor : implementations) {
    this.parentClassByName.put(parentClassDescriptor.getName(), parentClassDescriptor);
  }
  this.annotationsByName = HashMultimap.create();
  for (AnnotatedClassDescriptor annotated : annotatedClasses) {
    for (AnnotationDescriptor annotationDescriptor : annotated.getAnnotations()) {
      if (scannedAnnotations.contains(annotationDescriptor.getAnnotationType())) {
        this.annotationsByName.put(annotationDescriptor.getAnnotationType(), annotated);
      }
    }
  }
}
 
Example #20
Source File: ExpandMultiNormalizedTermsTest.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiNormalizedFieldOpField() throws ParseException {
    Multimap<String,Type<?>> dataTypes = HashMultimap.create();
    dataTypes.putAll("FOO", Sets.newHashSet(new LcNoDiacriticsType(), new LcType()));
    
    helper.setIndexedFields(dataTypes.keySet());
    helper.setIndexOnlyFields(dataTypes.keySet());
    helper.addTermFrequencyFields(dataTypes.keySet());
    
    config.setQueryFieldsDatatypes(dataTypes);
    
    // No change expected
    String original = "FOO == FOO";
    expandTerms(original, original);
}
 
Example #21
Source File: RangeStreamTest.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonIndexedNumeric() throws Exception {
    String originalQuery = "(FOO == 'bag' && BAR == 4)";
    ASTJexlScript script = JexlASTHelper.parseJexlQuery(originalQuery);
    
    config.setBeginDate(new Date(0));
    config.setEndDate(new Date(System.currentTimeMillis()));
    
    Multimap<String,Type<?>> dataTypes = HashMultimap.create();
    dataTypes.putAll("FOO", Sets.newHashSet(new LcNoDiacriticsType()));
    
    config.setQueryFieldsDatatypes(dataTypes);
    config.setIndexedFields(dataTypes);
    
    MockMetadataHelper helper = new MockMetadataHelper();
    helper.setIndexedFields(dataTypes.keySet());
    helper.addFields(Lists.newArrayList("BAR"));
    
    Range range1 = makeTestRange("20190314", "datatype1\u0000234");
    Range range2 = makeTestRange("20190314", "datatype1\u0000345");
    Set<Range> expectedRanges = Sets.newHashSet(range1, range2);
    
    RangeStream rangeStream = new RangeStream(config, new ScannerFactory(config.getConnector()), helper);
    for (QueryPlan queryPlan : rangeStream.streamPlans(script)) {
        for (Range range : queryPlan.getRanges()) {
            assertTrue("Tried to remove unexpected range " + range.toString() + " from expected ranges: " + expectedRanges.toString(),
                            expectedRanges.remove(range));
        }
    }
    assertTrue("Expected ranges not found in query plan: " + expectedRanges.toString(), expectedRanges.isEmpty());
}
 
Example #22
Source File: MemoryPerUserWaveViewHandlerImpl.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Inject
public MemoryPerUserWaveViewHandlerImpl(final WaveMap waveMap) {
  // Let the view expire if it not accessed for some time.
  explicitPerUserWaveViews =
      CacheBuilder.newBuilder().expireAfterAccess(PER_USER_WAVES_VIEW_CACHE_MINUTES, TimeUnit.MINUTES)
          .<ParticipantId, Multimap<WaveId, WaveletId>>build(new CacheLoader<ParticipantId, Multimap<WaveId, WaveletId>>() {

            @Override
            public Multimap<WaveId, WaveletId> load(final ParticipantId user) {
              Multimap<WaveId, WaveletId> userView = HashMultimap.create();

              // Create initial per user waves view by looping over all waves
              // in the waves store.
              Map<WaveId, Wave> waves = waveMap.getWaves();
              for (Map.Entry<WaveId, Wave> entry : waves.entrySet()) {
                Wave wave = entry.getValue();
                for (WaveletContainer c : wave) {
                  WaveletId waveletId = c.getWaveletName().waveletId;
                  try {
                    if (!c.hasParticipant(user)) {
                      continue;
                    }
                    // Add this wave to the user view.
                    userView.put(entry.getKey(), waveletId);
                  } catch (WaveletStateException e) {
                    LOG.warning("Failed to access wavelet " + c.getWaveletName(), e);
                  }
                }
              }
              LOG.info("Initalized waves view for user: " + user.getAddress()
                  + ", number of waves in view: " + userView.size());
              return userView;
            }
          });
}
 
Example #23
Source File: EntsoeCaseRepository.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Set<DateTime> dataAvailable(CaseType type, Set<Country> countries, Interval interval) {
    Set<EntsoeGeographicalCode> geographicalCodes = new HashSet<>();
    if (countries == null) {
        geographicalCodes.add(EntsoeGeographicalCode.UX);
    } else {
        for (Country country : countries) {
            geographicalCodes.addAll(forCountryHacked(country));
        }
    }
    Multimap<DateTime, EntsoeGeographicalCode> dates = HashMultimap.create();
    for (EntsoeFormat format : formats) {
        Path formatDir = config.getRootDir().resolve(format.getDirName());
        if (Files.exists(formatDir)) {
            Path typeDir = formatDir.resolve(type.name());
            if (Files.exists(typeDir)) {
                browse(typeDir, path -> {
                    EntsoeFileName entsoeFileName = EntsoeFileName.parse(path.getFileName().toString());
                    EntsoeGeographicalCode geographicalCode = entsoeFileName.getGeographicalCode();
                    if (geographicalCode != null
                            && !config.getForbiddenFormatsByGeographicalCode().get(geographicalCode).contains(format.getImporter().getFormat())
                            && interval.contains(entsoeFileName.getDate())) {
                        dates.put(entsoeFileName.getDate(), geographicalCode);
                    }
                });
            }
        }
    }
    return dates.asMap().entrySet().stream()
            .filter(e -> new HashSet<>(e.getValue()).containsAll(geographicalCodes))
            .map(Map.Entry::getKey)
            .collect(Collectors.toCollection(TreeSet::new));
}
 
Example #24
Source File: GeoSortedQueryDataTest.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
public Multimap<String,NormalizedContentInterface> getEventFields(RawRecordContainer record) {
    Multimap<String,NormalizedContentInterface> eventFields = HashMultimap.create();
    NormalizedContentInterface nci = new BaseNormalizedContent();
    nci.setFieldName(FIELD_NAME);
    nci.setEventFieldValue(new String(record.getRawData()));
    nci.setIndexedFieldValue(new String(record.getRawData()));
    eventFields.put(FIELD_NAME, nci);
    return normalizeMap(eventFields);
}
 
Example #25
Source File: CommonUtilsTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the query 1.
 *
 * @throws Exception the exception
 */
@Test
public void buildQuery1() throws Exception {
	Map<String, Object> json = Maps.newHashMap();
	HashMultimap<String, Object> shouldFilter = HashMultimap.create();
	final CommonUtils classUnderTest = PowerMockito.spy(new CommonUtils());
	Whitebox.invokeMethod(classUnderTest, "buildQuery", json, json, shouldFilter);
}
 
Example #26
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 #27
Source File: BaseIngestHelper.java    From datawave with Apache License 2.0 5 votes vote down vote up
private void compilePatterns() {
    Multimap<Matcher,datawave.data.type.Type<?>> patterns = HashMultimap.create();
    if (typePatternMap != null) {
        for (String pattern : typePatternMap.keySet()) {
            patterns.putAll(compileFieldNamePattern(pattern), typePatternMap.get(pattern));
        }
    }
    typeCompiledPatternMap = patterns;
}
 
Example #28
Source File: VpcCfgReconstruction.java    From jakstab with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fold ART into a map from VPC locations to sets of abstract states, and
 * then flatten the state sets into single abstract states by joining.
 * 
 * @return a map from VPC locations to the join of all abstract states at 
 * that VPC location
 */
private Map<Location, AbstractState> flattenArtOntoVpcLocations() {

	SetMultimap<Location, AbstractState> vpcSensitiveReached = HashMultimap.create();
	
	Deque<AbstractState> worklist = new LinkedList<AbstractState>();
	worklist.add(art.getRoot());
	Set<AbstractState> visited = new HashSet<AbstractState>();
	visited.add(art.getRoot());
	
	while (!worklist.isEmpty()) {
		AbstractState headState = worklist.removeFirst();
		if (isVpcStateBot(headState))
			continue;
		
		BasedNumberElement vpcVal = getVPC(headState);
		VpcLocation headVpcLoc = new VpcLocation(vpcVal, (RTLLabel)headState.getLocation());

		vpcSensitiveReached.put(headVpcLoc, headState);

		Set<Pair<CFAEdge, AbstractState>> successors = art.getChildren(headState);
		for (Pair<CFAEdge, AbstractState> sPair : successors) {
			AbstractState nextState = sPair.getRight();
			
			if (!visited.contains(nextState)) {
				visited.add(nextState);
				worklist.add(nextState);
			}
		}
	}
	
	Map<Location, AbstractState> constants = new HashMap<Location, AbstractState>();
	for (Location l : vpcSensitiveReached.keySet()) {
		constants.put(l, Lattices.joinAll(vpcSensitiveReached.get(l)));
	}
	
	return constants;
}
 
Example #29
Source File: CypherUtilTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void substituteSingleRelationship() {
  Multimap<String, Object> valueMap = HashMultimap.create();
  valueMap.put("node_id", "HP_123");
  valueMap.put("rel_id", "RO_1");
  String actual = util.substituteRelationships("({node_id})-[:${rel_id}!]-(end)", valueMap);
  assertThat(actual, is("({node_id})-[:RO_1!]-(end)"));
}
 
Example #30
Source File: SubscriberRegistry.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns all subscribers for the given listener grouped by the type of event they subscribe to.
 */
private Multimap<Class<?>, Subscriber> findAllSubscribers(Object listener) {
  Multimap<Class<?>, Subscriber> methodsInListener = HashMultimap.create();
  Class<?> clazz = listener.getClass();
  for (Method method : getAnnotatedMethods(clazz)) {
    Class<?>[] parameterTypes = method.getParameterTypes();
    Class<?> eventType = parameterTypes[0];
    methodsInListener.put(eventType, Subscriber.create(bus, listener, method));
  }
  return methodsInListener;
}