Java Code Examples for com.google.common.collect.LinkedHashMultimap

The following examples show how to use com.google.common.collect.LinkedHashMultimap. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Test
public void testMethodUriBodyWithAnyBoundaryMatchForDifferentMethods()
    throws Exception {
  Multimap<String, String> headers = LinkedHashMultimap.create();
  headers.put("key1", "value1");
  headers.put("Content-Type", "multipart/form-data; boundary=wxyz1234abcd5e");

  RecordedHttpBody body = new RecordedStringHttpBody("------wxyz1234abcd5e\nContent-Disposition: form-data; name=\"org\" \ngoogle\n------wxyz1234abcd5e");
  RecordedHttpRequest recordedHttpRequest1 =
      new RecordedHttpRequest("POST", new URI("http://www.google.com/"), headers, body);
  RecordedHttpRequest recordedHttpRequest2 =
      new RecordedHttpRequest("PUT", new URI("http://www.google.com/"), headers, body);

  MatchRule matchRule = MatchRuleUtils.matchMethodUriBodyWithAnyBoundary();

  Assert.assertFalse(matchRule.test(recordedHttpRequest1, recordedHttpRequest2));
  Assert.assertTrue(matchRule.getMatchFailureDescriptionForRequests(recordedHttpRequest1, recordedHttpRequest2).contains("HTTP Method Mismatch"));
}
 
Example 2
Source Project: buck   Source File: TargetSpecResolver.java    License: Apache License 2.0 6 votes vote down vote up
private ImmutableList<ImmutableSet<BuildTarget>> collectTargets(
    int specsCount,
    List<ListenableFuture<Entry<Integer, ImmutableSet<BuildTarget>>>> targetFutures)
    throws InterruptedException {
  // Walk through and resolve all the futures, and place their results in a multimap that
  // is indexed by the integer representing the input target spec order.
  LinkedHashMultimap<Integer, BuildTarget> targetsMap = LinkedHashMultimap.create();
  try {
    for (ListenableFuture<Map.Entry<Integer, ImmutableSet<BuildTarget>>> targetFuture :
        targetFutures) {
      Map.Entry<Integer, ImmutableSet<BuildTarget>> result = targetFuture.get();
      targetsMap.putAll(result.getKey(), result.getValue());
    }
  } catch (ExecutionException e) {
    MoreThrowables.throwIfAnyCauseInstanceOf(e, InterruptedException.class);
    HumanReadableExceptions.throwIfHumanReadableUnchecked(e.getCause());
    throw new RuntimeException(e);
  }
  // Finally, pull out the final build target results in input target spec order, and place them
  // into a list of sets that exactly matches the ihput order.
  ImmutableList.Builder<ImmutableSet<BuildTarget>> targets = ImmutableList.builder();
  for (int index = 0; index < specsCount; index++) {
    targets.add(ImmutableSet.copyOf(targetsMap.get(index)));
  }
  return targets.build();
}
 
Example 3
Source Project: swellrt   Source File: AbstractSearchProviderImpl.java    License: Apache License 2.0 6 votes vote down vote up
protected LinkedHashMap<WaveId, WaveViewData> filterWavesViewBySearchCriteria(
    Function<ReadableWaveletData, Boolean> matchesFunction,
    LinkedHashMultimap<WaveId, WaveletId> currentUserWavesView) {
  // Must use a map with stable ordering, since indices are meaningful.
  LinkedHashMap<WaveId, WaveViewData> results = Maps.newLinkedHashMap();

  // Loop over the user waves view.
  for (WaveId waveId : currentUserWavesView.keySet()) {
    Set<WaveletId> waveletIds = currentUserWavesView.get(waveId);
    WaveViewData view = buildWaveViewData(waveId, waveletIds, matchesFunction, waveMap);
    Iterable<? extends ObservableWaveletData> wavelets = view.getWavelets();
    boolean hasConversation = false;
    for (ObservableWaveletData waveletData : wavelets) {
      if (IdUtil.isConversationalId(waveletData.getWaveletId())) {
        hasConversation = true;
        break;
      }
    }
    if ((view != null) && hasConversation) {
      results.put(waveId, view);
    }
  }
  return results;
}
 
Example 4
@Test
public void testMethodUriBodyWithAnyBoundaryMatch()
    throws Exception {
  Multimap<String, String> headers = LinkedHashMultimap.create();
  headers.put("key1", "value1");
  headers.put("Content-Type", "multipart/form-data; boundary=wxyz1234abcd5e");

  RecordedHttpBody body = new RecordedStringHttpBody("------wxyz1234abcd5e\nContent-Disposition: form-data; name=\"org\" \ngoogle\n------wxyz1234abcd5e");
  RecordedHttpRequest recordedHttpRequest1 =
      new RecordedHttpRequest("POST", new URI("http://www.google.com/"), headers, body);
  RecordedHttpRequest recordedHttpRequest2 =
      new RecordedHttpRequest("POST", new URI("http://www.google.com/"), headers, body);

  MatchRule matchRule = MatchRuleUtils.matchMethodUriBodyWithAnyBoundary();
  Assert.assertTrue(matchRule.test(recordedHttpRequest1, recordedHttpRequest2));
}
 
