예제 #1
0
  @PUT
  public Response putItem(@Context HttpHeaders headers, byte[] data) {
    System.out.println("PUT ITEM " + container + " " + item);

    URI uri = uriInfo.getAbsolutePath();
    MediaType mimeType = headers.getMediaType();
    GregorianCalendar gc = new GregorianCalendar();
    gc.set(GregorianCalendar.MILLISECOND, 0);
    Item i = new Item(item, uri.toString(), mimeType.toString(), gc);
    String digest = computeDigest(data);
    i.setDigest(digest);

    Response r;
    if (!MemoryStore.MS.hasItem(container, item)) {
      r = Response.created(uri).build();
    } else {
      r = Response.noContent().build();
    }

    Item ii = MemoryStore.MS.createOrUpdateItem(container, i, data);
    if (ii == null) {
      // Create the container if one has not been created
      URI containerUri = uriInfo.getAbsolutePathBuilder().path("..").build().normalize();
      Container c = new Container(container, containerUri.toString());
      MemoryStore.MS.createContainer(c);
      i = MemoryStore.MS.createOrUpdateItem(container, i, data);
      if (i == null) throw new NotFoundException("Container not found");
    }

    return r;
  }
예제 #2
0
  /**
   * Builds a paged result out of a list of items and additional information.
   *
   * @param <T> result type
   * @param list bare list of items to be returned
   * @param page current page
   * @param size requested size
   * @param totalCount total result size (not considering pagination)
   * @return paged result
   */
  protected <T extends AbstractBaseBean> PagedResult<T> buildPagedResult(
      final List<T> list, final int page, final int size, final int totalCount) {

    PagedResult<T> result = new PagedResult<>();
    result.getResult().addAll(list);

    result.setPage(page);
    result.setSize(result.getResult().size());
    result.setTotalCount(totalCount);

    UriBuilder builder = uriInfo.getAbsolutePathBuilder();
    MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
    for (Map.Entry<String, List<String>> queryParam : queryParams.entrySet()) {
      builder.queryParam(queryParam.getKey(), queryParam.getValue().toArray());
    }

    if (result.getPage() > 1) {
      result.setPrev(
          builder
              .replaceQueryParam(PARAM_PAGE, result.getPage() - 1)
              .replaceQueryParam(PARAM_SIZE, size)
              .build());
    }
    if ((result.getPage() - 1) * size + result.getSize() < totalCount) {
      result.setNext(
          builder
              .replaceQueryParam(PARAM_PAGE, result.getPage() + 1)
              .replaceQueryParam(PARAM_SIZE, size)
              .build());
    }

    return result;
  }
  /**
   * Creates a new job on the Links Discovery Component.
   *
   * @param id the job identifier associated with this instance.
   * @return a response which includes the info of the new job.
   * @since 1.0
   */
  @POST
  @Path("/jobs")
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public Response newJob(
      @Context final HttpServletRequest request, @FormParam("jobid") final Integer jobid) {

    LOGGER.debug(MessageCatalog._00021_NEW_JOB_REQUEST);

    if (jobid == null) {
      LOGGER.error(MessageCatalog._00022_MISSING_INPUT_PARAM, "jobid");
      return Response.status(Status.BAD_REQUEST).build();
    }

    // Get configuration parameters
    final DBConnectionManager dbConn = (DBConnectionManager) context.getAttribute("db");
    final JobConfiguration jobConf = dbConn.getJobConfiguration(jobid);
    if (jobConf == null) {
      LOGGER.error(MessageCatalog._00023_JOB_CONFIGURATION_NOT_FOUND, jobid);
      return Response.status(Status.BAD_REQUEST).build();
    }
    final DDBBParams ddbbParams = new DDBBParams();
    ddbbParams.setUsername(context.getInitParameter("ddbb.username"));
    ddbbParams.setPassword(context.getInitParameter("ddbb.password"));
    ddbbParams.setDriverClassName(context.getInitParameter("ddbb.driverClassName"));
    ddbbParams.setUrl(context.getInitParameter("ddbb.url"));
    // Program linking processes
    final LinksDiscovery linksDisc = new LinksDiscovery();
    final Job job = linksDisc.programLinkingProcesses(jobConf, dbConn, ddbbParams);

    return Response.created(uriInfo.getAbsolutePathBuilder().build()).entity(job).build();
  }
  private UriInfo setUpCmdExpectations(
      String[] commands, String[] returns, String collectionType, String newId, boolean build)
      throws Exception {
    mockStatic(PowerShellCmd.class);
    for (int i = 0; i < Math.min(commands.length, returns.length); i++) {
      if (commands[i] != null) {
        expect(PowerShellCmd.runCommand(setUpPoolExpectations(), commands[i]))
            .andReturn(returns[i]);
      }
    }

    UriInfo uriInfo = null;
    if (collectionType != null && newId != null) {
      uriInfo = setUpBasicUriExpectations();
      if (build) {
        UriBuilder uriBuilder = createMock(UriBuilder.class);
        expect(uriInfo.getAbsolutePathBuilder()).andReturn(uriBuilder);
        expect(uriBuilder.path(newId)).andReturn(uriBuilder);
        expect(uriBuilder.build())
            .andReturn(new URI("vms/" + VM_ID + "/" + collectionType + "/" + newId))
            .anyTimes();
      }
    }

    replayAll();

    return uriInfo;
  }
