下面列出了javax.ws.rs.core.Response.Status#BAD_REQUEST 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public BatchDto modifyProcessInstanceAsync(ProcessInstanceModificationDto dto) {
Batch batch = null;
if (dto.getInstructions() != null && !dto.getInstructions().isEmpty()) {
ProcessInstanceModificationBuilder modificationBuilder =
engine.getRuntimeService().createProcessInstanceModification(processInstanceId);
dto.applyTo(modificationBuilder, engine, objectMapper);
if (dto.getAnnotation() != null) {
modificationBuilder.setAnnotation(dto.getAnnotation());
}
modificationBuilder.cancellationSourceExternal(true);
try {
batch = modificationBuilder.executeAsync(dto.isSkipCustomListeners(), dto.isSkipIoMappings());
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
return BatchDto.fromBatch(batch);
}
throw new InvalidRequestException(Status.BAD_REQUEST, "The provided instuctions are invalid.");
}
@Path("{policyId}")
@PUT
@Consumes("application/json")
@Produces("application/json")
public Response update(@PathParam("policyId") String policyId, String payload) {
UmaPermissionRepresentation representation;
try {
representation = JsonSerialization.readValue(payload, UmaPermissionRepresentation.class);
} catch (IOException e) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Failed to parse representation", Status.BAD_REQUEST);
}
checkRequest(getAssociatedResourceId(policyId), representation);
return PolicyTypeResourceService.class.cast(delegate.getResource(policyId)).update(payload);
}
private void appendFromObject(List<Sort> orderings, JsonNode node) {
JsonNode propertyNode = node.get(JSON_KEY_PROPERTY);
if (propertyNode == null || !propertyNode.isTextual()) {
// this is a hack for Sencha bug, passing us null sorters
// per LF-189... So allowing for lax property name checking as a result
// TODO: move this to Sencha package?
if (propertyNode != null && propertyNode.isNull()) {
LOGGER.info("ignoring NULL sort property");
return;
}
throw new AgException(Status.BAD_REQUEST, "Bad sort spec: " + node);
}
JsonNode directionNode = node.get(JSON_KEY_DIRECTION);
appendPath(
orderings,
propertyNode.asText(),
directionNode != null ? directionNode.asText() : null);
}
@Override
public Response toResponse(ValidationException exception) {
ValidationResult validation = exception.getValidationResult();
Status status = Status.BAD_REQUEST;
// TODO: perhaps we can convert this in a true DataResponse with a list
// of failed properties that can be analyzed on the client?
// for now log details, return a generic validation message to avoid leaking too much server internals
LOGGER.info("{} {} ({})", status.getStatusCode(), status.getReasonPhrase(), validation);
// TODO: localize error message
String message = String.format(ERROR_MESSAGE_EN, validation.getFailures().size());
SimpleResponse body = new SimpleResponse(false, message);
return Response.status(status).entity(body).type(MediaType.APPLICATION_JSON_TYPE).build();
}
public Batch updateSuspensionStateAsync(ProcessEngine engine) {
int params = parameterCount(processInstanceIds, processInstanceQuery, historicProcessInstanceQuery);
if (params == 0) {
String message = "Either processInstanceIds, processInstanceQuery or historicProcessInstanceQuery should be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
UpdateProcessInstancesSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateGroupBuilder(engine);
if (getSuspended()) {
return updateSuspensionStateBuilder.suspendAsync();
} else {
return updateSuspensionStateBuilder.activateAsync();
}
}
/**
* @since 3.8
*/
@Override
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploadComponent(@QueryParam("repository") final String repositoryId,
@Context final HttpServletRequest request)
throws IOException
{
if (!uploadConfiguration.isEnabled()) {
throw new WebApplicationException(NOT_FOUND);
}
Repository repository = repositoryManagerRESTAdapter.getRepository(repositoryId);
try {
uploadManager.handle(repository, request);
} catch (IllegalOperationException e) {
throw new WebApplicationMessageException(Status.BAD_REQUEST, e.getMessage());
}
}
public MigrationPlanDto generateMigrationPlan(MigrationPlanGenerationDto generationDto) {
RuntimeService runtimeService = processEngine.getRuntimeService();
String sourceProcessDefinitionId = generationDto.getSourceProcessDefinitionId();
String targetProcessDefinitionId = generationDto.getTargetProcessDefinitionId();
try {
MigrationInstructionsBuilder instructionsBuilder = runtimeService.createMigrationPlan(sourceProcessDefinitionId, targetProcessDefinitionId)
.mapEqualActivities();
if (generationDto.isUpdateEventTriggers()) {
instructionsBuilder = instructionsBuilder.updateEventTriggers();
}
MigrationPlan migrationPlan = instructionsBuilder.build();
return MigrationPlanDto.from(migrationPlan);
}
catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage());
}
}
@Override
public BatchDto executeModificationAsync(ModificationDto modificationExecutionDto) {
Batch batch = null;
try {
batch = createModificationBuilder(modificationExecutionDto).executeAsync();
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
return BatchDto.fromBatch(batch);
}
public void createTask(TaskDto taskDto) {
ProcessEngine engine = getProcessEngine();
TaskService taskService = engine.getTaskService();
Task newTask = taskService.newTask(taskDto.getId());
taskDto.updateTask(newTask);
try {
taskService.saveTask(newTask);
} catch (NotValidException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e, "Could not save task: " + e.getMessage());
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/segments/{tableName}/delete")
@ApiOperation(value = "Delete the segments in the JSON array payload", notes = "Delete the segments in the JSON array payload")
public SuccessResponse deleteSegments(
@ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName,
List<String> segments) {
int numSegments = segments.size();
if (numSegments == 0) {
throw new ControllerApplicationException(LOGGER, "Segments must be provided", Status.BAD_REQUEST);
}
boolean isRealtimeSegment = SegmentName.isRealtimeSegmentName(segments.get(0));
for (int i = 1; i < numSegments; i++) {
if (SegmentName.isRealtimeSegmentName(segments.get(i)) != isRealtimeSegment) {
throw new ControllerApplicationException(LOGGER, "All segments must be of the same type (OFFLINE|REALTIME)",
Status.BAD_REQUEST);
}
}
TableType tableType = isRealtimeSegment ? TableType.REALTIME : TableType.OFFLINE;
String tableNameWithType = getExistingTableNamesWithType(tableName, tableType).get(0);
deleteSegmentsInternal(tableNameWithType, segments);
if (numSegments <= 5) {
return new SuccessResponse("Deleted segments: " + segments + " from table: " + tableNameWithType);
} else {
return new SuccessResponse("Deleted " + numSegments + " segments from table: " + tableNameWithType);
}
}
@Test
public void testArrayMessage() throws GitLabApiException {
final MockResponse response = new MockResponse(Status.BAD_REQUEST, TEST_RESPONSE_JSON_ARRAY);
GitLabApiException glae = new GitLabApiException(response);
assertEquals(Status.BAD_REQUEST.getStatusCode(), glae.getHttpStatus());
assertEquals(TEST_ERROR_MESSAGE, glae.getMessage());
}
public static StateType validateState(String stateStr) {
if (stateStr == null) {
return null;
}
try {
return StateType.valueOf(stateStr.toUpperCase());
} catch (IllegalArgumentException e) {
LOGGER.info("Illegal state '{}'", stateStr);
throw new WebApplicationException("Illegal state '" + stateStr + "'", Status.BAD_REQUEST);
}
}
@Override
public BatchDto updateSuspensionStateAsync(ProcessInstanceSuspensionStateAsyncDto dto){
Batch batch = null;
try {
batch = dto.updateSuspensionStateAsync(getProcessEngine());
return BatchDto.fromBatch(batch);
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
}
@Override
public Response toResponse(JsonParseException exception) {
InvalidRequestException badRequestException = new InvalidRequestException(Status.BAD_REQUEST,
exception, "");
return ExceptionHandlerHelper.getInstance().getResponse(badRequestException);
}
@Override
Status getResponseStatus() {
return Status.BAD_REQUEST;
}
@Override
Status getResponseStatus() {
return Status.BAD_REQUEST;
}
@Override
Status getResponseStatus() {
return Status.BAD_REQUEST;
}
public TypedValue toTypedValue(ProcessEngine processEngine, ObjectMapper objectMapper) {
ValueTypeResolver valueTypeResolver = processEngine.getProcessEngineConfiguration().getValueTypeResolver();
if (type == null) {
if (valueInfo != null && valueInfo.get(ValueType.VALUE_INFO_TRANSIENT) instanceof Boolean) {
return Variables.untypedValue(value, (Boolean) valueInfo.get(ValueType.VALUE_INFO_TRANSIENT));
}
return Variables.untypedValue(value);
}
ValueType valueType = valueTypeResolver.typeForName(fromRestApiTypeName(type));
if(valueType == null) {
throw new RestException(Status.BAD_REQUEST, String.format("Unsupported value type '%s'", type));
}
else {
if(valueType instanceof PrimitiveValueType) {
PrimitiveValueType primitiveValueType = (PrimitiveValueType) valueType;
Class<?> javaType = primitiveValueType.getJavaType();
Object mappedValue = null;
try {
if(value != null) {
if(javaType.isAssignableFrom(value.getClass())) {
mappedValue = value;
}
else {
// use jackson to map the value to the requested java type
mappedValue = objectMapper.readValue("\""+value+"\"", javaType);
}
}
return valueType.createValue(mappedValue, valueInfo);
}
catch (Exception e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e,
String.format("Cannot convert value '%s' of type '%s' to java type %s", value, type, javaType.getName()));
}
}
else if(valueType instanceof SerializableValueType) {
if(value != null && !(value instanceof String)) {
throw new InvalidRequestException(Status.BAD_REQUEST, "Must provide 'null' or String value for value of SerializableValue type '"+type+"'.");
}
return ((SerializableValueType) valueType).createValueFromSerialized((String) value, valueInfo);
}
else if(valueType instanceof FileValueType) {
if (value instanceof String) {
value = Base64.decodeBase64((String) value);
}
return valueType.createValue(value, valueInfo);
} else {
return valueType.createValue(value, valueInfo);
}
}
}
/**
* Posts a message to a long polling channel.
*
* @param ccid
* the identifier of the long polling channel
* @param serializedMessage
* the message to send serialized as a SMRF message
* @return the path segment for the message status. The path, appended to
* the base URI of the messaging service, can be used to query the
* message status
*
* @throws JoynrHttpException
* if one of:
* <ul>
* <li>ccid is not set</li>
* <li>the message has expired or not expiry date is set</li>
* <li>no channel registered for ccid</li>
* </ul>
*/
public String postMessage(String ccid, byte[] serializedMessage) {
ImmutableMessage message;
try {
message = new ImmutableMessage(serializedMessage);
} catch (EncodingException | UnsuppportedVersionException e) {
throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_DESERIALIZATIONFAILED);
}
if (ccid == null) {
log.error("POST message {} to cluster controller: NULL. Dropped because: channel Id was not set.",
message.getId());
throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_CHANNELNOTSET);
}
// send the message to the receiver.
if (message.getTtlMs() == 0) {
log.error("POST message {} to cluster controller: {} dropped because: expiry date not set",
ccid,
message.getId());
throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_EXPIRYDATENOTSET);
}
// Relative TTLs are not supported yet.
if (!message.isTtlAbsolute()) {
throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_RELATIVE_TTL_UNSPORTED);
}
if (message.getTtlMs() < System.currentTimeMillis()) {
log.warn("POST message {} to cluster controller: {} dropped because: TTL expired", ccid, message.getId());
throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_EXPIRYDATEEXPIRED);
}
// look for an existing broadcaster
Broadcaster ccBroadcaster = BroadcasterFactory.getDefault().lookup(Broadcaster.class, ccid, false);
if (ccBroadcaster == null) {
// if the receiver has never registered with the bounceproxy
// (or his registration has expired) then return 204 no
// content.
log.error("POST message {} to cluster controller: {} dropped because: no channel found",
ccid,
message.getId());
throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_CHANNELNOTFOUND);
}
if (ccBroadcaster.getAtmosphereResources().size() == 0) {
log.debug("no poll currently waiting for channelId: {}", ccid);
}
ccBroadcaster.broadcast(message);
return "messages/" + message.getId();
}
/**
* Creates a builder for a bad request
*
* @return the exception builder
*/
public static ExceptionBuilder badRequest() {
return new ExceptionBuilder(Status.BAD_REQUEST);
}