com.google.common.collect.LinkedListMultimap Java Examples

The following examples show how to use com.google.common.collect.LinkedListMultimap. 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: ClientAuthInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 7 votes vote down vote up
@Test
public void testCopyCredentialToHeaders() throws IOException {
  ListMultimap<String, String> values = LinkedListMultimap.create();
  values.put("Authorization", "token1");
  values.put("Authorization", "token2");
  values.put("Extra-Authorization", "token3");
  values.put("Extra-Authorization", "token4");
  when(credentials.getRequestMetadata(any(URI.class))).thenReturn(Multimaps.asMap(values));
  ClientCall<String, Integer> interceptedCall =
      interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
  Metadata headers = new Metadata();
  interceptedCall.start(listener, headers);
  assertEquals(listener, call.responseListener);
  assertEquals(headers, call.headers);

  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  Assert.assertArrayEquals(new String[]{"token1", "token2"},
      Iterables.toArray(authorization, String.class));
  Iterable<String> extraAuthorization = headers.getAll(EXTRA_AUTHORIZATION);
  Assert.assertArrayEquals(new String[]{"token3", "token4"},
      Iterables.toArray(extraAuthorization, String.class));
}
 
Example #2
Source File: ExpandCompositeTermsTest.java    From datawave with Apache License 2.0 7 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    Multimap<String,String> multimap = LinkedListMultimap.create();
    multimap.clear();
    multimap.put("MAKE_COLOR", "MAKE");
    multimap.put("MAKE_COLOR", "COLOR");
    multimap.put("COLOR_WHEELS", "COLOR");
    multimap.put("COLOR_WHEELS", "WHEELS");
    multimap.put("TEAM_NAME_POINTS", "TEAM");
    multimap.put("TEAM_NAME_POINTS", "NAME");
    multimap.put("TEAM_NAME_POINTS", "POINTS");
    multimap.put("TEAM_POINTS", "TEAM");
    multimap.put("TEAM_POINTS", "POINTS");
    compositeToFieldMap = Multimaps.unmodifiableMultimap(multimap);
    
    Map<String,String> sepMap = new HashMap<>();
    sepMap.put("MAKE_COLOR", ",");
    sepMap.put("COLOR_WHEELS", ",");
    sepMap.put("TEAM_NAME_POINTS", ",");
    sepMap.put("TEAM_POINTS", ",");
    compositeFieldSeparators = Collections.unmodifiableMap(sepMap);
}
 
Example #3
Source File: BuildEncyclopediaProcessor.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Create a mapping of rules based on rule type and family.
 */
private void createRuleMapping(Iterable<RuleDocumentation> docEntries,
    Map<String, ListMultimap<RuleType, RuleDocumentation>> ruleMapping)
    throws BuildEncyclopediaDocException {
  for (RuleDocumentation ruleDoc : docEntries) {
    RuleClass ruleClass = ruleClassProvider.getRuleClassMap().get(ruleDoc.getRuleName());
    if (ruleClass != null) {
      String ruleFamily = ruleDoc.getRuleFamily();
      if (!ruleMapping.containsKey(ruleFamily)) {
        ruleMapping.put(ruleFamily, LinkedListMultimap.<RuleType, RuleDocumentation>create());
      }
      if (ruleClass.isDocumented()) {
        ruleMapping.get(ruleFamily).put(ruleDoc.getRuleType(), ruleDoc);
      }
    } else {
      throw ruleDoc.createException("Can't find RuleClass for " + ruleDoc.getRuleName());
    }
  }
}
 
Example #4
Source File: ExpandCompositeTermsTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void test15() throws Exception {
    ShardQueryConfiguration conf = new ShardQueryConfiguration();
    
    Multimap<String,String> compositeToFieldMap = LinkedListMultimap.create();
    
    compositeToFieldMap.put("GEO", "GEO");
    compositeToFieldMap.put("GEO", "WKT_BYTE_LENGTH");
    conf.setCompositeToFieldMap(compositeToFieldMap);
    
    Set<String> indexedFields = new HashSet<>();
    indexedFields.add("GEO");
    
    conf.getFieldToDiscreteIndexTypes().put("GEO", new GeometryType());
    
    String query = "GEO >= '0100' && WKT_BYTE_LENGTH <= '" + Normalizer.NUMBER_NORMALIZER.normalize("12345") + "'";
    String expected = "GEO >= '0100' && WKT_BYTE_LENGTH <= '" + Normalizer.NUMBER_NORMALIZER.normalize("12345") + "'";
    
    runTestQuery(query, expected, indexedFields, conf);
}
 