예제 #5
0
 @POST
 public Response create(
     @Context HttpHeaders headers,
     @QueryParam("durable") Boolean durable,
     @QueryParam("expiration") Long expiration,
     @QueryParam("priority") Integer priority,
     @Context UriInfo uriInfo,
     byte[] body) {
   try {
     boolean isDurable = defaultDurable;
     if (durable != null) {
       isDurable = durable.booleanValue();
     }
     publish(headers, body, isDurable, expiration, priority);
   } catch (Exception e) {
     Response error =
         Response.serverError()
             .entity("Problem posting message: " + e.getMessage())
             .type("text/plain")
             .build();
     throw new WebApplicationException(e, error);
   }
   Response.ResponseBuilder builder = Response.status(201);
   UriBuilder nextBuilder = uriInfo.getAbsolutePathBuilder();
   URI next = nextBuilder.build();
   serviceManager
       .getLinkStrategy()
       .setLinkHeader(builder, "create-next", "create-next", next.toString(), "*/*");
   return builder.build();
 }
예제 #6
0
 /**
  * Create cluster configuration.
  *
  * @param cluster contains the cluster information to create
  * @param uriInfo For gathering information about the request
  * @return The created cluster
  * @throws GenieException For any error
  */
 @POST
 @Consumes(MediaType.APPLICATION_JSON)
 @ApiOperation(
     value = "Create a cluster",
     notes = "Create a cluster from the supplied information.",
     response = Cluster.class)
 @ApiResponses(
     value = {
       @ApiResponse(
           code = HttpURLConnection.HTTP_CREATED,
           message = "Created",
           response = Cluster.class),
       @ApiResponse(
           code = HttpURLConnection.HTTP_CONFLICT,
           message = "A cluster with the supplied id already exists"),
       @ApiResponse(
           code = HttpURLConnection.HTTP_PRECON_FAILED,
           message = "Invalid required parameter supplied"),
       @ApiResponse(
           code = HttpURLConnection.HTTP_INTERNAL_ERROR,
           message = "Genie Server Error due to Unknown Exception")
     })
 public Response createCluster(
     @ApiParam(value = "The cluster to create.", required = true) final Cluster cluster,
     @Context UriInfo uriInfo)
     throws GenieException {
   LOG.info("Called to create new cluster " + cluster);
   final Cluster createdCluster = this.ccs.createCluster(cluster);
   return Response.created(uriInfo.getAbsolutePathBuilder().path(createdCluster.getId()).build())
       .entity(createdCluster)
       .build();
 }
예제 #7
0
 protected org.json.JSONArray getRestResponse(@Context UriInfo uriInfo, String category)
     throws UnirestException {
   return Unirest.post(uriInfo.getAbsolutePathBuilder().path(NewsGetter.class) + category)
       .asJson()
       .getBody()
       .getArray();
 }
예제 #8
0
  @POST
  public Response addMessage(Message message, @Context UriInfo uriInfo) {
    Message newMessage = messageService.addMessage(message);
    String newId = String.valueOf(newMessage.getId());
    URI uri = uriInfo.getAbsolutePathBuilder().path(newId).build();

    return Response.created(uri).entity(newMessage).build();
  }
예제 #9
0
 /**
  * This is the only non-idempotent method.
  *
  * @param stream a valid SXCML file
  * @return a Location header containing the UUID of the create machine
  */
 @POST
 @Produces(MediaType.APPLICATION_JSON)
 @Consumes(MediaType.APPLICATION_XML)
 public Response define(InputStream stream, @Context UriInfo info) {
   String id = this.dm.create(stream);
   URI uri = info.getAbsolutePathBuilder().path("/" + id).build();
   return Response.created(uri).build();
 }
