/**
  * 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));
 }
Пример #2
0
 public static String buildAgentUrl(String hostname, String subPath) {
   UriComponentsBuilder ub = UriComponentsBuilder.newInstance();
   ub.scheme(ApplianceVmGlobalProperty.AGENT_URL_SCHEME);
   if (CoreGlobalProperty.UNIT_TEST_ON) {
     ub.host("localhost");
   } else {
     ub.host(hostname);
   }
   ub.port(ApplianceVmGlobalProperty.AGENT_PORT);
   if (!"".equals(ApplianceVmGlobalProperty.AGENT_URL_ROOT_PATH)) {
     ub.path(ApplianceVmGlobalProperty.AGENT_URL_ROOT_PATH);
   }
   ub.path(subPath);
   return ub.build().toUriString();
 }
  /**
   * 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);
  }
Пример #4
0
  @RequestMapping(value = "/app/", method = RequestMethod.POST)
  public ResponseEntity<App> createApp(@RequestBody App app, UriComponentsBuilder ucBuilder) {
    System.out.println("Creating App " + app.getTitle());

    if (this.api.getAppService().isExist(app)) {
      System.out.println("A app with name " + app.getTitle() + " already exist");
      return new ResponseEntity<App>(HttpStatus.CONFLICT);
    }

    app = this.api.getAppService().createApp(app);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/app/{appid}").buildAndExpand(app.getAppid()).toUri());

    ObjectMapper mapper = new ObjectMapper();
    try {
      String jsonString = mapper.writeValueAsString(app);
      System.out.print(jsonString);
    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return new ResponseEntity<App>(app, headers, HttpStatus.CREATED);
  }
Пример #5
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();
  }
Пример #6
0
  @RequestMapping(value = "/submit", method = RequestMethod.POST)
  public String index(
      @Valid @ModelAttribute("orderForm") OrderFormDTO orderForm,
      Model m,
      BindingResult result,
      RedirectAttributes redirectAttributes,
      UriComponentsBuilder uriBuilder) {

    List<Long> serviceIds = orderForm.getServiceIds();
    List<Long> tireIds = orderForm.getTireIds();
    OrderDTO order = new OrderDTO();

    for (Long tireId : tireIds) {
      OrderItemDTO tireItem = new OrderItemDTO();
      tireItem.setItem(tireFacade.getTireById(tireId));
      order.addOrderItem(tireItem);
    }

    for (Long serviceId : serviceIds) {
      OrderItemDTO serviceItem = new OrderItemDTO();
      serviceItem.setItem(serviceFacade.findServiceById(serviceId));
      order.addOrderItem(serviceItem);
    }

    String email = orderForm.getEmail();
    if (email != null) {
      CustomerDTO customer = new CustomerDTO();
      customer.setEmail(email);
      customerFacade.createCustomer(customer);
    }

    redirectAttributes.addFlashAttribute("alert_success", "Order was successfully submitted");
    return "redirect:" + uriBuilder.path("/").toUriString();
  }
Пример #7
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();
  }
Пример #8
0
  protected final void findAllRedirectToPagination(
      final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
    final String resourceName = clazz.getSimpleName().toString().toLowerCase();
    final String locationValue =
        uriBuilder.path("/" + resourceName).build().encode().toUriString() + "?page=0&size=10";

    response.setHeader(HttpHeaders.LOCATION, locationValue);
  }
 /**
  * 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));
 }
 /**
  * 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));
 }
Пример #11
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();
 }
 /**
  * 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));
 }
 /**
  * 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);
 }
 /**
  * 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));
 }
 /**
  * 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));
 }
Пример #19
0
 @RequestMapping(value = "player", method = RequestMethod.POST)
 public ResponseEntity<Void> createPlayer(
     @RequestBody Player player, UriComponentsBuilder ucBuilder) {
   logger.info(String.format("Creating player %s", player));
   if (playerService.exists(player)) {
     logger.info(String.format("Player exists | %s", player));
     return new ResponseEntity<>(HttpStatus.CONFLICT);
   }
   playerService.createPlayer(player);
   HttpHeaders headers = new HttpHeaders();
   headers.setLocation(ucBuilder.path("/player/{id}").buildAndExpand(player.getId()).toUri());
   return new ResponseEntity<>(headers, HttpStatus.CREATED);
 }
 /**
  * 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);
 }
  @RequestMapping(method = RequestMethod.POST)
  @ResponseStatus(HttpStatus.CREATED)
  ResponseEntity<Equipment> postEquipment(
      @RequestBody Equipment equipment, UriComponentsBuilder uriBuilder) {

    Equipment created = equipmentService.createEquipment(equipment);
    URI location =
        uriBuilder.path("api/schedule/{id}").buildAndExpand(created.getEquipmentId()).toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(location);

    return new ResponseEntity<>(created, headers, HttpStatus.CREATED);
  }
  @RequestMapping(method = RequestMethod.POST, consumes = "application/json")
  @ResponseStatus(HttpStatus.CREATED)
  public ResponseEntity<BasePlayer> savePlayer(
      @RequestBody BasePlayer player, UriComponentsBuilder ucb) {
    BasePlayer saved = playerRepository.save(player);

    HttpHeaders headers = new HttpHeaders();
    URI locationUri = ucb.path("/player/").path(saved.getLastName()).build().toUri();
    headers.setLocation(locationUri);

    ResponseEntity<BasePlayer> responseEntity =
        new ResponseEntity<BasePlayer>(saved, headers, HttpStatus.CREATED);
    return responseEntity;
  }
Пример #23
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();
  }
 @RequestMapping(value = "/{appName}/rules", method = RequestMethod.POST)
 @ResponseStatus(HttpStatus.CREATED)
 public void createRule(
     @PathVariable String appName,
     @RequestBody AutoscalingRuleResource rule,
     UriComponentsBuilder builder,
     HttpServletResponse response) {
   autoscalingManager.addAutoscaleRule(appName, rule.getName(), rule.getRule());
   String uriString =
       builder
           .path("/autoscaledapps/{appName}/rules/{ruleName}")
           .buildAndExpand(appName, rule.getName())
           .toUriString();
   response.setHeader("location", uriString);
 }
  /**
   * 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()));
      }
    };
  }
 /**
  * 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 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));
 }
Пример #28
0
  @RequestMapping(method = RequestMethod.POST, consumes = MediaTypes.JSON)
  public ResponseEntity<?> create(@RequestBody Task task, UriComponentsBuilder uriBuilder) {
    // 调用JSR303 Bean Validator进行校验, 异常将由RestExceptionHandler统一处理.
    BeanValidators.validateWithException(validator, task);

    // 保存任务
    taskService.saveTask(task);

    // 按照Restful风格约定,创建指向新任务的url, 也可以直接返回id或对象.
    Long id = task.getId();
    URI uri = uriBuilder.path("/api/v1/task/" + id).build().toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uri);

    return new ResponseEntity(headers, HttpStatus.CREATED);
  }
  @RequestMapping(value = "api/Document/", method = RequestMethod.POST)
  public ResponseEntity<Void> createDocument(
      @RequestBody Document Document, UriComponentsBuilder ucBuilder) {
    System.out.println("Creating Document " + Document.getFilename());

    if (documentService.isDocumentExist(Document)) {
      System.out.println("A Document with name " + Document.getFilename() + " already exist");
      return new ResponseEntity<Void>(HttpStatus.CONFLICT);
    }

    documentService.saveDocument(Document);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/Document/{id}").buildAndExpand(Document.getId()).toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
  }
 @RequestMapping(method = RequestMethod.POST)
 @ResponseStatus(HttpStatus.CREATED)
 public void autoscaleApplication(
     @RequestBody AutoscaledApplicationResource autoscaledApplicationResource,
     UriComponentsBuilder builder,
     HttpServletResponse response) {
   autoscalingManager.autoscaleApplication(
       autoscaledApplicationResource.getAppName(),
       autoscaledApplicationResource.getAutoScalingPolicy());
   String uriString =
       builder
           .path("/autoscaledapps/{appName}")
           .buildAndExpand(autoscaledApplicationResource.getAppName())
           .toUriString();
   response.setHeader("location", uriString);
 }