/**
  * If the "value" entry contains both "DerivedTxConfig" AND "TxConfig", then the algorithm is
  * accidentally picking up shadowed annotations of the same type within the class hierarchy. Such
  * undesirable behavior would cause the logic in {@link
  * org.springframework.context.annotation.ProfileCondition} to fail.
  *
  * @see
  *     org.springframework.core.env.EnvironmentSystemIntegrationTests#mostSpecificDerivedClassDrivesEnvironment_withDevEnvAndDerivedDevConfigClass
  */
 @Test
 public void
     getAllAnnotationAttributesOnClassWithLocalAnnotationThatShadowsAnnotationFromSuperclass() {
   MultiValueMap<String, Object> attributes =
       getAllAnnotationAttributes(DerivedTxConfig.class, TX_NAME);
   assertNotNull("Annotation attributes map for @Transactional on DerivedTxConfig", attributes);
   assertEquals("value for DerivedTxConfig.", asList("DerivedTxConfig"), attributes.get("value"));
 }
 @Test
 public void getAllAnnotationAttributesOnClassWithLocalComposedAnnotationAndInheritedAnnotation() {
   MultiValueMap<String, Object> attributes =
       getAllAnnotationAttributes(SubClassWithInheritedAnnotation.class, TX_NAME);
   assertNotNull(
       "Annotation attributes map for @Transactional on SubClassWithInheritedAnnotation",
       attributes);
   assertEquals(asList("composed2", "transactionManager"), attributes.get("qualifier"));
 }
 @Test
 public void simpleStringKeyStringValueFormData() throws Exception {
   HttpRequestExecutingMessageHandler handler =
       new HttpRequestExecutingMessageHandler("http://www.springsource.org/spring-integration");
   MockRestTemplate template = new MockRestTemplate();
   new DirectFieldAccessor(handler).setPropertyValue("restTemplate", template);
   handler.setHttpMethod(HttpMethod.POST);
   setBeanFactory(handler);
   handler.afterPropertiesSet();
   Map<String, String> form = new LinkedHashMap<String, String>();
   form.put("a", "1");
   form.put("b", "2");
   form.put("c", "3");
   Message<?> message = MessageBuilder.withPayload(form).build();
   QueueChannel replyChannel = new QueueChannel();
   handler.setOutputChannel(replyChannel);
   Exception exception = null;
   try {
     handler.handleMessage(message);
   } catch (Exception e) {
     exception = e;
   }
   assertEquals("intentional", exception.getCause().getMessage());
   HttpEntity<?> request = template.lastRequestEntity.get();
   Object body = request.getBody();
   assertNotNull(request.getHeaders().getContentType());
   assertTrue(body instanceof MultiValueMap<?, ?>);
   MultiValueMap<?, ?> map = (MultiValueMap<?, ?>) body;
   assertEquals("1", map.get("a").iterator().next());
   assertEquals("2", map.get("b").iterator().next());
   assertEquals("3", map.get("c").iterator().next());
   assertEquals(MediaType.APPLICATION_FORM_URLENCODED, request.getHeaders().getContentType());
 }
 @Test
 public void nameOnlyWithNullValues() throws Exception {
   HttpRequestExecutingMessageHandler handler =
       new HttpRequestExecutingMessageHandler("http://www.springsource.org/spring-integration");
   MockRestTemplate template = new MockRestTemplate();
   new DirectFieldAccessor(handler).setPropertyValue("restTemplate", template);
   handler.setHttpMethod(HttpMethod.POST);
   setBeanFactory(handler);
   handler.afterPropertiesSet();
   Map<String, Object> form = new LinkedHashMap<String, Object>();
   form.put("a", null);
   form.put("b", "foo");
   form.put("c", null);
   Message<?> message = MessageBuilder.withPayload(form).build();
   Exception exception = null;
   try {
     handler.handleMessage(message);
   } catch (Exception e) {
     exception = e;
   }
   assertEquals("intentional", exception.getCause().getMessage());
   HttpEntity<?> request = template.lastRequestEntity.get();
   Object body = request.getBody();
   assertTrue(body instanceof MultiValueMap<?, ?>);
   MultiValueMap<?, ?> map = (MultiValueMap<?, ?>) body;
   assertTrue(map.containsKey("a"));
   assertTrue(map.get("a").size() == 1);
   assertNull(map.get("a").get(0));
   List<?> entryB = map.get("b");
   assertEquals("foo", entryB.get(0));
   assertTrue(map.containsKey("c"));
   assertTrue(map.get("c").size() == 1);
   assertNull(map.get("c").get(0));
   assertEquals(MediaType.APPLICATION_FORM_URLENCODED, request.getHeaders().getContentType());
 }
