@Test
  public void testStatusUpdatingMessageHandler() {
    TimelineOperations timelineOperations = Mockito.mock(TimelineOperations.class);
    Mockito.when(this.twitter.timelineOperations()).thenReturn(timelineOperations);

    ArgumentCaptor<TweetData> argument = ArgumentCaptor.forClass(TweetData.class);

    this.in1.send(new GenericMessage<String>("foo"));

    Mockito.verify(timelineOperations).updateStatus(argument.capture());
    assertEquals("foo", argument.getValue().toRequestParameters().getFirst("status"));

    Mockito.reset(timelineOperations);

    ClassPathResource media = new ClassPathResource("log4j.properties");
    this.in2.send(
        MessageBuilder.withPayload(Collections.singletonMap("foo", "bar"))
            .setHeader("media", media)
            .build());

    Mockito.verify(timelineOperations).updateStatus(argument.capture());
    TweetData tweetData = argument.getValue();
    MultiValueMap<String, Object> requestParameters = tweetData.toRequestParameters();
    assertEquals("bar", requestParameters.getFirst("status"));
    assertNull(requestParameters.getFirst("media"));
    MultiValueMap<String, Object> uploadMediaParameters = tweetData.toUploadMediaParameters();
    assertEquals(media, uploadMediaParameters.getFirst("media"));
  }
Exemplo n.º 2
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"));
  }
  private void saveConditionalURIs(String hash, MultiValueMap<String, String> params) {

    logger.info("Iterating through conditional params (if there are)");

    String ifurl = "ifurl";
    String expr = "expr";

    int paramn = 1;

    String firstparam = ifurl + paramn;
    String secondparam = expr + paramn;

    while ((params.getFirst(firstparam) != null && params.getFirst(secondparam) != null)
        && (!params.getFirst(firstparam).equals("") && !params.getFirst(secondparam).equals(""))) {
      logger.info(
          "Seeking url&expression -- "
              + firstparam
              + params.getFirst(firstparam)
              + secondparam
              + params.getFirst(secondparam));
      MultiplesURIs mu =
          new MultiplesURIs(hash, params.getFirst(firstparam), params.getFirst(secondparam));
      multiplesURIsRepository.save(mu);

      paramn++;
      firstparam = ifurl + paramn;
      secondparam = expr + paramn;
    }

    logger.info("Already cicled around " + paramn + " conditional params");
  }
Exemplo n.º 4
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"});
  }
 @RequestMapping(
     value = "/headers/{headerKey:.+}",
     method = RequestMethod.GET,
     produces = {MediaType.APPLICATION_JSON_VALUE})
 public String getFirstHeader(
     @PathVariable("headerKey") String headerKey,
     @RequestHeader MultiValueMap<String, String> headers) {
   return headers.getFirst(headerKey);
 }
  @Test
  public void resolveArgumentRawTypeFromParameterizedType() throws Exception {
    String content = "fruit=apple&vegetable=kale";
    this.servletRequest.setContent(content.getBytes("UTF-8"));
    this.servletRequest.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE);

    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(new AllEncompassingFormHttpMessageConverter());
    RequestResponseBodyMethodProcessor processor =
        new RequestResponseBodyMethodProcessor(converters);

    @SuppressWarnings("unchecked")
    MultiValueMap<String, String> result =
        (MultiValueMap<String, String>)
            processor.resolveArgument(paramMultiValueMap, mavContainer, webRequest, binderFactory);

    assertNotNull(result);
    assertEquals("apple", result.getFirst("fruit"));
    assertEquals("kale", result.getFirst("vegetable"));
  }