Example #5
Source File: AcyclicDepthFirstPostOrderTraversalTest.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that a traversal of a well-formed DAG proceeds as expected.
 *
 * <pre>
 *         A
 *       /   \
 *     B       C
 *   /   \   /
 * D       E
 *   \   /
 *     F
 * </pre>
 */
@Test
public void testExpectedTraversal() throws CycleException {
  Multimap<Node, Node> graph = LinkedListMultimap.create();
  graph.put(Node.A, Node.B);
  graph.put(Node.A, Node.C);
  graph.put(Node.B, Node.D);
  graph.put(Node.B, Node.E);
  graph.put(Node.C, Node.E);
  graph.put(Node.D, Node.F);
  graph.put(Node.E, Node.F);
  TestDagDepthFirstSearch dfs = new TestDagDepthFirstSearch(graph);

  dfs.traverse(ImmutableList.of(Node.A));
  ImmutableList<Node> expectedExploredNodes =
      ImmutableList.of(Node.F, Node.D, Node.E, Node.B, Node.C, Node.A);
  assertEquals(expectedExploredNodes, dfs.exploredNodes);
  assertEquals(expectedExploredNodes.size(), dfs.numFindChildrenCalls);
}
 
Example #6
Source File: SpringValueRegistry.java    From apollo with Apache License 2.0 6 votes vote down vote up
public void register(BeanFactory beanFactory, String key, SpringValue springValue) {
  if (!registry.containsKey(beanFactory)) {
    synchronized (LOCK) {
      if (!registry.containsKey(beanFactory)) {
        registry.put(beanFactory, Multimaps.synchronizedListMultimap(LinkedListMultimap.<String, SpringValue>create()));
      }
    }
  }

  registry.get(beanFactory).put(key, springValue);

  // lazy initialize
  if (initialized.compareAndSet(false, true)) {
    initialize();
  }
}
 
Example #7
Source File: ExpandCompositeTermsTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void test12() throws Exception {
    ShardQueryConfiguration conf = new ShardQueryConfiguration();
    
    Multimap<String,String> compositeToFieldMap = LinkedListMultimap.create();
    
    compositeToFieldMap.put("GEO", "GEO");
    compositeToFieldMap.put("GEO", "WKT_BYTE_LENGTH");
    conf.setCompositeToFieldMap(compositeToFieldMap);
    
    Map<String,String> compositeToSeparatorMap = new HashMap<>();
    compositeToSeparatorMap.put("GEO", ",");
    conf.setCompositeFieldSeparators(compositeToSeparatorMap);
    
    Set<String> indexedFields = new HashSet<>();
    indexedFields.add("GEO");
    
    conf.getFieldToDiscreteIndexTypes().put("GEO", new GeometryType());
    
    String query = "((GEO >= '1f0155640000000000' && GEO <= '1f01556bffffffffff') || GEO == '00' || (GEO >= '0100' && GEO <= '0103')) && (WKT_BYTE_LENGTH >= '"
                    + Normalizer.NUMBER_NORMALIZER.normalize("0") + "' && WKT_BYTE_LENGTH <= '" + Normalizer.NUMBER_NORMALIZER.normalize("12345") + "')";
    String expected = "(((GEO >= '1f0155640000000000,+AE0' && GEO <= '1f01556bffffffffff,+eE1.2345') && ((ASTEvaluationOnly = true) && ((GEO >= '1f0155640000000000' && GEO <= '1f01556bffffffffff') && (WKT_BYTE_LENGTH >= '+AE0' && WKT_BYTE_LENGTH <= '+eE1.2345')))) || ((GEO >= '00,+AE0' && GEO <= '00,+eE1.2345') && ((ASTEvaluationOnly = true) && (GEO == '00' && (WKT_BYTE_LENGTH >= '+AE0' && WKT_BYTE_LENGTH <= '+eE1.2345')))) || ((GEO >= '0100,+AE0' && GEO <= '0103,+eE1.2345') && ((ASTEvaluationOnly = true) && ((GEO >= '0100' && GEO <= '0103') && (WKT_BYTE_LENGTH >= '+AE0' && WKT_BYTE_LENGTH <= '+eE1.2345')))))";
    
    runTestQuery(query, expected, indexedFields, conf);
}
 