Exemplo n.º 5
0
  @Test
  public void parseMatrixVariablesString() {
    MultiValueMap<String, String> variables;

    variables = WebUtils.parseMatrixVariables(null);
    assertEquals(0, variables.size());

    variables = WebUtils.parseMatrixVariables("year");
    assertEquals(1, variables.size());
    assertEquals("", variables.getFirst("year"));

    variables = WebUtils.parseMatrixVariables("year=2012");
    assertEquals(1, variables.size());
    assertEquals("2012", variables.getFirst("year"));

    variables = WebUtils.parseMatrixVariables("year=2012;colors=red,blue,green");
    assertEquals(2, variables.size());
    assertEquals(Arrays.asList("red", "blue", "green"), variables.get("colors"));
    assertEquals("2012", variables.getFirst("year"));

    variables = WebUtils.parseMatrixVariables(";year=2012;colors=red,blue,green;");
    assertEquals(2, variables.size());
    assertEquals(Arrays.asList("red", "blue", "green"), variables.get("colors"));
    assertEquals("2012", variables.getFirst("year"));

    variables = WebUtils.parseMatrixVariables("colors=red;colors=blue;colors=green");
    assertEquals(1, variables.size());
    assertEquals(Arrays.asList("red", "blue", "green"), variables.get("colors"));
  }