Example 5
Source Project: datawave   Source File: ExpandCompositeTerms.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * The default leaf node visitor, which uses the anded nodes to determine whether a composite can be formed with this leaf node.
 *
 * @param node
 *            A leaf node from the original script
 * @param eData
 *            ExpandData, containing ancestor anded nodes, used anded nodes, and a flag indicating whether composites were found
 * @return Returns a composite node if one can be made, otherwise returns the original node
 */
private JexlNode visitLeafNode(JexlNode node, ExpandData eData) {
    String fieldName = (node instanceof ASTAndNode) ? JexlASTHelper.getIdentifier(node.jjtGetChild(0)) : JexlASTHelper.getIdentifier(node);
    
    Multimap<String,JexlNode> leafNodes = LinkedHashMultimap.create();
    leafNodes.put(fieldName, node);
    
    List<Composite> foundComposites = findComposites(leafNodes, eData.andedNodes, eData.usedAndedNodes);
    
    JexlNode resultNode = node;
    
    // if composites were found, create JexlNodes from them
    if (!foundComposites.isEmpty()) {
        List<JexlNode> compositeNodes = createCompositeNodes(foundComposites);
        
        if (!compositeNodes.isEmpty()) {
            eData.foundComposite = true;
            resultNode = createUnwrappedAndNode(compositeNodes);
        }
    }
    
    return resultNode;
}
 
Example 6
Source Project: datawave   Source File: ExpandCompositeTerms.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Using the leaf nodes and anded nodes passed in, attempts to create composites from those nodes. The generated composites are required to contain at least
 * one of the leaf nodes.
 *
 * @param leafNodes
 *            A multimap of leaf child nodes, keyed by field name, from the parent node
 * @param andedNodes
 *            A multimap of anded nodes, keyed by field name, passed down from our ancestors
 * @param usedLeafNodes
 *            A multimap of used leaf child nodes, keyed by field name, used to create the returned composites
 * @param usedAndedNodes
 *            A multimap of used anded nodes, keyed by field name, used to create the returned composites
 * @return A list of composites which can be created from the given leaf and anded nodes
 */
private List<Composite> findComposites(Multimap<String,JexlNode> leafNodes, Multimap<String,JexlNode> andedNodes, Multimap<String,JexlNode> usedLeafNodes,
                Multimap<String,JexlNode> usedAndedNodes) {
    
    // determine what composites can be made with these fields
    Multimap<String,String> filteredCompositeToFieldMap = getFilteredCompositeToFieldMap(leafNodes.keySet(), andedNodes.keySet());
    
    // TODO: Update this to use some kind of cardinality-based heuristic to sort the composites
    // order the composite to field map in order of preference
    filteredCompositeToFieldMap = orderByCollectionSize(filteredCompositeToFieldMap);
    
    // for each of the required fields, if is is an overloaded composite field,
    // we may need to create or tweak the leaf node's range, so we add a self-mapping
    Multimap<String,String> overloadedCompositeMap = LinkedHashMultimap.create();
    for (String requiredField : leafNodes.keySet())
        if (CompositeIngest.isOverloadedCompositeField(config.getCompositeToFieldMap(), requiredField))
            overloadedCompositeMap.put(requiredField, requiredField);
    
    // Add overloaded composite entries to the set of entries
    List<Entry<String,Collection<String>>> compositeFieldMapList = new ArrayList<>(filteredCompositeToFieldMap.asMap().entrySet());
    compositeFieldMapList.addAll(overloadedCompositeMap.asMap().entrySet());
    return findComposites(compositeFieldMapList, leafNodes, andedNodes, usedLeafNodes, usedAndedNodes);
}
 