Example #8
Source File: ExpandCompositeTermsTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void test14() throws Exception {
    ShardQueryConfiguration conf = new ShardQueryConfiguration();
    
    Multimap<String,String> compositeToFieldMap = LinkedListMultimap.create();
    
    compositeToFieldMap.put("GEO", "GEO");
    compositeToFieldMap.put("GEO", "WKT_BYTE_LENGTH");
    conf.setCompositeToFieldMap(compositeToFieldMap);
    
    Map<String,String> compositeToSeparatorMap = new HashMap<>();
    compositeToSeparatorMap.put("GEO", ",");
    conf.setCompositeFieldSeparators(compositeToSeparatorMap);
    
    Set<String> indexedFields = new HashSet<>();
    indexedFields.add("GEO");
    
    conf.getFieldToDiscreteIndexTypes().put("GEO", new GeometryType());
    
    String query = "(GEO >= '0100' && GEO <= '0103') && WKT_BYTE_LENGTH <= '" + Normalizer.NUMBER_NORMALIZER.normalize("12345") + "'";
    String expected = "(GEO >= '0100' && GEO <= '0103,+eE1.2345') && ((ASTEvaluationOnly = true) && ((GEO >= '0100' && GEO <= '0103') && WKT_BYTE_LENGTH <= '+eE1.2345'))";
    
    runTestQuery(query, expected, indexedFields, conf);
}
 
Example #9
Source File: TypesForMessageMapper.java    From saga-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Populate internal map to translate between incoming message event type and saga type.
 */
private Multimap<Class, SagaType> initializeMessageMappings(final Map<Class<? extends Saga>, SagaHandlersMap> handlersMap) {
    Multimap<Class, SagaType> scannedTypes = LinkedListMultimap.create();

    for (Map.Entry<Class<? extends Saga>, SagaHandlersMap> entry : handlersMap.entrySet()) {
        Class<? extends Saga> sagaClass = entry.getKey();

        Collection<MessageHandler> sagaHandlers = entry.getValue().messageHandlers();
        for (MessageHandler handler : sagaHandlers) {

            // remember all message types where a completely new saga needs to be started.
            if (handler.getStartsSaga()) {
                scannedTypes.put(handler.getMessageType(), SagaType.startsNewSaga(sagaClass));
            } else {
                scannedTypes.put(handler.getMessageType(), SagaType.continueSaga(sagaClass));
            }
        }
    }

    return scannedTypes;
}
 
Example #10
Source File: ImmutableSortedKeyListMultimapTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void builderPutAllMultimap() {
  Multimap<String, Integer> toPut = LinkedListMultimap.create();
  toPut.put("foo", 1);
  toPut.put("bar", 4);
  toPut.put("foo", 2);
  toPut.put("foo", 3);
  Multimap<String, Integer> moreToPut = LinkedListMultimap.create();
  moreToPut.put("foo", 6);
  moreToPut.put("bar", 5);
  moreToPut.put("foo", 7);
  ImmutableSortedKeyListMultimap.Builder<String, Integer> builder
      = ImmutableSortedKeyListMultimap.builder();
  builder.putAll(toPut);
  builder.putAll(moreToPut);
  Multimap<String, Integer> multimap = builder.build();
  assertThat(multimap).valuesForKey("foo").containsExactly(1, 2, 3, 6, 7).inOrder();
  assertThat(multimap).valuesForKey("bar").containsExactly(4, 5).inOrder();
  assertThat(multimap).hasSize(7);
}
 