Exemplo n.º 6
0
 /**
  * 根据规则名获取规则实例 <功能详细描述>
  *
  * @param rule
  * @return [参数说明]
  * @return Rule [返回类型说明]
  * @exception throws [异常类型] [异常说明]
  * @see [类、类#方法、类#成员]
  */
 public Rule getRule(String rule) {
   waitLoading();
   if (ruleKeyMapCache.containsKey(rule)) {
     return ruleKeyMapCache.get(rule);
   } else if (multiRuleMapCache.containsKey(rule)) {
     if (multiRuleMapCache.get(rule) != null && multiRuleMapCache.get(rule).size() > 1) {
       throw new RuleAccessException(rule, null, null, "未带业务类型(命名空间)的规则,检索到超过多个规则:{}", rule);
     } else {
       return multiRuleMapCache.getFirst(rule);
     }
   } else {
     return null;
   }
 }
  @Test
  public void stringKeyPrimitiveArrayValueMixedFormData() throws Exception {
    HttpRequestExecutingMessageHandler handler =
        new HttpRequestExecutingMessageHandler("http://www.springsource.org/spring-integration");
    MockRestTemplate template = new MockRestTemplate();
    new DirectFieldAccessor(handler).setPropertyValue("restTemplate", template);
    handler.setHttpMethod(HttpMethod.POST);
    setBeanFactory(handler);
    handler.afterPropertiesSet();
    Map<String, Object> form = new LinkedHashMap<String, Object>();
    form.put("a", new int[] {1, 2, 3});
    form.put("b", "4");
    form.put("c", new String[] {"5"});
    form.put("d", "6");
    Message<?> message = MessageBuilder.withPayload(form).build();
    Exception exception = null;
    try {
      handler.handleMessage(message);
    } catch (Exception e) {
      exception = e;
    }
    assertEquals("intentional", exception.getCause().getMessage());
    HttpEntity<?> request = template.lastRequestEntity.get();
    Object body = request.getBody();
    assertTrue(body instanceof MultiValueMap<?, ?>);
    MultiValueMap<?, ?> map = (MultiValueMap<?, ?>) body;

    List<?> aValue = map.get("a");
    assertEquals(1, aValue.size());
    Object value = aValue.get(0);
    assertTrue(value.getClass().isArray());
    int[] y = (int[]) value;
    assertEquals(1, y[0]);
    assertEquals(2, y[1]);
    assertEquals(3, y[2]);

    List<?> bValue = map.get("b");
    assertEquals(1, bValue.size());
    assertEquals("4", bValue.get(0));

    List<?> cValue = map.get("c");
    assertEquals(1, cValue.size());
    assertEquals("5", cValue.get(0));

    List<?> dValue = map.get("d");
    assertEquals(1, dValue.size());
    assertEquals("6", dValue.get(0));
    assertEquals(MediaType.MULTIPART_FORM_DATA, request.getHeaders().getContentType());
  }
 @Test
 @DirtiesContext
 public void testRoles() {
   this.roleController.stopLifecyclesInRole("foo");
   @SuppressWarnings("unchecked")
   MultiValueMap<String, SmartLifecycle> lifecycles =
       TestUtils.getPropertyValue(this.roleController, "lifecycles", MultiValueMap.class);
   assertEquals(2, lifecycles.size());
   assertEquals(2, lifecycles.get("foo").size());
   assertEquals(1, lifecycles.get("bar").size());
   assertFalse(this.serviceActivatorEndpoint.isRunning());
   assertFalse(this.sendAsyncHandler.isRunning());
   assertEquals(2, lifecycles.size());
   assertEquals(2, lifecycles.get("foo").size());
 }
 private String generateForm(MultiValueMap<String, String> form) {
   StringBuilder builder = new StringBuilder();
   try {
     for (Iterator<String> names = form.keySet().iterator(); names.hasNext(); ) {
       String name = names.next();
       for (Iterator<String> values = form.get(name).iterator(); values.hasNext(); ) {
         String value = values.next();
         builder.append(URLEncoder.encode(name, "UTF-8"));
         if (value != null) {
           builder.append('=');
           builder.append(URLEncoder.encode(value, "UTF-8"));
           if (values.hasNext()) {
             builder.append('&');
           }
         }
       }
       if (names.hasNext()) {
         builder.append('&');
       }
     }
   } catch (UnsupportedEncodingException ex) {
     throw new IllegalStateException(ex);
   }
   return builder.toString();
 }