Example 7
public Collection<IdeExtendedRepoFileDependency> extractRepoFileDependencies(DependencyHandler dependencyHandler, Collection<Configuration> plusConfigurations, Collection<Configuration> minusConfigurations, boolean downloadSources, boolean downloadJavadoc) {
    // can have multiple IDE dependencies with same component identifier (see GRADLE-1622)
    Multimap<ComponentIdentifier, IdeExtendedRepoFileDependency> resolvedDependenciesComponentMap = LinkedHashMultimap.create();
    for (IdeExtendedRepoFileDependency dep : resolvedExternalDependencies(plusConfigurations, minusConfigurations)) {
        resolvedDependenciesComponentMap.put(toComponentIdentifier(dep.getId()), dep);
    }

    List<Class<? extends Artifact>> artifactTypes = new ArrayList<Class<? extends Artifact>>(2);
    if (downloadSources) {
        artifactTypes.add(SourcesArtifact.class);
    }

    if (downloadJavadoc) {
        artifactTypes.add(JavadocArtifact.class);
    }

    downloadAuxiliaryArtifacts(dependencyHandler, resolvedDependenciesComponentMap, artifactTypes);

    Collection<UnresolvedIdeRepoFileDependency> unresolvedDependencies = unresolvedExternalDependencies(plusConfigurations, minusConfigurations);
    Collection<IdeExtendedRepoFileDependency> resolvedDependencies = resolvedDependenciesComponentMap.values();

    Collection<IdeExtendedRepoFileDependency> resolvedAndUnresolved = new ArrayList<IdeExtendedRepoFileDependency>(unresolvedDependencies.size() + resolvedDependencies.size());
    resolvedAndUnresolved.addAll(resolvedDependencies);
    resolvedAndUnresolved.addAll(unresolvedDependencies);
    return resolvedAndUnresolved;
}
 
Example 8
Source Project: bazel   Source File: ResourceSymbols.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Loads the SymbolTables from a list of SymbolFileProviders.
 *
 * @param dependencies The full set of library symbols to load.
 * @param executor The executor use during loading.
 * @param packageToExclude A string package to elide if it exists in the providers.
 * @return A list of loading {@link ResourceSymbols} instances.
 * @throws ExecutionException
 * @throws InterruptedException when there is an error loading the symbols.
 */
public static Multimap<String, ListenableFuture<ResourceSymbols>> loadFrom(
    Iterable<? extends SymbolFileProvider> dependencies,
    ListeningExecutorService executor,
    @Nullable String packageToExclude)
    throws InterruptedException, ExecutionException {
  Map<SymbolFileProvider, ListenableFuture<String>> providerToPackage = new LinkedHashMap<>();
  for (SymbolFileProvider dependency : dependencies) {
    providerToPackage.put(
        dependency, executor.submit(new PackageParsingTask(dependency.getManifest())));
  }
  Multimap<String, ListenableFuture<ResourceSymbols>> packageToTable =
      LinkedHashMultimap.create();
  for (Map.Entry<SymbolFileProvider, ListenableFuture<String>> entry :
      providerToPackage.entrySet()) {
    File symbolFile = entry.getKey().getSymbolFile();
    if (!Objects.equals(entry.getValue().get(), packageToExclude)) {
      packageToTable.put(entry.getValue().get(), load(symbolFile.toPath(), executor));
    }
  }
  return packageToTable;
}
 
Example 9
Source Project: raml-java-tools   Source File: PluginManager.java    License: Apache License 2.0 6 votes vote down vote up
public static PluginManager createPluginManager(String pluginFileName) {

    try {
      SetMultimap<String, Class<?>> info = LinkedHashMultimap.create();
      Enumeration<URL> resourcesFiles = PluginManager.class.getClassLoader().getResources(pluginFileName);

      while (resourcesFiles.hasMoreElements()) {
        URL url = resourcesFiles.nextElement();
        Properties properties = new Properties();
        loadProperties(url, properties);
        buildPluginNames(info, properties);
      }

      return new PluginManager(info);

    } catch (IOException e) {

      throw new GenerationException(e);
    }

  }
 
Example 10
Source Project: NullAway   Source File: NullAway.java    License: MIT License 6 votes vote down vote up
/**
 * @param entities field init info
 * @param state visitor state
 * @return a map from each constructor C to the nonnull fields that C does *not* initialize
 */
private SetMultimap<MethodTree, Symbol> checkConstructorInitialization(
    FieldInitEntities entities, VisitorState state) {
  SetMultimap<MethodTree, Symbol> result = LinkedHashMultimap.create();
  Set<Symbol> nonnullInstanceFields = entities.nonnullInstanceFields();
  Trees trees = getTreesInstance(state);
  boolean isExternalInit = isExternalInit(entities.classSymbol());
  for (MethodTree constructor : entities.constructors()) {
    if (constructorInvokesAnother(constructor, state)) {
      continue;
    }
    if (constructor.getParameters().size() == 0 && isExternalInit) {
      // external framework initializes fields in this case
      continue;
    }
    Set<Element> guaranteedNonNull =
        guaranteedNonNullForConstructor(entities, state, trees, constructor);
    for (Symbol fieldSymbol : nonnullInstanceFields) {
      if (!guaranteedNonNull.contains(fieldSymbol)) {
        result.put(constructor, fieldSymbol);
      }
    }
  }
  return result;
}
 