Example #11
Source File: ClientAuthInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopyCredentialToHeaders() throws IOException {
  ListMultimap<String, String> values = LinkedListMultimap.create();
  values.put("Authorization", "token1");
  values.put("Authorization", "token2");
  values.put("Extra-Authorization", "token3");
  values.put("Extra-Authorization", "token4");
  when(credentials.getRequestMetadata(any(URI.class))).thenReturn(Multimaps.asMap(values));
  ClientCall<String, Integer> interceptedCall =
      interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
  Metadata headers = new Metadata();
  interceptedCall.start(listener, headers);
  assertEquals(listener, call.responseListener);
  assertEquals(headers, call.headers);

  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  Assert.assertArrayEquals(new String[]{"token1", "token2"},
      Iterables.toArray(authorization, String.class));
  Iterable<String> extraAuthorization = headers.getAll(EXTRA_AUTHORIZATION);
  Assert.assertArrayEquals(new String[]{"token3", "token4"},
      Iterables.toArray(extraAuthorization, String.class));
}
 
Example #12
Source File: ExpandCompositeTermsTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void test23() throws Exception {
    ShardQueryConfiguration conf = new ShardQueryConfiguration();
    
    Multimap<String,String> compositeToFieldMap = LinkedListMultimap.create();
    
    compositeToFieldMap.put("GEO_WKT", "GEO");
    compositeToFieldMap.put("GEO_WKT", "WKT");
    conf.setCompositeToFieldMap(compositeToFieldMap);
    
    Map<String,String> compositeToSeparatorMap = new HashMap<>();
    compositeToSeparatorMap.put("GEO_WKT", ",");
    conf.setCompositeFieldSeparators(compositeToSeparatorMap);
    
    Set<String> indexedFields = new HashSet<>();
    indexedFields.add("GEO");
    
    conf.getFieldToDiscreteIndexTypes().put("GEO", new GeometryType());
    
    String query = "((((GEO >= '0202' && GEO <= '020d'))) || (((GEO >= '030a' && GEO <= '0335'))) || (((GEO >= '0428' && GEO <= '0483'))) || (((GEO >= '0500aa' && GEO <= '050355'))) || (((GEO >= '1f0aaaaaaaaaaaaaaa' && GEO <= '1f36c71c71c71c71c7')))) && ((WKT >= '+AE0' && WKT < '+bE4'))";
    String expected = "(((((GEO_WKT >= '0202,+AE0' && GEO_WKT < '020d,+bE4') && ((ASTEvaluationOnly = true) && ((GEO >= '0202' && GEO <= '020d') && (WKT >= '+AE0' && WKT < '+bE4')))))) || ((((GEO_WKT >= '030a,+AE0' && GEO_WKT < '0335,+bE4') && ((ASTEvaluationOnly = true) && ((GEO >= '030a' && GEO <= '0335') && (WKT >= '+AE0' && WKT < '+bE4')))))) || ((((GEO_WKT >= '0428,+AE0' && GEO_WKT < '0483,+bE4') && ((ASTEvaluationOnly = true) && ((GEO >= '0428' && GEO <= '0483') && (WKT >= '+AE0' && WKT < '+bE4')))))) || ((((GEO_WKT >= '0500aa,+AE0' && GEO_WKT < '050355,+bE4') && ((ASTEvaluationOnly = true) && ((GEO >= '0500aa' && GEO <= '050355') && (WKT >= '+AE0' && WKT < '+bE4')))))) || ((((GEO_WKT >= '1f0aaaaaaaaaaaaaaa,+AE0' && GEO_WKT < '1f36c71c71c71c71c7,+bE4') && ((ASTEvaluationOnly = true) && ((GEO >= '1f0aaaaaaaaaaaaaaa' && GEO <= '1f36c71c71c71c71c7') && (WKT >= '+AE0' && WKT < '+bE4')))))))";
    
    runTestQuery(query, expected, indexedFields, conf);
}
 
Example #13
Source File: ExpandCompositeTermsTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void test27() throws Exception {
    ShardQueryConfiguration conf = new ShardQueryConfiguration();
    
    Multimap<String,String> compositeToFieldMap = LinkedListMultimap.create();
    
    compositeToFieldMap.put("GEO", "GEO");
    compositeToFieldMap.put("GEO", "WKT");
    conf.setCompositeToFieldMap(compositeToFieldMap);
    
    Map<String,String> compositeToSeparatorMap = new HashMap<>();
    compositeToSeparatorMap.put("GEO", ",");
    conf.setCompositeFieldSeparators(compositeToSeparatorMap);
    
    Set<String> indexedFields = new HashSet<>();
    indexedFields.add("GEO");
    
    conf.getFieldToDiscreteIndexTypes().put("GEO", new GeometryType());
    
    String normNum = Normalizer.NUMBER_NORMALIZER.normalize("55");
    
    String query = "(GEO == '0202' || ((GEO >= '030a' && GEO <= '0335'))) && WKT == '" + normNum + "'";
    String expected = "(GEO == '0202,+bE5.5' || (((GEO >= '030a,+bE5.5' && GEO <= '0335,+bE5.5') && ((ASTEvaluationOnly = true) && ((GEO >= '030a' && GEO <= '0335') && WKT == '+bE5.5')))))";
    
    runTestQuery(query, expected, indexedFields, conf);
}
 