Exemplo n.º 10
0
 public URI build() {
   StringBuilder builder = new StringBuilder(url);
   try {
     if (!params.isEmpty()) {
       builder.append("?");
       boolean first = true;
       for (String key : params.keySet()) {
         if (!first) {
           builder.append("&");
         } else {
           first = false;
         }
         for (String value : params.get(key)) {
           builder.append(key + "=" + UriUtils.encodeQueryParam(value, "UTF-8"));
         }
       }
     }
     return new URI(builder.toString());
   } catch (UnsupportedEncodingException ex) {
     // should not happen, UTF-8 is always supported
     throw new IllegalStateException(ex);
   } catch (URISyntaxException ex) {
     throw new IllegalArgumentException(
         "Could not create URI from [" + builder + "]: " + ex, ex);
   }
 }
 private Header[] convertHeaders(MultiValueMap<String, String> headers) {
   List<Header> list = new ArrayList<>();
   for (String name : headers.keySet()) {
     for (String value : headers.get(name)) {
       list.add(new BasicHeader(name, value));
     }
   }
   return list.toArray(new BasicHeader[0]);
 }
 @Test
 public void
     getAllAnnotationAttributesFavorsInheritedComposedAnnotationsOverMoreLocallyDeclaredComposedAnnotations() {
   MultiValueMap<String, Object> attributes =
       getAllAnnotationAttributes(SubSubClassWithInheritedComposedAnnotation.class, TX_NAME);
   assertNotNull(
       "Annotation attributes map for @Transactional on SubSubClassWithInheritedComposedAnnotation",
       attributes);
   assertEquals(asList("composed1"), attributes.get("qualifier"));
 }
  @Test
  public void stringKeyObjectCollectionValueFormData() throws Exception {
    HttpRequestExecutingMessageHandler handler =
        new HttpRequestExecutingMessageHandler("http://www.springsource.org/spring-integration");
    MockRestTemplate template = new MockRestTemplate();
    new DirectFieldAccessor(handler).setPropertyValue("restTemplate", template);
    handler.setHttpMethod(HttpMethod.POST);
    setBeanFactory(handler);
    handler.afterPropertiesSet();
    Map<String, Object> form = new LinkedHashMap<String, Object>();
    List<Object> listA = new ArrayList<Object>();
    listA.add(new City("Philadelphia"));
    listA.add(new City("Ambler"));
    form.put("a", listA);
    form.put("b", Collections.EMPTY_LIST);
    form.put("c", Collections.singletonList(new City("Mohnton")));
    Message<?> message = MessageBuilder.withPayload(form).build();
    Exception exception = null;
    try {
      handler.handleMessage(message);
    } catch (Exception e) {
      exception = e;
    }
    assertEquals("intentional", exception.getCause().getMessage());
    HttpEntity<?> request = template.lastRequestEntity.get();
    Object body = request.getBody();
    assertTrue(body instanceof MultiValueMap<?, ?>);
    MultiValueMap<?, ?> map = (MultiValueMap<?, ?>) body;

    List<?> aValue = map.get("a");
    assertEquals(2, aValue.size());
    assertEquals("Philadelphia", aValue.get(0).toString());
    assertEquals("Ambler", aValue.get(1).toString());

    List<?> bValue = map.get("b");
    assertEquals(0, bValue.size());

    List<?> cValue = map.get("c");
    assertEquals(1, cValue.size());
    assertEquals("Mohnton", cValue.get(0).toString());

    assertEquals(MediaType.MULTIPART_FORM_DATA, request.getHeaders().getContentType());
  }
 private MultiValueMap<String, String> revertHeaders(Header[] headers) {
   MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
   for (Header header : headers) {
     String name = header.getName();
     if (!map.containsKey(name)) {
       map.put(name, new ArrayList<String>());
     }
     map.get(name).add(header.getValue());
   }
   return map;
 }
  /**
   * This test and the one below might look identical, but they are not. This test injected "5" into
   * the list as String resulting in the Content-TYpe being application/x-www-form-urlencoded
   *
   * @throws Exception
   */
  @Test
  public void stringKeyNullCollectionValueMixedFormDataString() throws Exception {
    HttpRequestExecutingMessageHandler handler =
        new HttpRequestExecutingMessageHandler("http://www.springsource.org/spring-integration");
    MockRestTemplate template = new MockRestTemplate();
    new DirectFieldAccessor(handler).setPropertyValue("restTemplate", template);
    handler.setHttpMethod(HttpMethod.POST);
    setBeanFactory(handler);
    handler.afterPropertiesSet();
    Map<String, Object> form = new LinkedHashMap<String, Object>();
    List<Object> list = new ArrayList<Object>();
    list.add(null);
    list.add("5");
    list.add(null);
    form.put("a", list);
    form.put("b", "4");
    Message<?> message = MessageBuilder.withPayload(form).build();
    Exception exception = null;
    try {
      handler.handleMessage(message);
    } catch (Exception e) {
      exception = e;
    }
    assertEquals("intentional", exception.getCause().getMessage());
    HttpEntity<?> request = template.lastRequestEntity.get();
    Object body = request.getBody();
    assertTrue(body instanceof MultiValueMap<?, ?>);
    MultiValueMap<?, ?> map = (MultiValueMap<?, ?>) body;

    List<?> aValue = map.get("a");
    assertEquals(3, aValue.size());
    assertNull(aValue.get(0));
    assertEquals("5", aValue.get(1));
    assertNull(aValue.get(2));

    List<?> bValue = map.get("b");
    assertEquals(1, bValue.size());
    assertEquals("4", bValue.get(0));

    assertEquals(MediaType.APPLICATION_FORM_URLENCODED, request.getHeaders().getContentType());
  }
 /**
  * Note: this functionality is required by {@link
  * org.springframework.context.annotation.ProfileCondition}.
  *
  * @see org.springframework.core.env.EnvironmentSystemIntegrationTests
  */
 @Test
 public void getAllAnnotationAttributesOnClassWithMultipleComposedAnnotations() {
   MultiValueMap<String, Object> attributes =
       getAllAnnotationAttributes(TxFromMultipleComposedAnnotations.class, TX_NAME);
   assertNotNull(
       "Annotation attributes map for @Transactional on TxFromMultipleComposedAnnotations",
       attributes);
   assertEquals(
       "value for TxFromMultipleComposedAnnotations.",
       asList("TxInheritedComposed", "TxComposed"),
       attributes.get("value"));
 }
  /**
   * Looks up the best-matching {@link HandlerMethod} for the given request.
   *
   * <p>This implementation iterators through all handler methods, calls {@link
   * #getMatchingMapping(Object, String, HttpServletRequest)} for each of them, sorts all matches
   * via {@linkplain #getMappingComparator(String, HttpServletRequest)} , and returns the top match,
   * if any. If no matches are found, {@link #handleNoMatch(Set, HttpServletRequest)} is invoked.
   *
   * @param lookupPath mapping lookup path within the current servlet mapping if applicable
   * @param request the current HTTP servlet request
   * @return the best-matching handler method, or {@code null} if there is no match
   */
  protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request)
      throws Exception {
    List<T> mappings = urlMap.get(lookupPath);
    if (mappings == null) {
      mappings = new ArrayList<T>(handlerMethods.keySet());
    }

    List<Match> matches = new ArrayList<Match>();

    for (T mapping : mappings) {
      T match = getMatchingMapping(mapping, request);
      if (match != null) {
        matches.add(new Match(match, handlerMethods.get(mapping)));
      }
    }

    if (!matches.isEmpty()) {
      Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
      Collections.sort(matches, comparator);

      if (logger.isTraceEnabled()) {
        logger.trace(
            "Found "
                + matches.size()
                + " matching mapping(s) for ["
                + lookupPath
                + "] : "
                + matches);
      }

      Match bestMatch = matches.get(0);
      if (matches.size() > 1) {
        Match secondBestMatch = matches.get(1);
        if (comparator.compare(bestMatch, secondBestMatch) == 0) {
          Method m1 = bestMatch.handlerMethod.getMethod();
          Method m2 = secondBestMatch.handlerMethod.getMethod();
          throw new IllegalStateException(
              "Ambiguous handler methods mapped for HTTP path '"
                  + request.getRequestURL()
                  + "': {"
                  + m1
                  + ", "
                  + m2
                  + "}");
        }
      }

      handleMatch(bestMatch.mapping, lookupPath, request);
      return bestMatch.handlerMethod;
    } else {
      return handleNoMatch(handlerMethods.keySet(), lookupPath, request);
    }
  }
 public MultiValueMap<String, Connection<?>> findConnectionsToUsers(
     MultiValueMap<String, String> providerUsers) {
   if (providerUsers == null || providerUsers.isEmpty()) {
     throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
   }
   StringBuilder providerUsersCriteriaSql = new StringBuilder();
   MapSqlParameterSource parameters = new MapSqlParameterSource();
   parameters.addValue("userId", userId);
   for (Iterator<Entry<String, List<String>>> it = providerUsers.entrySet().iterator();
       it.hasNext(); ) {
     Entry<String, List<String>> entry = it.next();
     String providerId = entry.getKey();
     providerUsersCriteriaSql
         .append("providerId = :providerId_")
         .append(providerId)
         .append(" and providerUserId in (:providerUserIds_")
         .append(providerId)
         .append(")");
     parameters.addValue("providerId_" + providerId, providerId);
     parameters.addValue("providerUserIds_" + providerId, entry.getValue());
     if (it.hasNext()) {
       providerUsersCriteriaSql.append(" or ");
     }
   }
   List<Connection<?>> resultList =
       new NamedParameterJdbcTemplate(jdbcTemplate)
           .query(
               selectFromUserConnection()
                   + " where userId = :userId and "
                   + providerUsersCriteriaSql
                   + " order by providerId, rank",
               parameters,
               connectionMapper);
   MultiValueMap<String, Connection<?>> connectionsForUsers =
       new LinkedMultiValueMap<String, Connection<?>>();
   for (Connection<?> connection : resultList) {
     String providerId = connection.getKey().getProviderId();
     List<String> userIds = providerUsers.get(providerId);
     List<Connection<?>> connections = connectionsForUsers.get(providerId);
     if (connections == null) {
       connections = new ArrayList<Connection<?>>(userIds.size());
       for (int i = 0; i < userIds.size(); i++) {
         connections.add(null);
       }
       connectionsForUsers.put(providerId, connections);
     }
     String providerUserId = connection.getKey().getProviderUserId();
     int connectionIndex = userIds.indexOf(providerUserId);
     connections.set(connectionIndex, connection);
   }
   return connectionsForUsers;
 }
  /**
   * Decode the given matrix variables unless {@link #setUrlDecode(boolean)} is set to {@code true}
   * in which case it is assumed the URL path from which the variables were extracted is already
   * decoded through a call to {@link #getLookupPathForRequest(ServerWebExchange)}.
   *
   * @param exchange current exchange
   * @param vars URI variables extracted from the URL path
   * @return the same Map or a new Map instance
   */
  public MultiValueMap<String, String> decodeMatrixVariables(
      ServerWebExchange exchange, MultiValueMap<String, String> vars) {

    if (this.urlDecode) {
      return vars;
    }
    MultiValueMap<String, String> decodedVars = new LinkedMultiValueMap<>(vars.size());
    for (String key : vars.keySet()) {
      for (String value : vars.get(key)) {
        decodedVars.add(key, decode(exchange, value));
      }
    }
    return decodedVars;
  }
