javax.ws.rs.PUT Java Examples

The following examples show how to use javax.ws.rs.PUT. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BelongAPI.java    From hugegraph with Apache License 2.0 7 votes vote down vote up
@PUT
@Timed
@Path("{id}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON_WITH_CHARSET)
public String update(@Context GraphManager manager,
                     @PathParam("graph") String graph,
                     @PathParam("id") String id,
                     JsonBelong jsonBelong) {
    LOG.debug("Graph [{}] update belong: {}", graph, jsonBelong);
    checkUpdatingBody(jsonBelong);

    HugeGraph g = graph(manager, graph);
    HugeBelong belong;
    try {
        belong = manager.userManager().getBelong(UserAPI.parseId(id));
    } catch (NotFoundException e) {
        throw new IllegalArgumentException("Invalid belong id: " + id);
    }
    belong = jsonBelong.build(belong);
    manager.userManager().updateBelong(belong);
    return manager.serializer(g).writeUserElement(belong);
}
 
Example #2
Source File: CustomerResource.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response putUser(JsonObject jsonEntity) {
	String jsonId = jsonEntity.getString(Customer.KEY_CUSTOMER_ID);

	if ((jsonId != null) && !jsonId.equals(id)) {
		return Response.status(409).entity("customerIds differ!\n").build();
	}

	// If we have no customer, this is an insert, otherwise an update
	final boolean newRecord = (null == customer);

	String fullName = jsonEntity.getString(Customer.KEY_FULL_NAME);
	String phoneNumber = jsonEntity.getString(Customer.KEY_PHONE_NUMBER);

	if (newRecord) {
		// We're allowing inserts here, but ID will be generated (i.e. we will ignore 
		// the ID provided by the path)
		DataAccess.createCustomer(fullName, phoneNumber);
		return Response.created(uriInfo.getAbsolutePath()).build();
	} else {
		DataAccess.updateCustomer(Long.valueOf(jsonId), fullName, phoneNumber);
		return Response.noContent().build();
	}
}
 
Example #3
Source File: BucketEndpoint.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@PUT
public Response put(@PathParam("bucket") String bucketName, @Context
    HttpHeaders httpHeaders) throws IOException, OS3Exception {

  try {
    String location = createS3Bucket(bucketName);
    LOG.info("Location is {}", location);
    return Response.status(HttpStatus.SC_OK).header("Location", location)
        .build();
  } catch (OMException exception) {
    LOG.error("Error in Create Bucket Request for bucket: {}", bucketName,
        exception);
    if (exception.getResult() == ResultCodes.INVALID_BUCKET_NAME) {
      throw S3ErrorTable.newError(S3ErrorTable.INVALID_BUCKET_NAME,
          bucketName);
    }
    throw exception;
  }
}
 
Example #4
Source File: LRAUnknownResource.java    From microprofile-lra with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/complete")
@Produces(MediaType.APPLICATION_JSON)
@Complete
public Response completeWork(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId)
        throws NotFoundException {
    lraMetricService.incrementMetric(LRAMetricType.Completed, lraId);

    // flow for the following cases
    // Scenario.COMPLETE_RETRY
    // -> /complete -> 202
    // -> /complete -> 410 (recalled to find final status by implementation)

    // Scenario.COMPLETE_IMMEDIATE
    // -> /complete -> 410

    int responseCode = 410;
    Scenario scenario = scenarioMap.get(lraId.toASCIIString());
    if (scenario == Scenario.COMPLETE_RETRY) {
        responseCode = 202; // The 'action' is in progress
        scenarioMap.remove(lraId.toASCIIString()); // so that by next call the return status is 410.
    }

    LOGGER.info(String.format("LRA id '%s' was completed", lraId.toASCIIString()));
    return Response.status(responseCode).build();
}
 
Example #5
Source File: FruitResource.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@PUT
@Path("{id}")
@Transactional
public Fruit update(@PathParam Integer id, Fruit fruit) {
    if (fruit.getName() == null) {
        throw new WebApplicationException("Fruit Name was not set on request.", 422);
    }

    Fruit entity = entityManager.find(Fruit.class, id);

    if (entity == null) {
        throw new WebApplicationException("Fruit with id of " + id + " does not exist.", 404);
    }

    entity.setName(fruit.getName());

    return entity;
}
 
Example #6
Source File: TeamRestApi.java    From submarine with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/edit")
@SubmarineApi
public Response edit(Team team) {
  LOG.info("edit team:{}", team.toString());

  // TODO(zhulinhao): need set update_by value
  try {
    // update team
    teamService.updateByPrimaryKeySelective(team);

    // TODO(zhulinhao)
    // Save inviter=0 in the newly added member and the invitation
    // message to join the team that has not been sent into the message
    // table sys_message to avoid sending the invitation message repeatedly

  } catch (Exception e) {
    return new JsonResponse.Builder<>(Response.Status.OK).success(false)
        .message("Update team failed!").build();
  }

  return new JsonResponse.Builder<>(Response.Status.OK)
      .message("Update team successfully!").success(true).build();
}
 
Example #7
Source File: HealthElementFacade.java    From icure-backend with GNU General Public License v2.0 6 votes vote down vote up
@ApiOperation(
		value = "Modify a health element",
		response = HealthElementDto.class,
		httpMethod = "PUT",
		notes = "Returns the modified health element."
)
@PUT
public Response modifyHealthElement(HealthElementDto healthElementDto) {
	if (healthElementDto == null) {
		return Response.status(400).type("text/plain").entity("A required query parameter was not specified for this request.").build();
	}


	healthElementLogic.modifyHealthElement(mapper.map(healthElementDto, HealthElement.class));
	HealthElement modifiedHealthElement = healthElementLogic.getHealthElement(healthElementDto.getId());

	boolean succeed = (modifiedHealthElement != null);
	if (succeed) {
		return Response.ok().entity(mapper.map(modifiedHealthElement, HealthElementDto.class)).build();
	} else {
		return Response.status(500).type("text/plain").entity("Health element modification failed.").build();
	}
}
 
Example #8
Source File: VariablesAPI.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@PUT
@Timed
@Path("{key}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON_WITH_CHARSET)
public Map<String, Object> update(@Context GraphManager manager,
                                  @PathParam("graph") String graph,
                                  @PathParam("key") String key,
                                  JsonVariableValue value) {
    E.checkArgument(value != null && value.data != null,
                    "The variable value can't be empty");
    LOG.debug("Graph [{}] set variable for {}: {}", graph, key, value);

    HugeGraph g = graph(manager, graph);
    commit(g, () -> g.variables().set(key, value.data));
    return ImmutableMap.of(key, value.data);
}
 
Example #9
Source File: UsersResource.java    From Java-EE-8-and-Angular with MIT License 6 votes vote down vote up
@PUT
@Path("{id}")
@ApiOperation(value = "Update user", response = User.class)
@ApiResponses(value = {
    @ApiResponse(code = 400, message = "Invalid user input")
    ,
  @ApiResponse(code = 404, message = "User not found")
    ,
  @ApiResponse(code = 200, message = "User updated")})
public Response update(@ApiParam(value = "ID of user that needs to be updated",
        required = true)
        @PathParam("id") Long id,
        @ApiParam(value = "User that needs to be updated", required = true) User updated) {
    updated.setId(id);
    boolean done = service.update(updated);

    return done
            ? Response.ok(updated).build()
            : Response.status(Response.Status.NOT_FOUND).build();
}
 
Example #10
Source File: GroupAPI.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@PUT
@Timed
@Path("{id}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON_WITH_CHARSET)
public String update(@Context GraphManager manager,
                     @PathParam("graph") String graph,
                     @PathParam("id") String id,
                     JsonGroup jsonGroup) {
    LOG.debug("Graph [{}] update group: {}", graph, jsonGroup);
    checkUpdatingBody(jsonGroup);

    HugeGraph g = graph(manager, graph);
    HugeGroup group;
    try {
        group = manager.userManager().getGroup(UserAPI.parseId(id));
    } catch (NotFoundException e) {
        throw new IllegalArgumentException("Invalid group id: " + id);
    }
    group = jsonGroup.build(group);
    manager.userManager().updateGroup(group);
    return manager.serializer(g).writeUserElement(group);
}
 
Example #11
Source File: MachineLearningResourceV2.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/{token}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response tokenPut(@PathParam("token") String token, @Valid List<ReportMessageDescriptor> body) {
    try {
        HttpSession session = httpRequest.getSession();
        String sessionKey = token;

        SessionStorage sessionStorage = (SessionStorage)session.getAttribute(sessionKey);

        if (sessionStorage == null) {
            return Response.status(Status.UNAUTHORIZED).build();
        }

        sessionStorage.addUserMark(body);

        return Response.ok().build();
    } catch (Exception ex) {
        logger.error("unable to process ml data", ex);
        return Response.serverError().entity("server error: " + ex.toString()).build();
    }
}
 
Example #12
Source File: ParticipatingTckResource.java    From microprofile-lra with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/complete")
@Complete
public Response completeWork(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId, String userData) {
    if(lraId == null) {
        throw new NullPointerException("lraId can't be null as it should be invoked with the context");
    }

    LOGGER.info(String.format("LRA id '%s' was told to complete", lraId));

    return getEndPhaseResponse(true, lraId);
}
 
Example #13
Source File: Nodes.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@PUT
@Path("{nodeName}/config")
public void setConfig(
    @Context
    Request request,
    @Suspended final AsyncResponse asyncResponse,
    @PathParam("nodeName")
    String nodeName,
    String jsonData
)
{
    Flux<ApiCallRc> flux = Flux.empty();
    try
    {
        JsonGenTypes.SatelliteConfig config = objectMapper
            .readValue(jsonData, JsonGenTypes.SatelliteConfig.class);
        SatelliteConfigPojo conf = new SatelliteConfigPojo(config);
        flux = ctrlNodeApiCallHandler.setConfig(nodeName, conf)
            .subscriberContext(requestHelper.createContext(InternalApiConsts.API_MOD_STLT_CONFIG, request));

    }
    catch (IOException ioExc)
    {
        ApiCallRcRestUtils.handleJsonParseException(ioExc, asyncResponse);
    }
    catch (AccessDeniedException e)
    {
        requestHelper
            .doFlux(asyncResponse, ApiCallRcRestUtils.mapToMonoResponse(flux, Response.Status.UNAUTHORIZED));
    }
    requestHelper.doFlux(asyncResponse, ApiCallRcRestUtils.mapToMonoResponse(flux, Response.Status.OK));
}
 
Example #14
Source File: HealthcarePartyFacade.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
@ApiOperation(
		value = "Modify a Healthcare Party.",
		response = HealthcarePartyDto.class,
		httpMethod = "PUT",
		notes = "No particular return value. It's just a message."
)
@PUT
public Response modifyHealthcareParty(HealthcarePartyDto healthcarePartyDto) {
	if (healthcarePartyDto == null) {
		return Response.status(400).type("text/plain").entity("A required query parameter was not specified for this request.").build();
	}

	try {
		healthcarePartyLogic.modifyHealthcareParty(mapper.map(healthcarePartyDto, HealthcareParty.class));
		HealthcareParty modifiedHealthcareParty = healthcarePartyLogic.getHealthcareParty(healthcarePartyDto.getId());

		boolean succeed = (modifiedHealthcareParty != null);
		if (succeed) {
			return Response.ok().entity(mapper.map(modifiedHealthcareParty, HealthcarePartyDto.class)).build();
		} else {
			return Response.status(500).type("text/plain").entity("Modification of the healthcare party failed. Read the server log.").build();
		}
	} catch (MissingRequirementsException e) {
		logger.warn(e.getMessage(), e);
		return Response.status(400).type("text/plain").entity(e.getMessage()).build();
	}
}
 
Example #15
Source File: LraResource.java    From microprofile-lra with Apache License 2.0 5 votes vote down vote up
@PUT
@Path(LraResource.ACCEPT_WORK)
@LRA(value = LRA.Type.REQUIRED, end = false)
public Response acceptWork(
        @HeaderParam(LRA_HTTP_RECOVERY_HEADER) URI recoveryId,
        @HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId) {

    assertHeaderPresent(lraId, LRA_HTTP_CONTEXT_HEADER);
    assertHeaderPresent(recoveryId, LRA_HTTP_RECOVERY_HEADER);

    Activity activity = storeActivity(lraId, recoveryId);

    activity.setAcceptedCount(1); // later tests that it is possible to asynchronously complete
    return Response.ok(lraId).build();
}
 
Example #16
Source File: LraResource.java    From microprofile-lra with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/compensate")
@Produces(MediaType.APPLICATION_JSON)
@Compensate
public Response compensateWork(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId,
                               @HeaderParam(LRA_HTTP_RECOVERY_HEADER) URI recoveryId,
                               String userData) {

    assertHeaderPresent(lraId, LRA_HTTP_CONTEXT_HEADER); // the TCK expects the implementation to invoke @Compensate methods
    assertHeaderPresent(recoveryId, LRA_HTTP_RECOVERY_HEADER); // the TCK expects the implementation to invoke @Compensate methods

    lraMetricService.incrementMetric(LRAMetricType.Compensated, lraId, LraResource.class.getName());

    Activity activity = activityStore.getActivityAndAssertExistence(lraId, context);

    activity.setEndData(userData);

    if (activity.getAndDecrementAcceptCount() > 0) {
        activity.setStatus(ParticipantStatus.Compensating);
        activity.setStatusUrl(String.format("%s/%s/%s/status", context.getBaseUri(),
                LRA_RESOURCE_PATH, lraId));

        return Response.accepted().location(URI.create(activity.getStatusUrl())).build();
    }

    activity.setStatus(ParticipantStatus.Compensated);
    activity.setStatusUrl(String.format("%s/%s/activity/compensated", context.getBaseUri(), lraId));

    LOGGER.info(String.format("LRA id '%s' was compensated", lraId));
    return Response.ok(activity.getStatusUrl()).build();
}
 
Example #17
Source File: HibernateSearchTestResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/init-data")
@Transactional
public void initData() {
    createPerson("John Irving", "Burlington");
    createPerson("David Lodge", "London");
    createPerson("Paul Auster", "New York");
    createPerson("John Grisham", "Oxford");
}
 
Example #18
Source File: FruitResource.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/id/{id}/color/{color}")
@Produces("application/json")
public Fruit changeColor(@PathParam Long id, @PathParam String color) {
    Optional<Fruit> optional = fruitRepository.findById(id);
    if (optional.isPresent()) {
        Fruit fruit = optional.get();
        fruit.setColor(color);
        return fruitRepository.save(fruit);
    }

    throw new IllegalArgumentException("No Fruit with id " + id + " exists");
}
 
Example #19
Source File: ParticipatingTckResource.java    From microprofile-lra with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/compensate")
@Compensate
public Response compensateWork(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId, String userData) {
    if(lraId == null) {
        throw new NullPointerException("lraId can't be null as it should be invoked with the context");
    }

    LOGGER.info(String.format("LRA id '%s' was told to compensate", lraId));

    return getEndPhaseResponse(false, lraId);
}
 
Example #20
Source File: EventsResource.java    From cantor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@PUT
@Path("/{namespace}")
@Operation(summary = "Create an event namespace")
@ApiResponses(value = {
    @ApiResponse(responseCode = "200", description = "Event namespace was successfully created or already existed"),
    @ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response createNamespace(@Parameter(description = "Namespace identifier") @PathParam("namespace") final String namespace) throws IOException {
    logger.info("received request for creation of namespace {}", namespace);
    this.cantor.events().create(namespace);
    return Response.ok().build();
}
 
Example #21
Source File: CourseChapterService.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@PUT
@Path("/")
@Consumes(APPLICATION_JSON)
void setChapters(
        @HeaderParam(AUTHORIZATION) AuthHeader authHeader,
        @PathParam("courseJid") String courseJid,
        List<CourseChapter> data);
 
Example #22
Source File: LibraryResource.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("author")
@Transactional
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void addAuthor(@FormParam String firstName, @FormParam String lastName) {
    Author author = new Author();
    author.firstName = firstName;
    author.lastName = lastName;
    author.persist();
}
 
Example #23
Source File: RestDocumentService.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
@PUT
@Path("/move")
@ApiOperation(value = "Moves an existing document with the given identifier")
public void move(@QueryParam("docId") @ApiParam(value = "Document ID", required = true) long docId,
		@QueryParam("folderId") @ApiParam(value = "Target Folder ID", required = true) long folderId)
		throws Exception {
	String sid = validateSession();
	super.move(sid, docId, folderId);
}
 
Example #24
Source File: ContextTckResource.java    From microprofile-lra with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/complete")
@Complete
public Response completeWork(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId,
                             @HeaderParam(LRA_HTTP_PARENT_CONTEXT_HEADER) URI parent) {
    lraMetricService.incrementMetric(LRAMetricType.Completed, lraId);
    if (parent != null) {
        lraMetricService.incrementMetric(LRAMetricType.Nested, parent);
    }

    return getEndPhaseResponse(true);
}
 
Example #25
Source File: ParticipatingTckResource.java    From microprofile-lra with Apache License 2.0 5 votes vote down vote up
@PUT
@Path(LEAVE_PATH)
@LRA(value = LRA.Type.SUPPORTS, end = false)
@Leave
public Response leaveLRA() {
    return Response.ok().build();
}
 
Example #26
Source File: ShoppingListApi.java    From commerce-cif-api with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/{id}/entries/{entryId}")
@ApiOperation(value = "Replaces an entry with the given one.")
@ApiResponses(value = {
    @ApiResponse(code = HTTP_BAD_REQUEST, message = HTTP_BAD_REQUEST_MESSAGE, response = ErrorResponse.class),
    @ApiResponse(code = HTTP_UNAUTHORIZED, message = HTTP_UNAUTHORIZED_MESSAGE, response = ErrorResponse.class),
    @ApiResponse(code = HTTP_NOT_FOUND, message = HTTP_NOT_FOUND_MESSAGE, response = ErrorResponse.class)
})
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
ShoppingListEntry putShoppingListEntry(
    @ApiParam(value = "The id of the shopping list.", required = true)
    @PathParam("id")
    String id,

    @ApiParam(value = "The id of the entry to replace.", required = true)
    @PathParam("entryId")
    String entryId,

    @ApiParam(value = "The quantity for the new entry.", required = true)
    @FormParam("quantity")
    @Min(value = 0)
    int quantity,

    @ApiParam(value = "The product variant id to be added to the entry. If the product variant exists in another entry in the shopping list, this request fails.", required = true)
    @FormParam("productVariantId")
    String productVariantId,

    @ApiParam(value = ACCEPT_LANGUAGE_DESC)
    @HeaderParam(ACCEPT_LANGUAGE) String acceptLanguage
);
 
Example #27
Source File: MessageFacade.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
@ApiOperation(
		value = "Set read status for given list of messages",
		httpMethod = "PUT",
		responseContainer = "List",
		response = MessageDto.class
)
@PUT
@Path("/readstatus")
public Response setMessagesReadStatus(MessagesReadStatusUpdate data) throws MissingRequirementsException {
	return ResponseUtils.ok(messageLogic.setReadStatus(data.getIds(), data.getUserId(), data.getStatus(), data.getTime() ).stream().map(m->mapper.map(m,MessageDto.class)).collect(Collectors.toList()));
}
 
Example #28
Source File: KuduResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/insert")
@PUT
public Response insert() {
    LOG.info("Calling insert");

    Map<String, Object> row = new HashMap<>();
    row.put("id", "key1");
    row.put("name", "Samuel");

    producerTemplate.requestBody("direct:insert", row);

    return Response.ok().build();
}
 
Example #29
Source File: TaskResource.java    From osgi-best-practices with Apache License 2.0 5 votes vote down vote up
@Operation(description =  "Change task")
@PUT
@Path("{id}")
public void updateTask(@PathParam("id") Integer id, Task task) {
    if (!task.getId().equals(id)) {
        throw new IllegalStateException("Id from path and content must be the same");
    }
    taskService.addOrUpdate(task);
}
 
Example #30
Source File: ResourceDefinitions.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("{rscName}")
public void modifyResourceDefinition(
    @Context Request request,
    @Suspended final AsyncResponse asyncResponse,
    @PathParam("rscName") String rscName,
    String jsonData
)
    throws IOException
{
    JsonGenTypes.ResourceDefinitionModify modifyData =
        objectMapper.readValue(jsonData, JsonGenTypes.ResourceDefinitionModify.class);

    Flux<ApiCallRc> flux = ctrlApiCallHandler.modifyRscDfn(
        null,
        rscName,
        modifyData.drbd_port,
        modifyData.override_props,
        new HashSet<>(modifyData.delete_props),
        new HashSet<>(modifyData.delete_namespaces),
        modifyData.layer_stack,
        modifyData.drbd_peer_slots == null ? null : modifyData.drbd_peer_slots.shortValue()
    )
    .subscriberContext(requestHelper.createContext(ApiConsts.API_MOD_RSC_DFN, request));

    requestHelper.doFlux(asyncResponse, ApiCallRcRestUtils.mapToMonoResponse(flux, Response.Status.OK));
}