Example #14
Source File: QuotaLimitNameValidator.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
private void checkQuotaLimitNamesAreUnique(Quota quota) {
  ListMultimap<String, QuotaLimit> limitNameCounts = LinkedListMultimap.create();
  for (QuotaLimit limit : quota.getLimitsList()) {
    limitNameCounts.put(limit.getName(), limit);
  }
  for (String limitName : limitNameCounts.keySet()) {
    List<QuotaLimit> limits = limitNameCounts.get(limitName);
    if (limits.size() > 1) {
      error(
          MessageLocationContext.create(Iterables.getLast(limits), "name"),
          "There are %d quota limits with name '%s'.",
          limits.size(),
          limitName);
    }
  }
}
 
Example #15
Source File: PolyfillValidatorFragment.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Find clashes by name.
 *
 * @param myPolyMember
 *            current validated Polyfill
 * @param pivotPolyMember
 *            other polyfill in same project
 * @return pairs of contrandicting or same polyfills.
 */
private ListMultimap<TMember, TMember> findClashingMembersByName(EList<TMember> myPolyMember,
		EList<TMember> pivotPolyMember) {
	ListMultimap<TMember, TMember> ret = LinkedListMultimap.create();
	for (TMember my : myPolyMember) {
		String myName = my.getName();
		if (myName == null)
			continue; // broken AST
		for (TMember other : pivotPolyMember) {
			String otherName = other.getName();
			if (myName.equals(otherName)) {
				ret.put(my, other);
			}
		}
	}
	return ret;
}
 
Example #16
Source File: BaseDataObject.java    From emissary with Apache License 2.0 6 votes vote down vote up
/**
 * Clone this payload
 */
@Override
public IBaseDataObject clone() throws CloneNotSupportedException {
    final BaseDataObject c = (BaseDataObject) super.clone();
    if ((this.theData != null) && (this.theData.length > 0)) {
        c.setData(this.theData, 0, this.theData.length);
    }
    c.currentForm = new ArrayList<>(this.currentForm);
    c.history = new ArrayList<>(this.history);
    c.multipartAlternative = new HashMap<>(this.multipartAlternative);
    c.priority = this.priority;
    c.creationTimestamp = this.creationTimestamp;

    if ((this.extractedRecords != null) && !this.extractedRecords.isEmpty()) {
        c.clearExtractedRecords(); // remove super.clone copy
        for (final IBaseDataObject r : this.extractedRecords) {
            c.addExtractedRecord(r.clone());
        }
    }
    // This creates a deep copy Guava style
    c.parameters = LinkedListMultimap.create(this.parameters);

    return c;
}
 
Example #17
Source File: PreciseAspectResolver.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableMultimap<Attribute, Label> computeAspectDependencies(
    Target target, DependencyFilter dependencyFilter) throws InterruptedException {
  if (!(target instanceof Rule)) {
    return ImmutableMultimap.of();
  }
  Rule rule = (Rule) target;
  if (!rule.hasAspects()) {
    return ImmutableMultimap.of();
  }
  Multimap<Attribute, Label> result = LinkedListMultimap.create();
  Multimap<Attribute, Label> transitions =
      rule.getTransitions(DependencyFilter.NO_NODEP_ATTRIBUTES);
  for (Attribute attribute : transitions.keySet()) {
    for (Aspect aspect : attribute.getAspects(rule)) {
      if (hasDepThatSatisfies(aspect, transitions.get(attribute))) {
        AspectDefinition.forEachLabelDepFromAllAttributesOfAspect(
            rule, aspect, dependencyFilter, result::put);
      }
    }
  }
  return ImmutableMultimap.copyOf(result);
}
 