Exemplo n.º 20
0
 @Override
 public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
   if (context.getEnvironment() != null) {
     MultiValueMap<String, Object> attrs =
         metadata.getAllAnnotationAttributes(Profile.class.getName());
     if (attrs != null) {
       for (Object value : attrs.get("value")) {
         if (context.getEnvironment().acceptsProfiles(((String[]) value))) {
           return true;
         }
       }
       return false;
     }
   }
   return true;
 }
Exemplo n.º 21
0
  @Test
  public void testImplicitGrant() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("source", "credentials");
    postBody.add("username", user.getUserName());
    postBody.add("password", secret);

    ResponseEntity<Void> responseEntity =
        restOperations.exchange(
            loginUrl + "/oauth/authorize",
            HttpMethod.POST,
            new HttpEntity<>(postBody, headers),
            Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents =
        UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation()).build();
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(
        Arrays.asList(scopes),
        containsInAnyOrder(
            "scim.userids",
            "password.write",
            "cloud_controller.write",
            "openid",
            "cloud_controller.read",
            "uaa.user"));

    validateToken("access_token", params.toSingleValueMap(), scopes, aud);
    validateToken("id_token", params.toSingleValueMap(), openid, new String[] {"cf"});
  }
 /** Return a {@link HandlerMapping} with mapped {@link HttpRequestHandler}s. */
 public AbstractHandlerMapping getHandlerMapping() {
   Map<String, Object> urlMap = new LinkedHashMap<>();
   for (ServletWebSocketHandlerRegistration registration : this.registrations) {
     MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
     for (HttpRequestHandler httpHandler : mappings.keySet()) {
       for (String pattern : mappings.get(httpHandler)) {
         urlMap.put(pattern, httpHandler);
       }
     }
   }
   WebSocketHandlerMapping hm = new WebSocketHandlerMapping();
   hm.setUrlMap(urlMap);
   hm.setOrder(this.order);
   if (this.urlPathHelper != null) {
     hm.setUrlPathHelper(this.urlPathHelper);
   }
   return hm;
 }
