/**
  * Retrieve the attribute of an entity
  *
  * @param entityId the entity ID
  * @param type optional entity type to avoid ambiguity when multiple entities have the same ID,
  *     null or zero-length for empty
  * @param attributeName the attribute name
  * @return
  */
 public ListenableFuture<Object> getAttributeValue(
     String entityId, String type, String attributeName) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/entities/{entityId}/attrs/{attributeName}/value");
   addParam(builder, "type", type);
   return adapt(
       request(
           HttpMethod.GET,
           builder.buildAndExpand(entityId, attributeName).toUriString(),
           null,
           Object.class));
 }
  /**
   * Retrieve a list of Entities
   *
   * @param ids an optional list of entity IDs (cannot be used with idPatterns)
   * @param idPattern an optional pattern of entity IDs (cannot be used with ids)
   * @param types an optional list of types of entity
   * @param attrs an optional list of attributes to return for all entities
   * @param query an optional Simple Query Language query
   * @param geoQuery an optional Geo query
   * @param orderBy an option list of attributes to difine the order of entities
   * @param offset an optional offset (0 for none)
   * @param limit an optional limit (0 for none)
   * @param count true to return the total number of matching entities
   * @return a pagined list of Entities
   */
  public ListenableFuture<Paginated<Entity>> getEntities(
      Collection<String> ids,
      String idPattern,
      Collection<String> types,
      Collection<String> attrs,
      String query,
      GeoQuery geoQuery,
      Collection<String> orderBy,
      int offset,
      int limit,
      boolean count) {

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/entities");
    addParam(builder, "id", ids);
    addParam(builder, "idPattern", idPattern);
    addParam(builder, "type", types);
    addParam(builder, "attrs", attrs);
    addParam(builder, "query", query);
    addGeoQueryParams(builder, geoQuery);
    addParam(builder, "orderBy", orderBy);
    addPaginationParams(builder, offset, limit);
    if (count) {
      addParam(builder, "options", "count");
    }

    return adaptPaginated(
        request(HttpMethod.GET, builder.toUriString(), null, Entity[].class), offset, limit);
  }
  @Override
  public AniServiceDto getByAniService(String aniServiceId, String clientSecret) throws Exception {
    if (StringUtils.isEmpty(aniServiceId) || StringUtils.isEmpty(clientSecret)) {
      throw new Exception("AniServiceId or ClientSecret is null.");
    }

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder
        .append(anicelMeta.getAniServiceBusUrl())
        .append(anicelMeta.getServiceBusGetByUrl())
        .append("/")
        .append(aniServiceId)
        .append("/")
        .append(clientSecret);

    UriComponentsBuilder uriComponentsBuilder =
        UriComponentsBuilder.fromHttpUrl(stringBuilder.toString());
    LOGGER.info(uriComponentsBuilder.toUriString());
    AniServiceHttpMessage result =
        restTemplateFactory
            .getRestTemplate(new Class[] {AniServiceDto.class})
            .getForObject(uriComponentsBuilder.toUriString(), AniServiceHttpMessage.class);

    if (result.getResultCode() == Message.ResultCode.SUCCESS) {
      return result.getReturnObj();
    } else {
      StringBuilder builder =
          new StringBuilder("message: ")
              .append(result.getMsg())
              .append(", error code:")
              .append(result.getResultCode());
      throw new Exception(builder.toString());
    }
  }
 @RequestMapping("/drug/enforcements")
 @ResponseBody
 public JsonNode getDrugRecallsForUnii(
     @RequestParam(value = "unii", defaultValue = "") String unii,
     @RequestParam(value = "limit", defaultValue = "0") int limit)
     throws Exception {
   JsonNode node;
   HttpHeaders headers = new HttpHeaders();
   ObjectMapper mapper = new ObjectMapper();
   headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
   UriComponentsBuilder builder =
       UriComponentsBuilder.fromHttpUrl(searchDrugEnfrcmntUrl)
           .queryParam("limit", uniiRecallsLimit);
   this.apiKey.addToUriComponentsBuilder(builder);
   if (unii != null && unii.trim().length() > 0) {
     builder.queryParam("search", "openfda.unii:" + unii);
     try {
       node = mapper.readTree(rest.getForObject(builder.build().toUri(), String.class));
       ((ObjectNode) node).set("results", getSortedResults(node.get("results"), limit));
     } catch (HttpClientErrorException ex) {
       if (ex.getStatusCode().value() == 404) {
         node =
             new ObjectMapper()
                 .readTree(
                     "{\"error\":{\"code\":\"NOT_FOUND\", \"message\":\"No matches found!\"}}");
       } else {
         throw ex;
       }
     }
   } else {
     node = getDrugRecalls(limit == 0 ? 10 : limit, null, null);
   }
   return node;
 }
  private UriComponents applyContributers(
      UriComponentsBuilder builder,
      Method method,
      Object[] argumentValues,
      Map<String, Object> uriVars) {

    if (this.contributors.isEmpty()) {
      return builder.buildAndExpand(uriVars);
    }

    int paramCount = method.getParameters().length;
    int argCount = argumentValues.length;

    Assert.isTrue(
        paramCount == argCount,
        "Number of method parameters "
            + paramCount
            + " does not match number of argument values "
            + argCount);

    for (int i = 0; i < paramCount; i++) {
      MethodParameter param = new MethodParameter(method, i);
      param.initParameterNameDiscovery(parameterNameDiscoverer);
      for (UriComponentsContributor c : this.contributors) {
        if (c.supportsParameter(param)) {
          c.contributeMethodArgument(
              param, argumentValues[i], builder, uriVars, this.conversionService);
          break;
        }
      }
    }

    return builder.buildAndExpand(uriVars);
  }
  @Override
  public AniServiceDto register(AniServiceRegisterDto registerDto) throws Exception {
    if (!DomainObjectValidator.isDomainObjectValid(registerDto)) {
      throw new ValidationException("Invalid AniServiceRegisterDto Instance.");
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    HttpEntity<AniServiceRegisterDto> requestEntity = new HttpEntity<>(registerDto, httpHeaders);

    UriComponentsBuilder uriComponentsBuilder =
        UriComponentsBuilder.fromHttpUrl(
            anicelMeta.getAniServiceBusUrl() + anicelMeta.getServiceBusRegisterUrl());

    LOGGER.info("post url : {}.", uriComponentsBuilder.toUriString());

    AniServiceHttpMessage result =
        restTemplateFactory
            .getRestTemplate(new Class[] {AniServiceDto.class})
            .postForObject(
                uriComponentsBuilder.toUriString(), requestEntity, AniServiceHttpMessage.class);

    if (result.getResultCode() == Message.ResultCode.SUCCESS) {
      return result.getReturnObj();
    } else {
      StringBuilder builder =
          new StringBuilder("message: ")
              .append(result.getMsg())
              .append(", error code:")
              .append(result.getResultCode());
      throw new Exception(builder.toString());
    }
  }
 public Set<String> getBrandNamesByNameAndUnii(String name, String unii) throws IOException {
   UriComponentsBuilder builder =
       UriComponentsBuilder.fromHttpUrl(this.fdaDrugLabelUrl)
           .queryParam(
               "search",
               "(openfda.unii:"
                   + fixTerm.makeFdaSafe(unii)
                   + ")+AND+(openfda.brand_name:"
                   + fixTerm.makeFdaReady(fixTerm.makeFdaSafe(name))
                   + ")")
           .queryParam("count", "openfda.brand_name.exact");
   this.apiKey.addToUriComponentsBuilder(builder);
   try {
     String result = rest.getForObject(builder.build().toUri(), String.class);
     FieldFinder finder = new FieldFinder("term");
     return finder.find(result);
   } catch (HttpClientErrorException notFound) {
     if (notFound.getStatusCode() == HttpStatus.NOT_FOUND) {
       // server reported 404, handle it by returning no results
       log.warn("No brand name data found for search by name: " + name + " and unii " + unii);
       return Collections.emptySet();
     }
     throw notFound;
   }
 }
示例#8
0
  private String path(UriComponentsBuilder builder, Page page, boolean encode) {
    Map<String, Object> params = new HashMap<>();

    PageTree pageTree =
        (PageTree) processingContext.getContext().getVariables().get("PAGE_TREE_ALL");
    //		PageTree pageTree =
    // defaultModelAttributeService.readPageTree(LocaleContextHolder.getLocale().getLanguage());
    List<String> codes = new LinkedList<>();
    Page parent = page.getParent();
    while (parent != null) {
      codes.add(parent.getCode());
      parent =
          (parent.getParent() != null)
              ? pageTree.getPageByCode(parent.getParent().getCode())
              : null;
    }

    Collections.reverse(codes);
    codes.add(page.getCode());

    for (int i = 0; i < codes.size(); i++) {
      String key = "code" + i;
      builder.path("/{" + key + "}");
      params.put(key, codes.get(i));
    }

    UriComponents components = builder.buildAndExpand(params);
    if (encode) {
      components = components.encode();
    }
    return components.toUriString();
  }
 private void addPaginationParams(UriComponentsBuilder builder, int offset, int limit) {
   if (offset > 0) {
     builder.queryParam("offset", offset);
   }
   if (limit > 0) {
     builder.queryParam("limit", limit);
   }
 }
 private String getHref() {
   UriComponentsBuilder localBuilder = baseComponent.cloneBuilder();
   if (queryString == null) {
     return localBuilder.build().toString();
   } else {
     return localBuilder.query(queryString).build().toString();
   }
 }
 /**
  * Delete an entity
  *
  * @param entityId the entity ID
  * @param type optional entity type to avoid ambiguity when multiple entities have the same ID,
  *     null or zero-length for empty
  * @return the listener to notify of completion
  */
 public ListenableFuture<Void> deleteEntity(String entityId, String type) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/entities/{entityId}");
   addParam(builder, "type", type);
   return adapt(
       request(
           HttpMethod.DELETE, builder.buildAndExpand(entityId).toUriString(), null, Void.class));
 }
 /**
  * Retrieve an entity type
  *
  * @param entityType the entityType to retrieve
  * @return an entity type
  */
 public ListenableFuture<EntityType> getEntityType(String entityType) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/types/{entityType}");
   return adapt(
       request(
           HttpMethod.GET,
           builder.buildAndExpand(entityType).toUriString(),
           null,
           EntityType.class));
 }
 /**
  * Delete the subscription by subscription ID
  *
  * @param subscriptionId the subscription ID
  * @return
  */
 public ListenableFuture<Void> deleteSubscription(String subscriptionId) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/subscriptions/{subscriptionId}");
   return adapt(
       request(
           HttpMethod.DELETE,
           builder.buildAndExpand(subscriptionId).toUriString(),
           null,
           Void.class));
 }
 /**
  * Retrieve the registration by registration ID
  *
  * @param registrationId the registration ID
  * @return registration
  */
 public ListenableFuture<Registration> getRegistration(String registrationId) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/registrations/{registrationId}");
   return adapt(
       request(
           HttpMethod.GET,
           builder.buildAndExpand(registrationId).toUriString(),
           null,
           Registration.class));
 }
 /**
  * Get an entity
  *
  * @param entityId the entity ID
  * @param type optional entity type to avoid ambiguity when multiple entities have the same ID,
  *     null or zero-length for empty
  * @param attrs the list of attributes to retreive for this entity, null or empty means all
  *     attributes
  * @return the entity
  */
 public ListenableFuture<Entity> getEntity(
     String entityId, String type, Collection<String> attrs) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/entities/{entityId}");
   addParam(builder, "type", type);
   addParam(builder, "attrs", attrs);
   return adapt(
       request(
           HttpMethod.GET, builder.buildAndExpand(entityId).toUriString(), null, Entity.class));
 }