Example 11
Source Project: j2cl   Source File: TypeDeclaration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds and caches a mapping from method override signature to matching method descriptors from
 * the entire super-type hierarchy. This map can *greatly* speed up method override checks.
 */
@Memoized
Multimap<String, MethodDescriptor> getMethodDescriptorsByOverrideSignature() {
  Multimap<String, MethodDescriptor> methodDescriptorsByOverrideSignature =
      LinkedHashMultimap.create();

  for (MethodDescriptor declaredMethodDescriptor : getDeclaredMethodDescriptors()) {
    if (declaredMethodDescriptor.isPolymorphic()) {
      methodDescriptorsByOverrideSignature.put(
          declaredMethodDescriptor.getOverrideSignature(), declaredMethodDescriptor);
    }
  }

  // Recurse into immediate super class and interfaces for overridden method.
  if (getSuperTypeDeclaration() != null) {
    methodDescriptorsByOverrideSignature.putAll(
        getSuperTypeDeclaration().getMethodDescriptorsByOverrideSignature());
  }

  for (DeclaredTypeDescriptor interfaceTypeDescriptor : getInterfaceTypeDescriptors()) {
    methodDescriptorsByOverrideSignature.putAll(
        interfaceTypeDescriptor.getTypeDeclaration().getMethodDescriptorsByOverrideSignature());
  }

  return methodDescriptorsByOverrideSignature;
}
 
Example 12
Source Project: j2cl   Source File: JsInteropRestrictionsChecker.java    License: Apache License 2.0 6 votes vote down vote up
private static Multimap<String, MemberDescriptor> collectInstanceNames(
    DeclaredTypeDescriptor typeDescriptor) {
  if (typeDescriptor == null) {
    return LinkedHashMultimap.create();
  }

  // The supertype of an interface is java.lang.Object. java.lang.Object methods need to be
  // considered when checking for name collisions.
  // TODO(b/135140069): remove if the model starts including java.lang.Object as the supertype of
  // interfaces.
  DeclaredTypeDescriptor superTypeDescriptor =
      typeDescriptor.isInterface() && !typeDescriptor.isNative()
          ? TypeDescriptors.get().javaLangObject
          : typeDescriptor.getSuperTypeDescriptor();
  Multimap<String, MemberDescriptor> instanceMembersByName =
      collectInstanceNames(superTypeDescriptor);
  for (MemberDescriptor member : typeDescriptor.getDeclaredMemberDescriptors()) {
    if (isInstanceJsMember(member)) {
      addMember(instanceMembersByName, member);
    }
  }
  return instanceMembersByName;
}
 
Example 13
@Test
public void testHeaderBlacklistMatchEmptyBL()
    throws Exception {
  Multimap<String, String> headers1 = LinkedHashMultimap.create();
  headers1.put("key1", "value1");
  headers1.put("key2", "value2");
  RecordedHttpRequest recordedHttpRequest1 = new RecordedHttpRequest(null, null, headers1, null);

  Multimap<String, String> headers2 = LinkedHashMultimap.create();
  headers2.put("key1", "value1");
  headers2.put("key2", "value2");
  RecordedHttpRequest recordedHttpRequest2 = new RecordedHttpRequest(null, null, headers2, null);

  Set<String> blList = new HashSet<>();
  MatchRule matchRule = MatchRuleUtils.matchHeadersWithBlacklist(blList);

  Assert.assertTrue(matchRule.test(recordedHttpRequest1, recordedHttpRequest2));
}
 
Example 14
protected LightweightTypeReference doGetCommonSuperType(List<LightweightTypeReference> types) {
	LightweightTypeReference firstType = types.get(0);
	final List<LightweightTypeReference> tail = types.subList(1, types.size());
	// mapping from rawtype to resolved parameterized types
	// used to determine the correct type arguments
	Multimap<JvmType, LightweightTypeReference> all = LinkedHashMultimap.create();
	// cumulated rawtype to max distance (used for sorting)
	Multiset<JvmType> cumulatedDistance = LinkedHashMultiset.create();
	
	initializeDistance(firstType, all, cumulatedDistance);
	cumulateDistance(tail, all, cumulatedDistance);
	
	List<Entry<JvmType>> candidates = Lists.newArrayList(cumulatedDistance.entrySet());
	if (candidates.size() == 1) { // only one super type -> should be java.lang.Object
		JvmType firstRawType = candidates.get(0).getElement();
		return getFirstForRawType(all, firstRawType);
	}
	inplaceSortByDistanceAndName(candidates);
	List<LightweightTypeReference> referencesWithSameDistance = getMostSpecialCandidates(types, all, candidates);
	return wrapInCompoundTypeIfNecessary(referencesWithSameDistance);
}
 
