javax.ws.rs.Consumes#javax.ws.rs.PUT源码实例Demo

下面列出了javax.ws.rs.Consumes#javax.ws.rs.PUT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hugegraph   文件: BelongAPI.java
@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);
}
 
源代码2 项目: Java-EE-8-and-Angular   文件: UsersResource.java
@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();
}
 
源代码3 项目: icure-backend   文件: HealthElementFacade.java
@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();
	}
}
 
源代码4 项目: submarine   文件: TeamRestApi.java
@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();
}
 
源代码5 项目: hadoop-ozone   文件: BucketEndpoint.java
@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;
  }
}
 
源代码6 项目: sailfish-core   文件: MachineLearningResourceV2.java
@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();
    }
}
 
@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();
	}
}
 
源代码8 项目: hugegraph   文件: VariablesAPI.java
@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);
}
 
源代码9 项目: microprofile-lra   文件: LRAUnknownResource.java
@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();
}
 
源代码10 项目: intellij-quarkus   文件: FruitResource.java
@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;
}
 
源代码11 项目: hugegraph   文件: GroupAPI.java
@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);
}
 
源代码12 项目: clouditor   文件: AccountsResource.java
@PUT
@Path("{provider}")
public void putAccount(@PathParam("provider") String provider, CloudAccount account) {
  provider = sanitize(provider);

  try {
    this.service.addAccount(provider, account);
  } catch (IOException ex) {
    throw new BadRequestException(
        Response.status(Status.BAD_REQUEST).entity(ex.getMessage()).build());
  }
}
 
@PUT
@Path(NonParticipatingTckResource.START_BUT_DONT_END_PATH)
@LRA(value = LRA.Type.REQUIRES_NEW, end = false,
        cancelOnFamily = Response.Status.Family.SERVER_ERROR)
public Response startDontEndLRA(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId,
                                @DefaultValue("200") @QueryParam(STATUS_CODE_QUERY_NAME) int coerceStatus) {
    return Response.status(coerceStatus).entity(checkLRANotNull(lraId)).build();
}
 
@PUT
@Path(NonParticipatingTckResource.START_AND_END_PATH)
@LRA(value = LRA.Type.REQUIRES_NEW,
        cancelOnFamily = Response.Status.Family.SERVER_ERROR) // default is to end the LRA
public Response startAndEndLRA(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId,
                               @DefaultValue("200") @QueryParam(STATUS_CODE_QUERY_NAME) int coerceStatus) {
    return Response.status(coerceStatus).entity(checkLRANotNull(lraId)).build();
}
 
源代码15 项目: linstor-server   文件: Nodes.java
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("{nodeName}")
public void modifyNode(
    @Context Request request,
    @Suspended final AsyncResponse asyncResponse,
    @PathParam("nodeName") String nodeName,
    String jsonData
)
{
    try
    {
        JsonGenTypes.NodeModify modifyData = objectMapper.readValue(jsonData, JsonGenTypes.NodeModify.class);

        Flux<ApiCallRc> flux = ctrlApiCallHandler.modifyNode(
            null,
            nodeName,
            modifyData.node_type,
            modifyData.override_props,
            new HashSet<>(modifyData.delete_props),
            new HashSet<>(modifyData.delete_namespaces)
        )
        .subscriberContext(requestHelper.createContext(ApiConsts.API_MOD_NODE, request));

        requestHelper.doFlux(asyncResponse, ApiCallRcRestUtils.mapToMonoResponse(flux, Response.Status.OK));
    }
    catch (IOException ioExc)
    {
        ApiCallRcRestUtils.handleJsonParseException(ioExc, asyncResponse);
    }
}
 
@Override
@PUT
@Path("/lock")
@ApiOperation(value="Locks a document", notes = "Locks an existing document with the given identifier")	
public void lock(@QueryParam("docId") @ApiParam(value = "Document ID", required = true) long docId) throws Exception {
	String sid = validateSession();
	super.lock(sid, docId);
}
 
源代码17 项目: hugegraph   文件: RebuildAPI.java
@PUT
@Timed
@Path("vertexlabels/{name}")
@Status(Status.ACCEPTED)
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RolesAllowed({"admin", "$owner=$graph $action=index_write"})
public Map<String, Id> vertexLabelRebuild(@Context GraphManager manager,
                                          @PathParam("graph") String graph,
                                          @PathParam("name") String name) {
    LOG.debug("Graph [{}] rebuild vertex label: {}", graph, name);

    HugeGraph g = graph(manager, graph);
    return ImmutableMap.of("task_id",
                           g.schema().vertexLabel(name).rebuildIndex());
}
 