示例#16
0
 @RequestMapping("/completion")
 public String completion(
     @Validated OrderForm form,
     @RequestParam(value = "productCode") String productCode,
     UriComponentsBuilder uriBuilder) {
   orderService.order(productCode, form.getQuantity());
   uriBuilder.path("/menu");
   uriBuilder.queryParam("orderedCode", productCode);
   return "redirect:" + uriBuilder.build().toUriString();
 }
 /**
  * Update the registration by registration ID
  *
  * @param registrationId the registration ID
  * @return
  */
 public ListenableFuture<Void> updateRegistration(
     String registrationId, Registration registration) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/registrations/{registrationId}");
   return adapt(
       request(
           HttpMethod.PATCH,
           builder.buildAndExpand(registrationId).toUriString(),
           registration,
           Void.class));
 }
 /**
  * Retrieve a list of entity types
  *
  * @param offset an optional offset (0 for none)
  * @param limit an optional limit (0 for none)
  * @param count true to return the total number of matching entities
  * @return a pagined list of entity types
  */
 public ListenableFuture<Paginated<EntityType>> getEntityTypes(
     int offset, int limit, boolean count) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/types");
   addPaginationParams(builder, offset, limit);
   if (count) {
     addParam(builder, "options", "count");
   }
   return adaptPaginated(
       request(HttpMethod.GET, builder.toUriString(), null, EntityType[].class), offset, limit);
 }
 /**
  * Replace all the existing attributes of an entity with a new set of attributes
  *
  * @param entityId the entity ID
  * @param type optional entity type to avoid ambiguity when multiple entities have the same ID,
  *     null or zero-length for empty
  * @param attributes the new set of attributes
  * @return the listener to notify of completion
  */
 public ListenableFuture<Void> replaceEntity(
     String entityId, String type, Map<String, Attribute> attributes) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/entities/{entityId}");
   addParam(builder, "type", type);
   return adapt(
       request(
           HttpMethod.PUT,
           builder.buildAndExpand(entityId).toUriString(),
           attributes,
           Void.class));
 }
 /**
  * Delete the attribute of an entity
  *
  * @param entityId the entity ID
  * @param type optional entity type to avoid ambiguity when multiple entities have the same ID,
  *     null or zero-length for empty
  * @param attributeName the attribute name
  * @return
  */
 public ListenableFuture<Attribute> deleteAttribute(
     String entityId, String type, String attributeName) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/entities/{entityId}/attrs/{attributeName}");
   addParam(builder, "type", type);
   return adapt(
       request(
           HttpMethod.DELETE,
           builder.buildAndExpand(entityId, attributeName).toUriString(),
           null,
           Attribute.class));
 }
 /**
  * Discover registration matching entities and their attributes
  *
  * @param bulkQueryRequest defines the list of entities, attributes and scopes to match
  *     registrations
  * @param offset an optional offset (0 for none)
  * @param limit an optional limit (0 for none)
  * @param count true to return the total number of matching entities
  * @return a paginated list of registration
  */
 public ListenableFuture<Paginated<Registration>> bulkDiscover(
     BulkQueryRequest bulkQueryRequest, int offset, int limit, boolean count) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/op/discover");
   addPaginationParams(builder, offset, limit);
   if (count) {
     addParam(builder, "options", "count");
   }
   return adaptPaginated(
       request(HttpMethod.POST, builder.toUriString(), bulkQueryRequest, Registration[].class),
       offset,
       limit);
 }