Example #18
Source File: AcyclicDepthFirstPostOrderTraversalTest.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the reported cycle mentions only A, B, and D, but not C or E.
 *
 * <pre>
 *         A <---|
 *       /       |
 *     B         |
 *   / | \       |
 * C   D   E     |
 *     |         |
 *     ==========|
 * </pre>
 */
@Test
public void testCycleExceptionDoesNotContainUnrelatedNodes() {
  Multimap<Node, Node> graph = LinkedListMultimap.create();
  graph.put(Node.A, Node.B);
  graph.put(Node.B, Node.C);
  graph.put(Node.B, Node.D);
  graph.put(Node.B, Node.E);
  graph.put(Node.D, Node.A);

  TestDagDepthFirstSearch dfs = new TestDagDepthFirstSearch(graph);
  try {
    dfs.traverse(ImmutableList.of(Node.A));
  } catch (CycleException e) {
    assertThat(
        e.getMessage(),
        Matchers.containsString(
            linesToText(
                "The following circular dependency has been found:", "A -> B -> D -> A")));
    assertEquals(ImmutableList.of(Node.A, Node.B, Node.D, Node.A), e.getCycle());
  }
}
 
Example #19
Source File: ExpandCompositeTermsTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void test29() throws Exception {
    ShardQueryConfiguration conf = new ShardQueryConfiguration();
    
    Multimap<String,String> compositeToFieldMap = LinkedListMultimap.create();
    
    compositeToFieldMap.put("GEO", "GEO");
    compositeToFieldMap.put("GEO", "WKT");
    conf.setCompositeToFieldMap(compositeToFieldMap);
    
    Map<String,String> compositeToSeparatorMap = new HashMap<>();
    compositeToSeparatorMap.put("GEO", ",");
    conf.setCompositeFieldSeparators(compositeToSeparatorMap);
    
    Set<String> indexedFields = new HashSet<>();
    indexedFields.add("GEO");
    
    conf.getFieldToDiscreteIndexTypes().put("GEO", new GeometryType());
    
    String query = "(GEO == '0202' || GEO >= '030a') && WKT == '+bE5.5'";
    String expected = "((WKT == '+bE5.5' && GEO >= '030a') || GEO == '0202,+bE5.5')";
    
    runTestQuery(query, expected, indexedFields, conf);
}
 
Example #20
Source File: Signer.java    From galaxy-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Sign the specified http request.
 *
 * @param httpMethod  The http request method
 * @param uri The uri string
 * @param httpHeaders The http request headers
 * @param secretAccessKeyId The user's secret access key
 * @param algorithm   The sign algorithm
 * @return Byte buffer of the signed result
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.InvalidKeyException
 */
public static byte[] sign(HttpMethod httpMethod, URI uri,
    LinkedListMultimap<String, String> httpHeaders, String secretAccessKeyId,
    SignAlgorithm algorithm) throws NoSuchAlgorithmException,
    InvalidKeyException {
  Preconditions.checkNotNull(httpMethod, "Http method");
  Preconditions.checkNotNull(uri, "uri");
  Preconditions.checkNotNull(secretAccessKeyId, "secret access key");
  Preconditions.checkNotNull(algorithm, "algorithm");

  String stringToSign = constructStringToSign(httpMethod,
      uri, httpHeaders);

  Mac mac = Mac.getInstance(algorithm.name());
  mac.init(new SecretKeySpec(secretAccessKeyId.getBytes(), algorithm.name()));
  return mac.doFinal(stringToSign.getBytes());
}
 
Example #21
Source File: ExpandCompositeTermsTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void test24() throws Exception {
    ShardQueryConfiguration conf = new ShardQueryConfiguration();
    
    Multimap<String,String> compositeToFieldMap = LinkedListMultimap.create();
    
    compositeToFieldMap.put("GEO_WKT", "GEO");
    compositeToFieldMap.put("GEO_WKT", "WKT");
    conf.setCompositeToFieldMap(compositeToFieldMap);
    
    Set<String> indexedFields = new HashSet<>();
    indexedFields.add("GEO");
    
    conf.getFieldToDiscreteIndexTypes().put("GEO", new GeometryType());
    
    String query = "((((GEO >= '0202' && GEO <= '020d'))) || (((GEO >= '030a' && GEO <= '0335'))) || (((GEO >= '0428' && GEO <= '0483'))) || (((GEO >= '0500aa' && GEO <= '050355'))) || (((GEO >= '1f0aaaaaaaaaaaaaaa' && GEO <= '1f36c71c71c71c71c7'))))";
    String expected = "((((GEO >= '0202' && GEO <= '020d'))) || (((GEO >= '030a' && GEO <= '0335'))) || (((GEO >= '0428' && GEO <= '0483'))) || (((GEO >= '0500aa' && GEO <= '050355'))) || (((GEO >= '1f0aaaaaaaaaaaaaaa' && GEO <= '1f36c71c71c71c71c7'))))";
    
    runTestQuery(query, expected, indexedFields, conf);
}
 