Example 15
@Test
public void testHeaderBlacklistMatch()
    throws Exception {
  Multimap<String, String> headers1 = LinkedHashMultimap.create();
  headers1.put("key2", "value2");
  headers1.put("key3", "value3");
  RecordedHttpRequest recordedHttpRequest1 = new RecordedHttpRequest(null, null, headers1, null);

  Multimap<String, String> headers2 = LinkedHashMultimap.create();
  headers2.put("key1", "value1");
  headers2.put("key2", "value2");
  headers2.put("key3", "value3");
  RecordedHttpRequest recordedHttpRequest2 = new RecordedHttpRequest(null, null, headers2, null);

  Set<String> blList = new HashSet<>();
  blList.add("key1");

  MatchRule matchRule = MatchRuleUtils.matchHeadersWithBlacklist(blList);

  Assert.assertTrue(matchRule.test(recordedHttpRequest1, recordedHttpRequest2));
}
 
Example 16
public String getJavaStubSource(IEObjectDescription description, IResourceDescription resourceDescription) {
	if(isNestedType(description) || !isJvmDeclaredType(description)) {
		return null;
	}
	Multimap<QualifiedName, IEObjectDescription> owner2nested = LinkedHashMultimap.create();
	for(IEObjectDescription other: resourceDescription.getExportedObjects()) {
		if(isJvmDeclaredType(other) && isNestedType(other))
			owner2nested.put(getOwnerClassName(other.getQualifiedName()), other);
	}
	StringBuilder classSignatureBuilder = new StringBuilder();
	QualifiedName qualifiedName = description.getQualifiedName();
	if (qualifiedName.getSegments().size() > 1) {
		String string = qualifiedName.toString();
		classSignatureBuilder.append("package " + string.substring(0, string.lastIndexOf('.')) + ";");
	}
	appendType(description, owner2nested, classSignatureBuilder);
	return classSignatureBuilder.toString();
}
 
Example 17
Source Project: timely   Source File: TimelyUser.java    License: Apache License 2.0 6 votes vote down vote up
@JsonCreator
public TimelyUser(@JsonProperty(value = "dn", required = true) SubjectIssuerDNPair dn,
        @JsonProperty(value = "userType", required = true) UserType userType,
        @JsonProperty("auths") Collection<String> auths, @JsonProperty("roles") Collection<String> roles,
        @JsonProperty("roleToAuthMapping") Multimap<String, String> roleToAuthMapping,
        @JsonProperty(value = "creationTime", defaultValue = "-1L") long creationTime,
        @JsonProperty(value = "expirationTime", defaultValue = "-1L") long expirationTime) {
    this.name = dn.toString();
    this.commonName = DnUtils.getCommonName(dn.subjectDN());
    this.dn = dn;
    this.userType = userType;
    this.auths = auths == null ? Collections.emptyList() : new LinkedHashSet<>(auths);
    this.unmodifiableAuths = Collections.unmodifiableCollection(this.auths);
    this.roles = roles == null ? Collections.emptyList() : new LinkedHashSet<>(roles);
    this.unmodifiableRoles = Collections.unmodifiableCollection(this.roles);
    this.roleToAuthMapping = roleToAuthMapping == null ? LinkedHashMultimap.create()
            : Multimaps.unmodifiableMultimap(LinkedHashMultimap.create(roleToAuthMapping));
    this.creationTime = creationTime;
    this.expirationTime = expirationTime;
}
 
Example 18
Source Project: flashback   Source File: MatchHeadersTest.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testMatchDifferentOrder()
    throws Exception {
  Multimap<String, String> headers1 = LinkedHashMultimap.create();
  headers1.put("key1", "value1");
  headers1.put("key2", "value2");
  RecordedHttpRequest recordedHttpRequest1 = new RecordedHttpRequest(null, null, headers1, null);

  Multimap<String, String> headers2 = LinkedHashMultimap.create();
  headers2.put("key2", "value2");
  headers2.put("key1", "value1");
  RecordedHttpRequest recordedHttpRequest2 = new RecordedHttpRequest(null, null, headers2, null);
  MatchRule matchRule = new MatchHeaders();

  Assert.assertTrue(matchRule.test(recordedHttpRequest1, recordedHttpRequest2));
}
 