示例#22
0
  private String path(UriComponentsBuilder builder, Article article, boolean encode) {
    Map<String, Object> params = new HashMap<>();
    builder.path("/{year}/{month}/{day}/{code}");
    params.put("year", String.format("%04d", article.getDate().getYear()));
    params.put("month", String.format("%02d", article.getDate().getMonthOfYear()));
    params.put("day", String.format("%02d", article.getDate().getDayOfMonth()));
    params.put("code", article.getCode());

    UriComponents components = builder.buildAndExpand(params);
    if (encode) {
      components = components.encode();
    }
    return components.toUriString();
  }
 private String getHref(int pageParameter) {
   UriComponentsBuilder localBuilder = baseComponent.cloneBuilder();
   if (queryString == null) {
     return localBuilder
         .queryParam(HalResourceMetadata.PARAM_PAGE, pageParameter)
         .build()
         .toString();
   } else {
     return localBuilder
         .query(queryString)
         .queryParam(HalResourceMetadata.PARAM_PAGE, pageParameter)
         .build()
         .toString();
   }
 }
示例#24
0
  @Override
  protected String getAuthorizationUrl(UserRedirectRequiredException exception) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder =
        UriComponentsBuilder.fromUriString(exception.getRedirectUri())
            .queryParam("state", exception.getStateKey())
            .queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code")
            .queryParam("scope", StringUtils.collectionToDelimitedString(resource.getScope(), " "))
            .queryParam("redirect_uri", getCallbackUrl());

    return uriBuilder.build().encode().toUriString();
  }
 /**
  * Retrieve the attribute of an entity
  *
  * @param entityId the entity ID
  * @param type optional entity type to avoid ambiguity when multiple entities have the same ID,
  *     null or zero-length for empty
  * @param attributeName the attribute name
  * @return
  */
 public ListenableFuture<String> getAttributeValueAsString(
     String entityId, String type, String attributeName) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/entities/{entityId}/attrs/{attributeName}/value");
   addParam(builder, "type", type);
   HttpHeaders httpHeaders = cloneHttpHeaders();
   httpHeaders.setAccept(Collections.singletonList(MediaType.TEXT_PLAIN));
   return adapt(
       request(
           HttpMethod.GET,
           builder.buildAndExpand(entityId, attributeName).toUriString(),
           httpHeaders,
           null,
           String.class));
 }
 /**
  * Update existing or append some attributes to an entity
  *
  * @param entityId the entity ID
  * @param type optional entity type to avoid ambiguity when multiple entities have the same ID,
  *     null or zero-length for empty
  * @param attributes the attributes to update or to append
  * @param append if true, will only allow to append new attributes
  * @return the listener to notify of completion
  */
 public ListenableFuture<Void> updateEntity(
     String entityId, String type, Map<String, Attribute> attributes, boolean append) {
   UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
   builder.path("v2/entities/{entityId}");
   addParam(builder, "type", type);
   if (append) {
     addParam(builder, "options", "append");
   }
   return adapt(
       request(
           HttpMethod.POST,
           builder.buildAndExpand(entityId).toUriString(),
           attributes,
           Void.class));
 }
  /**
   * Retrieve the list of all Registrations
   *
   * @return a list of registrations
   */
  public ListenableFuture<List<Registration>> getRegistrations() {

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/registrations");

    ListenableFuture<ResponseEntity<Registration[]>> e =
        request(HttpMethod.GET, builder.toUriString(), null, Registration[].class);
    return new ListenableFutureAdapter<List<Registration>, ResponseEntity<Registration[]>>(e) {
      @Override
      protected List<Registration> adapt(ResponseEntity<Registration[]> result)
          throws ExecutionException {
        return new ArrayList<>(Arrays.asList(result.getBody()));
      }
    };
  }
  public OperationResult execute(Long customerId, CustomerAddress newAddress) throws Exception {

    OperationResult result = null;
    logger.trace("CustomerAddressService.execute");

    Long start = System.currentTimeMillis();

    try {
      RestTemplate restTemplate = new RestTemplate();
      restTemplate
          .getMessageConverters()
          .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_JSON);

      StringBuilder sBuilder =
          new StringBuilder(inventoryServiceURL)
              .append(InventoryServiceActions.ADDRESS)
              .append("/")
              .append(customerId.toString());

      UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(sBuilder.toString());

      String requestJson = new ObjectMapper().writeValueAsString(newAddress);
      HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);

      result =
          restTemplate
              .exchange(
                  builder.build().encode().toString(),
                  HttpMethod.PUT,
                  entity,
                  OperationResult.class)
              .getBody();
      if (result == null) {
        throw new Exception("Unable to get responce from inventory service");
      }
    } catch (Exception ex) {
      logger.warn(ex.getMessage());
      throw ex;
    } finally {
      logger.info(
          "Execution time: " + TimeUnit.MILLISECONDS.toMillis(System.currentTimeMillis() - start));
    }

    return result;
  }
示例#29
0
  private String link(Article article) {
    UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
    Map<String, Object> params = new HashMap<>();

    Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
    if (blog.getLanguages().size() > 1) {
      builder.path("/{language}");
      params.put("language", LocaleContextHolder.getLocale().getLanguage());
    }
    builder.path("/{year}/{month}/{day}/{code}");
    params.put("year", String.format("%04d", article.getDate().getYear()));
    params.put("month", String.format("%02d", article.getDate().getMonthOfYear()));
    params.put("day", String.format("%02d", article.getDate().getDayOfMonth()));
    params.put("code", article.getCode());
    return builder.buildAndExpand(params).encode().toUriString();
  }
 @Override
 public String getSwaggerDocumentationBasePath() {
   return UriComponentsBuilder.fromHttpUrl(getAppBasePath())
       .pathSegment("api-docs/")
       .build()
       .toString();
 }