Exemplo n.º 7
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;
   }
 }
 protected final String getCallbackParam(ServerHttpRequest request) {
   String query = request.getURI().getQuery();
   MultiValueMap<String, String> params =
       UriComponentsBuilder.newInstance().query(query).build().getQueryParams();
   String value = params.getFirst("c");
   if (StringUtils.isEmpty(value)) {
     return null;
   }
   try {
     String result = UriUtils.decode(value, "UTF-8");
     return (CALLBACK_PARAM_PATTERN.matcher(result).matches() ? result : null);
   } catch (UnsupportedEncodingException ex) {
     // should never happen
     throw new SockJsException("Unable to decode callback query parameter", null, ex);
   }
 }
 @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"));
 }
  @RequestMapping(value = "/link", method = RequestMethod.POST)
  public ResponseEntity<?> shortener(
      @RequestParam("url") String url,
      @RequestParam(value = "sponsor", required = false) String sponsor,
      @RequestParam(value = "brand", required = false) String brand,
      @RequestParam(value = "urlName", required = false) String name,
      @RequestParam("username") String username,
      @RequestParam(value = "advert", required = false) String advertisement,
      @RequestParam(value = "max", required = false) String max,
      @RequestParam MultiValueMap<String, String> params,
      HttpServletRequest request,
      Principal currentUser,
      Model model) {
    logger.info("Requested new short for uri " + url);
    sponsor = "http://localhost:8080/advert";

    boolean useConditional = false;
    // Comprobamos si se usan URIs condicionales
    if (params.getFirst("ifurl1") != null
        && !params.getFirst("ifurl1").equals("")
        && params.getFirst("expr1") != null
        && !params.getFirst("expr1").equals("")) {
      useConditional = true;
    }

    logger.info("Name (hash) is " + name);
    // Si se usan URIs condicionales pero no hay url estandar,
    // se crea un hash usando las targets de las condicionales
    if (name.equals("") && url.equals("") && useConditional) {
      logger.info("There are Conditional URIs but no default target" + name);
      String ifurl = "ifurl";
      String expr = "expr";
      String nueva = "a";

      int paramn = 1;

      String firstparam = ifurl + paramn;
      String secondparam = expr + paramn;

      while ((params.getFirst(firstparam) != null && params.getFirst(secondparam) != null)
          && (!params.getFirst(firstparam).equals("")
              && !params.getFirst(secondparam).equals(""))) {
        nueva += params.getFirst(firstparam);

        paramn++;
        firstparam = ifurl + paramn;
        secondparam = expr + paramn;
      }

      name =
          Hashing.murmur3_32()
              .hashString(url + username + nueva, StandardCharsets.UTF_8)
              .toString();
      while (shortURLRepositoryExtended.findByHash(name, username) != null) {
        // seguir creando
        name =
            Hashing.murmur3_32()
                .hashString(url + username + "" + nueva, StandardCharsets.UTF_8)
                .toString();
        nueva += "a";
      }
    }

    // Si no existe una hash (id or name) se crea una
    else if (name.equals("")) {
      name = Hashing.murmur3_32().hashString(url + username, StandardCharsets.UTF_8).toString();
      String nueva = "a";
      while (shortURLRepositoryExtended.findByHash(name, username) != null) {
        // seguir creando
        name =
            Hashing.murmur3_32()
                .hashString(url + username + "" + nueva, StandardCharsets.UTF_8)
                .toString();
        nueva += "a";
      }
    }
    logger.info("After name (hash) is " + name);

    boolean advert = false;
    int seconds = 0;
    if (advertisement != null) {
      advert = true;
      if (!max.equals("")) {
        seconds = Integer.valueOf(max);
        if (seconds < 1) {
          seconds = 5;
        }
      }
    }

    if (shortURLRepositoryExtended.findByHash(name, username) != null
        && url != null
        && !url.equals("")) {
      ArrayList<String> sufijos = new ArrayList<String>(); // contiene todos los sufijos
      sufijos.add("ada");
      sufijos.add("aco");
      sufijos.add("ado");
      JSONArray arr = new JSONArray();
      JSONObject tmp;
      try {
        for (int i = 0; i < sufijos.size(); i++) {
          ShortURL l = shortURLRepositoryExtended.findByHash(name + "" + sufijos.get(i), username);
          if (l == null) {
            // No existe en la BD, luego no esta cogido
            tmp = new JSONObject();
            tmp.put("name", name + "" + sufijos.get(i));
            arr.put(tmp);
          }
        }
      } catch (Exception e) {
      }
      String devueltos = "'{\"names\":" + arr.toString() + "}'";

      RiWordnet wordnet = new RiWordnet();

      // Crea 10 sinonimos
      String[] poss = wordnet.getPos(name);
      /*
       * for (int j = 0; j < poss.length; j++) {
       * System.out.println("\n\nSynonyms for " + name + " (pos: " +
       * poss[j] + ")");
       */
      JSONArray sinonimos = new JSONArray();
      try {
        String[] synonyms = wordnet.getAllSynonyms(name, poss[0], 10);
        Arrays.sort(synonyms);
        JSONObject tmpo;
        for (int i = 0; i < synonyms.length; i++) {
          ShortURL l = shortURLRepositoryExtended.findByHash(synonyms[i], username);
          if (l == null) {
            // No existe en la BD, luego no esta cogido
            tmpo = new JSONObject();
            tmpo.put("synonym", synonyms[i]);
            sinonimos.put(tmpo);
          }
        }
      } catch (Exception e) {
      }
      String synDevueltos = "'{\"synonyms\":" + sinonimos.toString() + "}'";
      String respuesta = devueltos + "separa" + synDevueltos;
      return new ResponseEntity<>(respuesta, HttpStatus.NOT_ACCEPTABLE);
    } else {
      ShortURL su =
          createAndSaveIfValid(
              url,
              sponsor,
              brand,
              UUID.randomUUID().toString(),
              extractIP(request),
              name,
              username,
              advert,
              seconds,
              useConditional);
      if (su != null) {
        HttpHeaders h = new HttpHeaders();
        h.setLocation(su.getUri());

        saveConditionalURIs(name, params);

        return new ResponseEntity<>(su, h, HttpStatus.CREATED);
      } else {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
      }
    }
  }