Example 19
@Before
public void setUp() throws SQLException {
    dataSourceMap.put(DATA_SOURCE_NAME, dataSource);
    when(dataSource.getConnection()).thenReturn(connection);
    when(connection.getMetaData()).thenReturn(databaseMetaData);
    when(resultSet.getMetaData()).thenReturn(mock(ResultSetMetaData.class));
    CachedDatabaseMetaData cachedDatabaseMetaData = new CachedDatabaseMetaData(databaseMetaData);
    when(shardingSphereConnection.getCachedConnections()).thenReturn(LinkedHashMultimap.create());
    when(shardingSphereConnection.getConnection(anyString())).thenReturn(connection);
    when(shardingSphereConnection.getDataSourceMap()).thenReturn(dataSourceMap);
    when(shardingSphereConnection.getSchemaContexts()).thenReturn(schemaContexts);
    SchemaContext schemaContext = mock(SchemaContext.class);
    ShardingSphereSchema schema = mock(ShardingSphereSchema.class);
    RuntimeContext runtimeContext = mock(RuntimeContext.class);
    when(schemaContexts.getDefaultSchemaContext()).thenReturn(schemaContext);
    when(schemaContext.getSchema()).thenReturn(schema);
    when(schemaContext.getRuntimeContext()).thenReturn(runtimeContext);
    when(runtimeContext.getCachedDatabaseMetaData()).thenReturn(cachedDatabaseMetaData);
    when(schema.getRules()).thenReturn(Collections.singletonList(mockShardingRule()));
    shardingSphereDatabaseMetaData = new ShardingSphereDatabaseMetaData(shardingSphereConnection);
}
 
Example 20
Source Project: xtext-core   Source File: ImportScope.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected Iterable<IEObjectDescription> getAliasedElements(Iterable<IEObjectDescription> candidates) {
	Multimap<QualifiedName, IEObjectDescription> keyToDescription = LinkedHashMultimap.create();
	Multimap<QualifiedName, ImportNormalizer> keyToNormalizer = HashMultimap.create();

	for (IEObjectDescription imported : candidates) {
		QualifiedName fullyQualifiedName = imported.getName();
		for (ImportNormalizer normalizer : normalizers) {
			QualifiedName alias = normalizer.deresolve(fullyQualifiedName);
			if (alias != null) {
				QualifiedName key = alias;
				if (isIgnoreCase()) {
					key = key.toLowerCase();
				}
				keyToDescription.put(key, new AliasedEObjectDescription(alias, imported));
				keyToNormalizer.put(key, normalizer);
			}
		}
	}
	for (QualifiedName name : keyToNormalizer.keySet()) {
		if (keyToNormalizer.get(name).size() > 1)
			keyToDescription.removeAll(name);
	}
	return keyToDescription.values();
}
 
Example 21
Source Project: swagger2markup   Source File: TagUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Groups the operations by tag. The key of the Multimap is the tag name.
 * The value of the Multimap is a PathOperation
 *
 * @param allOperations     all operations
 * @param operationOrdering comparator for operations, for a given tag
 * @return Operations grouped by Tag
 */
public static Multimap<String, SwaggerPathOperation> groupOperationsByTag(List<SwaggerPathOperation> allOperations, Comparator<PathOperation> operationOrdering) {

    Multimap<String, SwaggerPathOperation> operationsGroupedByTag;
    if (operationOrdering == null) {
        operationsGroupedByTag = LinkedHashMultimap.create();
    } else {
        operationsGroupedByTag = MultimapBuilder.linkedHashKeys().treeSetValues(operationOrdering).build();
    }
    for (SwaggerPathOperation operation : allOperations) {
        List<String> tags = operation.getOperation().getTags();

        Validate.notEmpty(tags, "Can't GroupBy.TAGS. Operation '%s' has no tags", operation);
        for (String tag : tags) {
            if (logger.isDebugEnabled()) {
                logger.debug("Added path operation '{}' to tag '{}'", operation, tag);
            }
            operationsGroupedByTag.put(tag, operation);
        }
    }

    return operationsGroupedByTag;
}
 
Example 22
@Test
public void testMethodUriBodyWithAnyBoundaryMatchForDifferentUri()
    throws Exception {
  Multimap<String, String> headers = LinkedHashMultimap.create();
  headers.put("key1", "value1");
  headers.put("Content-Type", "multipart/form-data; boundary=wxyz1234abcd5e");

  RecordedHttpBody body = new RecordedStringHttpBody("------wxyz1234abcd5e\nContent-Disposition: form-data; name=\"org\" \ngoogle\n------wxyz1234abcd5e");
  RecordedHttpRequest recordedHttpRequest1 =
      new RecordedHttpRequest("POST", new URI("http://www.linkedin.com/"), headers, body);
  RecordedHttpRequest recordedHttpRequest2 =
      new RecordedHttpRequest("POST", new URI("http://www.google.com/"), headers, body);

  MatchRule matchRule = MatchRuleUtils.matchMethodUriBodyWithAnyBoundary();

  Assert.assertFalse(matchRule.test(recordedHttpRequest1, recordedHttpRequest2));
  Assert.assertTrue(matchRule.getMatchFailureDescriptionForRequests(recordedHttpRequest1, recordedHttpRequest2).contains("URI Mismatch"));
}
 