@PUT
@Path(BUSINESS_METHOD)
@LRA(value = LRA.Type.MANDATORY)
public Response enlistWithLongLatency(@HeaderParam(LRA.LRA_HTTP_CONTEXT_HEADER) URI lraId) {
    LOGGER.info("call of enlistWithLongLatency");
    try {
        syncLatch.countDown();
        // await for compensation
        businessLatch.await();
        return Response.ok(lraId).build();
    } catch (InterruptedException ex) {
        return Response.serverError().build();
    }
}
 
源代码19 项目: submarine   文件: ParamRestApi.java
@PUT
@Path("/edit")
@SubmarineApi
public Response putParam(Param param) {
  LOG.info("putParam ({})", param);
  boolean result = false;
  try {
    result = paramService.update(param);
  } catch (Exception e) {
    LOG.error(e.toString());
    return new JsonResponse.Builder<Boolean>(Response.Status.OK).success(false).build();
  }
  return new JsonResponse.Builder<Boolean>(Response.Status.OK).success(true).result(result).build();
}
 
@PUT
@Path(NonParticipatingTckResource.END_PATH)
@LRA(value = LRA.Type.MANDATORY,
        cancelOnFamily = Response.Status.Family.SERVER_ERROR) // default is to end the LRA
public Response endLRA(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId,
                       @DefaultValue("200") @QueryParam(STATUS_CODE_QUERY_NAME) int coerceStatus) {
    return Response.status(coerceStatus).entity(checkLRANotNull(lraId)).build();
}
 
源代码21 项目: localization_nifi   文件: DataTransferResource.java
@PUT
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("output-ports/{portId}/transactions/{transactionId}")
@ApiOperation(
        value = "Extend transaction TTL",
        response = TransactionResultEntity.class,
        authorizations = {
                @Authorization(value = "Write - /data-transfer/output-ports/{uuid}", type = "")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful."),
                @ApiResponse(code = 503, message = "NiFi instance is not ready for serving request, or temporarily overloaded. Retrying the same request later may be successful"),
        }
)
public Response extendOutputPortTransactionTTL(
        @PathParam("portId") String portId,
        @PathParam("transactionId") String transactionId,
        @Context HttpServletRequest req,
        @Context HttpServletResponse res,
        @Context ServletContext context,
        @Context UriInfo uriInfo,
        InputStream inputStream) {

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        authorizeDataTransfer(lookup, ResourceType.OutputPort, portId);
    });

    return extendPortTransactionTTL(PORT_TYPE_OUTPUT, portId, transactionId, req, res, context, uriInfo, inputStream);
}
 
源代码22 项目: localization_nifi   文件: DataTransferResource.java
@PUT
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("input-ports/{portId}/transactions/{transactionId}")
@ApiOperation(
        value = "Extend transaction TTL",
        response = TransactionResultEntity.class,
        authorizations = {
                @Authorization(value = "Write - /data-transfer/input-ports/{uuid}", type = "")
        }
)
@ApiResponses(
        value = {
                @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
                @ApiResponse(code = 401, message = "Client could not be authenticated."),
                @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
                @ApiResponse(code = 404, message = "The specified resource could not be found."),
                @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
        }
)
public Response extendInputPortTransactionTTL(
        @PathParam("portId") String portId,
        @PathParam("transactionId") String transactionId,
        @Context HttpServletRequest req,
        @Context HttpServletResponse res,
        @Context ServletContext context,
        @Context UriInfo uriInfo,
        InputStream inputStream) {

    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        authorizeDataTransfer(lookup, ResourceType.InputPort, portId);
    });

    return extendPortTransactionTTL(PORT_TYPE_INPUT, portId, transactionId, req, res, context, uriInfo, inputStream);
}
 