예제 #10
0
  @POST
  public Response addComment(
      @PathParam("messageId") long messageId, @Context UriInfo uriInfo, Comment comment) {
    Comment newComment = commentService.addComment(messageId, comment);

    URI uri = uriInfo.getAbsolutePathBuilder().path(String.valueOf(newComment.getId())).build();
    return Response.created(uri).entity(newComment).build();
  }
예제 #11
0
  /**
   * Builds response to successful {@code create} request, taking into account any {@code Prefer}
   * header.
   *
   * @param provisioningResult the entity just created
   * @return response to successful {@code create} request
   */
  protected Response createResponse(final ProvisioningResult<?> provisioningResult) {
    String entityId = provisioningResult.getEntity().getKey();
    Response.ResponseBuilder builder =
        Response.created(uriInfo.getAbsolutePathBuilder().path(entityId).build())
            .header(RESTHeaders.RESOURCE_KEY, entityId);

    return applyPreference(provisioningResult, builder).build();
  }
예제 #12
0
 JsonObject createCacheLinks(UriInfo info, String name) {
   JsonObjectBuilder response = Json.createObjectBuilder();
   UriBuilder cacheLink = info.getAbsolutePathBuilder().path(name);
   UriBuilder entries = cacheLink.path("entries");
   response.add("name", name);
   response.add("link", cacheLink.build().toASCIIString());
   response.add("entries", entries.build().toASCIIString());
   return response.build();
 }
예제 #13
0
 /**
  * Creates a new History resource from the provided representation
  *
  * @return an instance of PublicHistoryTO
  */
 @POST
 @Consumes({"application/json"})
 public Response createResource(PublicHistoryTO newHistoryTO) {
   History newHistory = new History();
   historiesTOService.updateHistoryEntity(newHistory, newHistoryTO);
   long newHistoryId = historiesManager.create(newHistory);
   URI createdURI = context.getAbsolutePathBuilder().path(Long.toString(newHistoryId)).build();
   return Response.created(createdURI).build();
 }
예제 #14
0
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  public Response createOAuthClient(
      final @Context UriInfo uriInfo, final OAuthClientRepresentation rep) {
    auth.requireManage();

    OAuthClientManager resourceManager = new OAuthClientManager(realm);
    OAuthClientModel oauth = resourceManager.create(rep);
    return Response.created(uriInfo.getAbsolutePathBuilder().path(oauth.getId()).build()).build();
  }
예제 #15
0
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 @ApiOperation(
     value = "Get all available sitemaps.",
     response = SitemapDTO.class,
     responseContainer = "Collection")
 @ApiResponses(value = {@ApiResponse(code = 200, message = "OK")})
 public Response getSitemaps() {
   logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath());
   Object responseObject = getSitemapBeans(uriInfo.getAbsolutePathBuilder().build());
   return Response.ok(responseObject).build();
 }
예제 #16
0
 @Override
 @PUT
 @Path("/workitem")
 public Response updateWorkItem(WorkItem workItem) {
   try {
     WorkItem updatedWorkItem = ticketSystemService.updateWorkItem(workItem);
     final URI location = uriInfo.getAbsolutePathBuilder().path(updatedWorkItem.getName()).build();
     return Response.created(location).build();
   } catch (final TicketSystemServiceException exception) {
     return Response.status(400).entity(exception).build();
   }
 }
예제 #17
0
 @Override
 @POST
 @Path("/user")
 public Response addUser(final User user) {
   try {
     ticketSystemService.addUser(user);
     final URI location = uriInfo.getAbsolutePathBuilder().path(user.getUserID()).build();
     return Response.created(location).build();
   } catch (final TicketSystemServiceException exception) {
     return Response.status(400).entity(exception).build();
   }
 }
예제 #18
0
 @Override
 @POST
 @Path("/issue")
 public Response addIssue(final Issue issue) {
   try {
     ticketSystemService.addIssue(issue);
     final URI location = uriInfo.getAbsolutePathBuilder().path("" + issue.getId()).build();
     return Response.created(location).build();
   } catch (final TicketSystemServiceException exception) {
     return Response.status(400).entity(exception).build();
   }
 }
예제 #19
0
 @Override
 @POST
 @Path("/team")
 public Response addTeam(final Team team) {
   try {
     ticketSystemService.addTeam(team);
     final URI location = uriInfo.getAbsolutePathBuilder().path(team.getTeamName()).build();
     return Response.created(location).build();
   } catch (final TicketSystemServiceException exception) {
     return Response.status(400).entity(exception).build();
   }
 }