Exemplo n.º 23
0
  private static MultiValueMap<String, String> validateRelationship(
      MultiValueMap<String, String> unresolvedRelations, Field field, RelationshipHolder holder) {
    List<String> relatedClasses = unresolvedRelations.get(holder.getRelatedClass());

    if (relatedClasses != null
        && relatedClasses.contains(field.getEntity().getClassName())
        && StringUtils.isEmpty(holder.getRelatedField())) {
      throw new InvalidRelationshipException(
          holder.getRelatedClass(), field.getEntity().getClassName());
    }

    if (holder.hasUnresolvedRelation()
        && !field.getEntity().getClassName().equals(holder.getRelatedClass())) {
      unresolvedRelations.add(field.getEntity().getClassName(), holder.getRelatedClass());
    }

    return unresolvedRelations;
  }
 @Test
 @SuppressWarnings("unchecked")
 public void getRequestOk() throws Exception {
   MockHttpServletRequest request = new MockHttpServletRequest();
   request.setMethod("GET");
   request.setParameter("foo", "bar");
   MockHttpServletResponse response = new MockHttpServletResponse();
   defaultAdapter.handleRequest(request, response);
   assertEquals(HttpServletResponse.SC_OK, response.getStatus());
   Message<?> message = requests.receive(0);
   assertNotNull(message);
   Object payload = message.getPayload();
   assertTrue(payload instanceof MultiValueMap);
   MultiValueMap<String, String> map = (MultiValueMap<String, String>) payload;
   assertEquals(1, map.size());
   assertEquals("foo", map.keySet().iterator().next());
   assertEquals(1, map.get("foo").size());
   assertEquals("bar", map.getFirst("foo"));
   assertNotNull(TestUtils.getPropertyValue(defaultAdapter, "errorChannel"));
 }