Example 23
private Multimap<String, String> createHeaders()
    throws IOException {
  if (!isValidOptionalField(SceneSerializationConstant.SCENE_TAG_HTTPHEADERS)) {
    return null;
  }
  skipStartObject();  // HTTPHEADERS

  Multimap<String, String> headers = LinkedHashMultimap.create();
  while (_jsonParser.nextToken() != JsonToken.END_OBJECT) {   //FIELD_NAME
    String key = _jsonParser.getCurrentName();
    _jsonParser.nextToken();   // VALUE_STRING
    String value = _jsonParser.getValueAsString();
    headers.put(key, value);
  }
  if (SceneSerializationConstant.SCENE_TAG_HTTPHEADERS.equals(_jsonParser.getCurrentName())
      && _jsonParser.getCurrentToken() == JsonToken.END_OBJECT) {
    skipEndObject();
  }
  return headers;
}
 
Example 24
Source Project: calcite   Source File: JethroDataSqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
private JethroInfo makeInfo(Connection jethroConnection) {
  try (Statement jethroStatement = jethroConnection.createStatement();
       ResultSet functionsTupleSet =
           jethroStatement.executeQuery("show functions extended")) {
    final Multimap<String, JethroSupportedFunction> supportedFunctions =
        LinkedHashMultimap.create();
    while (functionsTupleSet.next()) {
      String functionName = functionsTupleSet.getString(1);
      String operandsType = functionsTupleSet.getString(3);
      supportedFunctions.put(functionName,
          new JethroSupportedFunction(functionName, operandsType));
    }
    return new JethroInfo(supportedFunctions);
  } catch (Exception e) {
    final String msg =
        "Jethro server failed to execute 'show functions extended'";
    LOGGER.error(msg, e);
    throw new RuntimeException(msg
        + "; make sure your Jethro server is up to date", e);
  }
}
 
Example 25
@Test
public void testEntireRequestMatch()
    throws Exception {

  Multimap<String, String> headers = LinkedHashMultimap.create();
  headers.put("key1", "value1");
  headers.put("key2", "value2");

  RecordedHttpBody body = new RecordedStringHttpBody("body");
  RecordedHttpRequest recordedHttpRequest1 =
      new RecordedHttpRequest("POST", new URI("http://www.google.com/"), headers, body);
  RecordedHttpRequest recordedHttpRequest2 =
      new RecordedHttpRequest("POST", new URI("http://www.google.com/"), headers, body);

  MatchRule entireRequestRule = MatchRuleUtils.matchEntireRequest();
  MatchRule methodUriRule = MatchRuleUtils.matchMethodUri();

  Assert.assertTrue(entireRequestRule.test(recordedHttpRequest1, recordedHttpRequest2));
  Assert.assertTrue(methodUriRule.test(recordedHttpRequest1, recordedHttpRequest2));
}
 
Example 26
Source Project: brooklyn-server   Source File: BundleUpgradeParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testParseKeyEqualsValueWildcardsAndDefault() throws Exception {
    String input = "foo, foo:9-bogus, *, *:8, \"*:[9-bogus,9-bogut)=foo9:10.bogus\"";
    Multimap<VersionedName, VersionRangedName> expected = LinkedHashMultimap.create();
    expected.putAll(new VersionedName("foo", DEFAULT_TARGET_VERSION),
        MutableList.of(
            VersionRangedName.fromString("foo:"+DEFAULT_WILDCARD_VERSION_RANGE, false),
            VersionRangedName.fromString("foo:"+"9-bogus", false)
        ));
    expected.putAll(new VersionedName(DEFAULT_WILDCARD_NAME, DEFAULT_TARGET_VERSION),
        MutableList.of(
            VersionRangedName.fromString(DEFAULT_WILDCARD_NAME+":"+DEFAULT_WILDCARD_VERSION_RANGE, false),
            VersionRangedName.fromString(DEFAULT_WILDCARD_NAME+":8", false)
        ));
    expected.put(new VersionedName("foo9", "10.bogus"),
        VersionRangedName.fromString(DEFAULT_WILDCARD_NAME+":[9-bogus,9-bogut)", false));
    assertParseListVersionRangedNameToVersionedNames(input, expected); 
}
 