源代码23 项目: linstor-server   文件: VolumeGroups.java
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("{volume_number}")
public void modifyVolumeGroup(
    @Context Request request,
    @Suspended final AsyncResponse asyncResponse,
    @PathParam("rscName") String rscName,
    @PathParam("volume_number") int volumeNumber,
    String jsonData
) throws IOException
{
    JsonGenTypes.VolumeGroupModify modifyData = objectMapper.readValue(
        jsonData,
        JsonGenTypes.VolumeGroupModify.class
    );

    Flux<ApiCallRc> flux = ctrlApiCallHandler.modifyVolumeGroup(
        rscName,
        volumeNumber,
        modifyData.override_props,
        new HashSet<>(modifyData.delete_props),
        new HashSet<>(modifyData.delete_namespaces),
        modifyData.flags
    )
    .subscriberContext(requestHelper.createContext(ApiConsts.API_MOD_VLM_GRP, request));

    requestHelper.doFlux(asyncResponse, ApiCallRcRestUtils.mapToMonoResponse(flux, Response.Status.OK));
}
 
源代码24 项目: icure-backend   文件: PatientFacade.java
@ApiOperation(
	value = "Modify a patient",
	response = PatientDto.class,
	httpMethod = "PUT",
	notes = "No particular return value. It's just a message."
)
@PUT
public Response modifyPatient(PatientDto patientDto) {
	if (patientDto == null) {
		return Response.status(400).type("text/plain").entity("A required query parameter was not specified for this request.").build();
	}

	try {
		Patient modifiedPatient = patientLogic.modifyPatient(mapper.map(patientDto, Patient.class));

		boolean succeed = (modifiedPatient != null);
		if (succeed) {
			return Response.ok().entity(mapper.map(modifiedPatient, PatientDto.class)).build();
		} else {
			log.error("Getting patient failed. Possible reasons: no such patient exists, or server error. Please try again or read the server log.");
			return Response.status(500).type("text/plain").entity("Modification patient failed. Possible reasons: no such patient exists, or server error. Please try again or read the server log.").build();
		}
	} catch (MissingRequirementsException e) {
		log.warn(e.getMessage(), e);
		return Response.status(400).type("text/plain").entity(e.getMessage()).build();
	}
}
 
源代码25 项目: quarkus-quickstarts   文件: FruitResource.java
@PUT
@Path("{id}")
public Uni<Response> update(@PathParam Long id, Fruit fruit) {
    return fruit.update(client)
            .onItem().apply(updated -> updated ? Status.OK : Status.NOT_FOUND)
            .onItem().apply(status -> Response.status(status).build());
}
 
源代码26 项目: microprofile-lra   文件: ValidLRAParticipant.java
@PUT
@Path(ACCEPT_PATH)
@LRA(value = LRA.Type.REQUIRES_NEW)
public Response acceptLRA(@QueryParam(RECOVERY_PARAM) @DefaultValue("0") Integer recoveryPasses) {
    this.recoveryPasses = recoveryPasses;

    return Response.ok().build();
}
 
@PUT
@Path(NonParticipatingTckResource.START_AND_END_NESTED_PATH)
@LRA(value = LRA.Type.NESTED,
        cancelOnFamily = Response.Status.Family.SERVER_ERROR) // default is to end the LRA
public Response startAndEndNestedLRA(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId) {
    return Response.ok(lraId).build();
}
 
源代码28 项目: presto   文件: UiQueryResource.java
@ResourceSecurity(WEB_UI)
@PUT
@Path("{queryId}/killed")
public Response killQuery(@PathParam("queryId") QueryId queryId, String message, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
    return failQuery(queryId, createKillQueryException(message), servletRequest, httpHeaders);
}
 
源代码29 项目: presto   文件: UiQueryResource.java
@ResourceSecurity(WEB_UI)
@PUT
@Path("{queryId}/preempted")
public Response preemptQuery(@PathParam("queryId") QueryId queryId, String message, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
    return failQuery(queryId, createPreemptQueryException(message), servletRequest, httpHeaders);
}
 
源代码30 项目: microprofile-lra   文件: ContextTckResource.java
@LRA(value = LRA.Type.REQUIRED)
@PUT
@Path(ASYNC_LRA_PATH1)
public void async1LRA(@HeaderParam(LRA_HTTP_CONTEXT_HEADER) URI lraId,
                     final @Suspended AsyncResponse ar) {
    excecutorService.submit(() -> {
        // excecute long running business activity and resume when done
        ar.resume(Response.ok().entity(lraId.toASCIIString()).build());
    });
}