Example #22
Source File: JsonLdSerializer.java    From schemaorg-java with Apache License 2.0 5 votes vote down vote up
private Thing readObject(JsonReader reader) throws IOException {
  reader.beginObject();
  Multimap<String, ValueType> properties = LinkedListMultimap.create();
  ListMultimap<String, Thing> reverseMap = LinkedListMultimap.create();
  String typeName = null;
  while (reader.hasNext()) {
    String key = reader.nextName();
    if (JsonLdConstants.TYPE.equals(key)) {
      typeName = reader.nextString();
    } else if (JsonLdConstants.CONTEXT.equals(key)) {
      properties.putAll(key, readContext(reader));
    } else if (JsonLdConstants.REVERSE.equals(key)) {
      reverseMap.putAll(readReverse(reader));
    } else {
      properties.putAll(
          key, readInternal(reader, JsonLdConstants.ID.equals(key) /* acceptNull */));
    }
  }
  reader.endObject();
  if (Strings.isNullOrEmpty(typeName)) {
    // Treat any unrecognized types as Thing.
    typeName = THING;
  }
  // Value of @type should be short type name or full type name.
  // Doesn't support relative IRI or compact IRI for now.
  return buildSchemaOrgObject(typeName, properties, reverseMap);
}
 
Example #23
Source File: Signer.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
static List<String> checkAndGet(LinkedListMultimap<String, String> headers,
    String header) {
  List<String> result = new LinkedList<String>();
  if (headers == null) {
    result.add("");
    return result;
  }

  List<String> values = headers.get(header);
  if (values == null || values.isEmpty()) {
    result.add("");
    return result;
  }
  return values;
}
 
Example #24
Source File: Signer.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
private static LinkedListMultimap<String, String> parseUriParameters(URI uri) {
  LinkedListMultimap<String, String> params = LinkedListMultimap.create();
  String query = uri.getQuery();
  if (query != null) {
    for (String param : query.split("&")) {
      String[] kv = param.split("=");
      if (kv.length >= 2) {
        params.put(kv[0], param.substring(kv[0].length() + 1));
      } else {
        params.put(kv[0], "");
      }
    }
  }
  return params;
}
 
Example #25
Source File: WidgetPerfLinter.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CompletableFuture<ArrayList<PerfTip>> getTipsFor(Set<TextEditor> textEditors) {
  final ArrayList<PerfTipRule> candidateRules = new ArrayList<>();
  final Set<Location> candidateLocations = new HashSet<>();
  final ArrayList<FilePerfInfo> allFileStats = widgetPerf.buildAllSummaryStats(textEditors);
  for (PerfTipRule rule : getAllTips()) {
    for (FilePerfInfo fileStats : allFileStats) {
      for (SummaryStats stats : fileStats.getStats()) {
        if (rule.maybeMatches(stats)) {
          candidateRules.add(rule);
          candidateLocations.add(stats.getLocation());
          break;
        }
      }
    }
  }

  if (candidateRules.isEmpty()) {
    return CompletableFuture.completedFuture(new ArrayList<>());
  }

  if (candidateLocations.equals(lastCandidateLocations)) {
    // No need to load the widget tree again if the list of locations matching rules has not changed.
    return CompletableFuture.completedFuture(computeMatches(candidateRules, allFileStats));
  }

  lastCandidateLocations = candidateLocations;
  return perfProvider.getWidgetTree().thenApplyAsync((treeRoot) -> {
    if (treeRoot != null) {
      nodesForLocation = LinkedListMultimap.create();
      addNodesToMap(treeRoot);
      return computeMatches(candidateRules, allFileStats);
    }
    else {
      return new ArrayList<>();
    }
  });
}
 