Example 27
@Test
public void testDifferentHeaders()
    throws Exception {

  Multimap<String, String> headers1 = LinkedHashMultimap.create();
  headers1.put("key1", "value1");
  headers1.put("key2", "value2");

  Multimap<String, String> headers2 = LinkedHashMultimap.create();
  headers2.put("key1", "value1");
  headers2.put("key3", "value3");

  RecordedHttpRequest recordedHttpRequest1 =
      new RecordedHttpRequest("GET", new URI("http://www.google.com/"), headers1, null);
  RecordedHttpRequest recordedHttpRequest2 =
      new RecordedHttpRequest("GET", new URI("http://www.google.com/"), headers2, null);

  MatchRule entireRequestRule = MatchRuleUtils.matchEntireRequest();
  MatchRule methodUriRule = MatchRuleUtils.matchMethodUri();

  Assert.assertFalse(entireRequestRule.test(recordedHttpRequest1, recordedHttpRequest2));
  Assert.assertTrue(methodUriRule.test(recordedHttpRequest1, recordedHttpRequest2));
  Assert.assertTrue(entireRequestRule.getMatchFailureDescriptionForRequests(recordedHttpRequest1, recordedHttpRequest2).contains("HTTP Headers Mismatch"));
}
 
Example 28
@Test
public void testDifferentURIs()
    throws Exception {

  Multimap<String, String> headers = LinkedHashMultimap.create();
  headers.put("key1", "value1");
  headers.put("key2", "value2");

  RecordedHttpRequest recordedHttpRequest1 =
      new RecordedHttpRequest("GET", new URI("http://www.google.com/"), headers, null);
  RecordedHttpRequest recordedHttpRequest2 =
      new RecordedHttpRequest("GET", new URI("http://www.google.com/foo/"), headers, null);

  MatchRule entireRequestRule = MatchRuleUtils.matchEntireRequest();
  MatchRule methodUriRule = MatchRuleUtils.matchMethodUri();

  Assert.assertFalse(entireRequestRule.test(recordedHttpRequest1, recordedHttpRequest2));
  Assert.assertFalse(methodUriRule.test(recordedHttpRequest1, recordedHttpRequest2));
  Assert.assertTrue(entireRequestRule.getMatchFailureDescriptionForRequests(recordedHttpRequest1, recordedHttpRequest2).contains("URI Mismatch"));
  Assert.assertTrue(entireRequestRule.getMatchFailureDescriptionForRequests(recordedHttpRequest1, recordedHttpRequest2).contains("URI Mismatch"));
}
 
Example 29
public static void main(String[] args) {
    String INPUT_TEXT = "Hello World! Hello All! Hi World!";
    // Parse text to words and index
    List<String> words = Arrays.asList(INPUT_TEXT.split(" "));
    // Create Multimap
    Multimap<String, Integer> multiMap = LinkedHashMultimap.create();

    // Fill Multimap
    int i = 0;
    for(String word: words) {
        multiMap.put(word, i);
        i++;
    }

    // Print all words
    System.out.println(multiMap); // print {Hello=[0, 2], World!=[1, 5], All!=[3], Hi=[4]}-in predictable iteration order
    // Print all unique words
    System.out.println(multiMap.keySet());    // print [Hello, World!, All!, Hi]- in predictable iteration order

    // Print all indexes
    System.out.println("Hello = " + multiMap.get("Hello"));    // print [0, 2]
    System.out.println("World = " + multiMap.get("World!"));    // print [1, 5]
    System.out.println("All = " + multiMap.get("All!"));    // print [3]
    System.out.println("Hi = " + multiMap.get("Hi"));    // print [4]
    System.out.println("Empty = " + multiMap.get("Empty"));    // print []

    // Print count all words
    System.out.println(multiMap.size());    //print 6

    // Print count unique words
    System.out.println(multiMap.keySet().size());    //print 4
}
 
Example 30
public static void main(String[] args) {
    String INPUT_TEXT = "Hello World! Hello All! Hi World!";
    // Разберем текст на слова и индексы
    List<String> words = Arrays.asList(INPUT_TEXT.split(" "));
    // Создаем Multimap
    Multimap<String, Integer> multiMap = LinkedHashMultimap.create();

    // Заполним Multimap
    int i = 0;
    for(String word: words) {
        multiMap.put(word, i);
        i++;
    }

    // Выводим все вхождения слов в текст
    System.out.println(multiMap); // напечатает {Hello=[0, 2], World!=[1, 5], All!=[3], Hi=[4]}-в порядке добавления
    // Выводим все уникальные слова
    System.out.println(multiMap.keySet());    // напечатает [Hello, World!, All!, Hi]- в порядке добавления

    // Выводим все индексы вхождения слова в текст
    System.out.println("Hello = " + multiMap.get("Hello"));    // напечатает [0, 2]
    System.out.println("World = " + multiMap.get("World!"));    // напечатает [1, 5]
    System.out.println("All = " + multiMap.get("All!"));    // напечатает [3]
    System.out.println("Hi = " + multiMap.get("Hi"));    // напечатает [4]
    System.out.println("Empty = " + multiMap.get("Empty"));    // напечатает []

    // Выводим общее количества всех слов в тексте
    System.out.println(multiMap.size());    //напечатает 6

    // Выводим общее количество всех уникальных слов
    System.out.println(multiMap.keySet().size());    //напечатает 4
}