예제 #20
0
 @GET
 @Produces({MediaType.WILDCARD})
 public Response getSitemaps(
     @Context HttpHeaders headers,
     @QueryParam("type") String type,
     @QueryParam("jsoncallback") @DefaultValue("callback") String callback) {
   logger.debug(
       "Received HTTP GET request at '{}' for media type '{}'.",
       new String[] {uriInfo.getPath(), type});
   String responseType =
       MediaTypeHelper.getResponseMediaType(headers.getAcceptableMediaTypes(), type);
   if (responseType != null) {
     Object responseObject =
         responseType.equals(MediaTypeHelper.APPLICATION_X_JAVASCRIPT)
             ? new JSONWithPadding(
                 new SitemapListBean(getSitemapBeans(uriInfo.getAbsolutePathBuilder().build())),
                 callback)
             : new SitemapListBean(getSitemapBeans(uriInfo.getAbsolutePathBuilder().build()));
     return Response.ok(responseObject, responseType).build();
   } else {
     return Response.notAcceptable(null).build();
   }
 }
  /**
   * Create new authenticator configuration
   *
   * @param rep JSON describing new authenticator configuration
   * @deprecated Use {@link #newExecutionConfig(String, AuthenticatorConfigRepresentation)} instead
   */
  @Path("config")
  @POST
  @NoCache
  public Response createAuthenticatorConfig(AuthenticatorConfigRepresentation rep) {
    auth.requireManage();

    AuthenticatorConfigModel config =
        realm.addAuthenticatorConfig(RepresentationToModel.toModel(rep));
    adminEvent
        .operation(OperationType.CREATE)
        .resourcePath(uriInfo, config.getId())
        .representation(rep)
        .success();
    return Response.created(uriInfo.getAbsolutePathBuilder().path(config.getId()).build()).build();
  }
예제 #22
0
  /**
   * GET method implementation. Lists the available caches
   *
   * @return
   */
  @GET
  public Caches getCaches() {
    LOG.info("GET Caches");

    String[] cacheNames = CacheManager.getInstance().getCacheNames();

    List<Cache> cacheList = new ArrayList<Cache>();

    for (String cacheName : cacheNames) {
      URI cacheUri = uriInfo.getAbsolutePathBuilder().path(cacheName).build().normalize();
      Cache cache = new Cache(cacheName, cacheUri.toString());
      cacheList.add(cache);
    }

    return new Caches(cacheList);
  }
  @Test
  public void shouldCreateTodoItem() throws Exception {
    final TodoItem todoItem = createTodoItem();
    final UriInfo uriInfo = mock(UriInfo.class);
    final UriBuilder uriBuilder = mock(UriBuilder.class);
    final URI todoUri = new URI(baseUri + todoItem.getId());
    given(todoItems.createTodoItem(todoItem.getTitle(), todoItem.getCompleted()))
        .willReturn(todoItem);
    given(uriInfo.getAbsolutePathBuilder()).willReturn(uriBuilder);
    given(uriBuilder.path("/" + todoItem.getId())).willReturn(uriBuilder);
    given(uriBuilder.build()).willReturn(todoUri);

    final Response response = todoItemsResource.createTodoItem(todoItem, uriInfo);

    assertThat(response.getStatus(), is(equalTo(Status.CREATED)));
  }
  @Test
  public void shouldCreateRecord() throws Exception {

    RecordPayload recordPayload = RecordPayload.instanceOf(7);

    when(mockService.create(argThat(isRecord(null, 7)))).thenReturn(TEST_ID);
    when(mockUriInfo.getAbsolutePathBuilder())
        .thenReturn(UriBuilder.fromPath("http://localhost:8080/services/webapi/myresource"));

    Response response = recordResource.createRecord(recordPayload);

    assertThat(
        response.getLocation().toString(),
        is("http://localhost:8080/services/webapi/myresource/a02"));
    assertThat(response.getStatus(), is(HttpStatus.CREATED.value()));
  }
 @GET
 @Path(PASSWORD_RESET_REQUEST_PATH + "{username}")
 @PermitAll
 public Response sendPasswordResetLink(
     @PathParam("username") String username, @Context UriInfo url) {
   // url contains password reset request path, replace it with password reset path and send mail
   // using that path
   String basePath = url.getAbsolutePathBuilder().build().toString();
   basePath = basePath.replace(PASSWORD_RESET_REQUEST_PATH, PASSWORD_RESET_PATH);
   boolean linkIsSend = userManager.sendPasswordResetLink(username, basePath);
   if (linkIsSend) {
     return Response.status(Response.Status.OK).build();
   } else {
     return Response.status(Response.Status.NOT_FOUND).build();
   }
 }
  // new Android
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response registerAndroidVariant(
      AndroidVariant androidVariant,
      @PathParam("pushAppID") String pushApplicationID,
      @Context UriInfo uriInfo,
      @Context HttpServletRequest request) {

    // find the root push app
    PushApplication pushApp =
        pushAppService.findByPushApplicationIDForDeveloper(
            pushApplicationID, request.getUserPrincipal().getName());

    if (pushApp == null) {
      return Response.status(Status.NOT_FOUND)
          .entity("Could not find requested PushApplicationEntity")
          .build();
    }

    // some validation
    try {
      validateModelClass(androidVariant);
    } catch (ConstraintViolationException cve) {

      // Build and return the 400 (Bad Request) response
      ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations());

      return builder.build();
    }

    // store the "developer:
    androidVariant.setDeveloper(request.getUserPrincipal().getName());

    // store the Android variant:
    variantService.addVariant(androidVariant);
    // add iOS variant, and merge:
    pushAppService.addAndroidVariant(pushApp, androidVariant);

    return Response.created(
            uriInfo
                .getAbsolutePathBuilder()
                .path(String.valueOf(androidVariant.getVariantID()))
                .build())
        .entity(androidVariant)
        .build();
  }
  @POST
  public Response createSurveyPoint(SurveyPoint pSurveyPoint) {
    if (pSurveyPoint == null) throw new RuntimeException("got no data!");

    WeatherSurveyPointTO surveyPointTO = new WeatherSurveyPointTO();
    surveyPointTO.setAirPressure(pSurveyPoint.getAirPressure());
    surveyPointTO.setDate(pSurveyPoint.getDate().toGregorianCalendar().getTime());
    surveyPointTO.setDevice(pSurveyPoint.getDevice());
    surveyPointTO.setHumidity(pSurveyPoint.getHumidity());
    surveyPointTO.setIlluminance(pSurveyPoint.getIlluminance());
    surveyPointTO.setTemperature(pSurveyPoint.getTemperature());

    int id = myWeatherSurveyRepositoryLocal.save(surveyPointTO);

    URI uri = uriInfo.getAbsolutePathBuilder().path(Integer.toString(id)).build();
    return Response.created(uri).build();
  }