Example #26
Source File: SignatureUtil.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
public static long getDateTime(LinkedListMultimap<String, String> headers) {
  List<String> dateList = headers.get(HttpKeys.MI_DATE);
  if (dateList.isEmpty()) {
    dateList = headers.get(HttpKeys.DATE);
  }

  if (!dateList.isEmpty()) {
    String datetime = dateList.get(0);
    return HttpUtils.parseDateTimeToMilliseconds(datetime);
  }
  return 0;
}
 
Example #27
Source File: HttpCaller.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ActualResult call(HttpRequest value) throws IOException {
  return executeRequest(value, response -> {
    LinkedListMultimap<String, String> headers = LinkedListMultimap.create();
    for (Header header : response.getAllHeaders()) {
      headers.put(header.getName(), header.getValue());
    }

    return new ActualResult(
      response.getStatusLine().getStatusCode(),
      response.getStatusLine().getReasonPhrase(),
      headers
    );
  });
}
 
Example #28
Source File: Signer.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
static String canonicalizeXiaomiHeaders(
    LinkedListMultimap<String, String> headers) {
  if (headers == null) {
    return "";
  }

  // 1. Sort the header and merge the values
  Map<String, String> sortedHeaders = new TreeMap<String, String>();
  for (String key : headers.keySet()) {
    if (!key.toLowerCase().startsWith(HttpKeys.XIAOMI_HEADER_PREFIX)) {
      continue;
    }

    StringBuilder builder = new StringBuilder();
    int index = 0;
    for (String value : headers.get(key)) {
      if (index != 0) {
        builder.append(",");
      }
      builder.append(value);
      index++;
    }
    sortedHeaders.put(key, builder.toString());
  }

  // 3. Generate the canonicalized result
  StringBuilder result = new StringBuilder();
  for (Entry<String, String> entry : sortedHeaders.entrySet()) {
    result.append(entry.getKey()).append(":")
        .append(entry.getValue()).append("\n");
  }
  return result.toString();
}
 
Example #29
Source File: MetricsHttpClient.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Set signature related headers when credential is properly set
 */
private MetricsHttpClient setAuthenticationHeaders(HttpPost post, byte[] data) {
  if (this.client != null && credential != null) {
    if (credential.getSecretKeyId() != null) {
      String host = this.host.toHostString();
      host = host.split(":")[0];
      post.setHeader(AuthenticationConstants.HK_HOST, host);

      // timestamp
      String timestamp = Long.toString(clock.getCurrentEpoch());
      post.setHeader(AuthenticationConstants.HK_TIMESTAMP, timestamp);
      post.setHeader(HttpKeys.MI_DATE, HttpUtils.getGMTDatetime(new Date()));

      // content md5
      String md5 = BytesUtil
          .bytesToHex(DigestUtil.digest(DigestUtil.DigestAlgorithm.MD5, data));
      post.setHeader(com.xiaomi.infra.galaxy.sds.thrift.AuthenticationConstants.HK_CONTENT_MD5, md5);
      LinkedListMultimap<String, String> headers = LinkedListMultimap.create();
      for (Header header : post.getAllHeaders()) {
        headers.put(header.getName().toLowerCase(), header.getValue());
      }
      try {
        String authString = "Galaxy-V3 "
            + credential.getSecretKeyId()
            + ":"
            + Signer.signToBase64(HttpMethod.POST, post.getURI(), headers,
              credential.getSecretKey(), SignAlgorithm.HmacSHA1);
        post.setHeader(AuthenticationConstants.HK_AUTHORIZATION, authString);
      } catch (Exception e) {
        throw new RuntimeException("Failed to sign", e);
      }
    } else {
      throw new RuntimeException("SecretKeyId must not be null");
    }
  }
  return this;
}
 
Example #30
Source File: StateChangeNotifier.java    From tez with Apache License 2.0 5 votes vote down vote up
public StateChangeNotifier(DAG dag) {
  this.dag = dag;
  this.vertexListeners = Multimaps.synchronizedSetMultimap(
      HashMultimap.<TezVertexID, ListenerContainer>create());
  this.lastKnowStatesMap = LinkedListMultimap.create();
  startThread();
}