Exemplo n.º 25
0
  @Override
  public MultiValueMap<String, Connection<?>> findConnectionsToUsers(
      MultiValueMap<String, String> providerUsers) {
    if (providerUsers == null || providerUsers.isEmpty()) {
      throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
    }

    List<Connection<?>> allConnections =
        providerUsers
            .entrySet()
            .stream()
            .flatMap(
                entry ->
                    entry
                        .getValue()
                        .stream()
                        .map(u -> LdoD.getInstance().getUserConnection(userId, entry.getKey(), u)))
            .sorted((uc1, uc2) -> compareByProviderIdAndRank(uc1, uc2))
            .map(uc -> mapUserConnection(uc))
            .collect(Collectors.toList());

    MultiValueMap<String, Connection<?>> connectionsForUsers =
        new LinkedMultiValueMap<String, Connection<?>>();
    for (Connection<?> connection : allConnections) {
      String providerId = connection.getKey().getProviderId();
      List<String> userIds = providerUsers.get(providerId);
      List<Connection<?>> connections = connectionsForUsers.get(providerId);
      if (connections == null) {
        connections = new ArrayList<Connection<?>>(userIds.size());
        for (int i = 0; i < userIds.size(); i++) {
          connections.add(null);
        }
        connectionsForUsers.put(providerId, connections);
      }
      String providerUserId = connection.getKey().getProviderUserId();
      int connectionIndex = userIds.indexOf(providerUserId);
      connections.set(connectionIndex, connection);
    }
    return connectionsForUsers;
  }
 @Test
 public void getAllAnnotationAttributesOnClassWithLocalAnnotation() {
   MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(TxConfig.class, TX_NAME);
   assertNotNull("Annotation attributes map for @Transactional on TxConfig", attributes);
   assertEquals("value for TxConfig.", asList("TxConfig"), attributes.get("value"));
 }