예제 #28
0
 public Response listAllResources(String typeName, UriInfo uri) {
   LinkedHashMap<String, String> resourceNameData = new LinkedHashMap<>();
   Iterator<org.cristalise.kernel.lookup.Path> iter =
       Gateway.getLookup()
           .search(new DomainPath("/desc/" + typeName), new Property("Type", typeName));
   while (iter.hasNext()) {
     ItemPath schemaPath = (ItemPath) iter.next();
     try {
       ItemProxy proxy = Gateway.getProxyManager().getProxy(schemaPath);
       String name = proxy.getName();
       resourceNameData.put(name, uri.getAbsolutePathBuilder().path(name).build().toString());
     } catch (ObjectNotFoundException e) {
       resourceNameData.put(schemaPath.getUUID().toString(), "Name not found");
     }
   }
   return toJSON(resourceNameData);
 }
 @VisibleForTesting
 public URI getLocationURI(List<String> guids) {
   URI locationURI = null;
   if (uriInfo != null) {
     UriBuilder ub = uriInfo.getAbsolutePathBuilder();
     locationURI = guids.isEmpty() ? null : ub.path(guids.get(0)).build();
   } else {
     String uriPath = AtlasClient.API.GET_ENTITY.getPath();
     locationURI =
         guids.isEmpty()
             ? null
             : UriBuilder.fromPath(AtlasConstants.DEFAULT_ATLAS_REST_ADDRESS)
                 .path(uriPath)
                 .path(guids.get(0))
                 .build();
   }
   return locationURI;
 }
  /**
   * Update execution with new configuration
   *
   * @param execution Execution id
   * @param json JSON with new configuration
   * @return
   */
  @Path("/executions/{executionId}/config")
  @POST
  @NoCache
  @Consumes(MediaType.APPLICATION_JSON)
  public Response newExecutionConfig(
      @PathParam("executionId") String execution, AuthenticatorConfigRepresentation json) {
    auth.requireManage();

    AuthenticationExecutionModel model = realm.getAuthenticationExecutionById(execution);
    if (model == null) {
      session.getTransaction().setRollbackOnly();
      throw new NotFoundException("Illegal execution");
    }
    AuthenticatorConfigModel config = RepresentationToModel.toModel(json);
    config = realm.addAuthenticatorConfig(config);
    model.setAuthenticatorConfig(config.getId());
    realm.updateAuthenticatorExecution(model);

    json.setId(config.getId());
    adminEvent.operation(OperationType.CREATE).resourcePath(uriInfo).representation(json).success();
    return Response.created(uriInfo.getAbsolutePathBuilder().path(config.getId()).build()).build();
  }