下面列出了怎么用javax.ws.rs.core.GenericEntity的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testPostCollectionGenericEntityGenericCallback() throws Exception {
String endpointAddress =
"http://localhost:" + PORT + "/bookstore/collections3";
WebClient wc = WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
GenericEntity<List<Book>> collectionEntity = createGenericEntity();
GenericInvocationCallback<Book> callback = new GenericInvocationCallback<Book>(new Holder<>()) {
};
Future<Book> future = wc.post(collectionEntity, callback);
Book book = future.get();
assertEquals(200, wc.getResponse().getStatus());
assertSame(book, callback.value());
assertNotSame(collectionEntity.getEntity().get(0), book);
assertEquals(collectionEntity.getEntity().get(0).getName(), book.getName());
}
/**
* Resource that only relies on {@link Single}/{@link Publisher} for consuming and producing data,
* and returns a JAX-RS {@link Response} in order to set its status.
* No OIO adaptation is involved when requests are dispatched to it,
* allowing it to fully benefit from ReactiveStream's features like flow control.
* Behind the scene, ServiceTalk's aggregation mechanism is used to provide the resource with a
* {@link Single Single<Buffer>} that contains the whole request entity as a {@link Buffer}.
* Note that the {@link ConnectionContext} could also be injected into a class-level {@code @Context} field.
* <p>
* Test with:
* <pre>
* curl -i -H 'content-type: text/plain' -d 'kitty' http://localhost:8080/greetings/random-hello
* </pre>
*
* @param who the recipient of the greetings.
* @param ctx the {@link ConnectionContext}.
* @return greetings as a JAX-RS {@link Response}.
*/
@POST
@Path("random-hello")
@Consumes(TEXT_PLAIN)
@Produces(TEXT_PLAIN)
public Response randomHello(final Single<Buffer> who,
@Context final ConnectionContext ctx) {
if (random() < .5) {
return accepted("greetings accepted, call again for a response").build();
}
final BufferAllocator allocator = ctx.executionContext().bufferAllocator();
final Publisher<Buffer> payload = from(allocator.fromAscii("hello ")).concat(who);
// Wrap content Publisher to capture its generic type (i.e. Buffer) so it is handled correctly
final GenericEntity<Publisher<Buffer>> entity = new GenericEntity<Publisher<Buffer>>(payload) { };
return ok(entity).build();
}
@Override
public void uploadToVerifier(Extension extension) {
final WebTarget target = client.target(String.format("http://%s/api/v1/drivers", verificationConfig.getService()));
final MultipartFormDataOutput multipart = new MultipartFormDataOutput();
String fileName = ExtensionActivator.getConnectorIdForExtension(extension);
multipart.addFormData("fileName", fileName, MediaType.TEXT_PLAIN_TYPE);
InputStream is = fileDataManager.getExtensionBinaryFile(extension.getExtensionId());
multipart.addFormData("file", is, MediaType.APPLICATION_OCTET_STREAM_TYPE);
GenericEntity<MultipartFormDataOutput> genericEntity = new GenericEntity<MultipartFormDataOutput>(multipart) {};
Entity<?> entity = Entity.entity(genericEntity, MediaType.MULTIPART_FORM_DATA_TYPE);
Boolean isDeployed = target.request().post(entity, Boolean.class);
if (isDeployed) {
openShiftClient.deploymentConfigs().withName("syndesis-meta").deployLatest();
}
}
@Override
public Response toResponse(JaxbException exception) {
int errorCode = 1;
String errorMsg = "JAXB convert/validate error, please check your input data";
if (config != null) {
Object propErrorCode = config.getProperty(PROP_JAXB_DEFAULT_ERROR_CODE);
Object propErrorMsg = config.getProperty(PROP_JAXB_DEFAULT_ERROR_MSG);
if (propErrorCode != null) {
errorCode = Integer.valueOf(propErrorCode.toString());
}
if (propErrorMsg != null) {
errorMsg = propErrorMsg.toString();
}
}
List<JaxbError> errors = new ArrayList<>();
errors.add(new JaxbError(exception.getMessage()));
ParsecErrorResponse<JaxbError> errorResponse = ValidateUtil.buildErrorResponse(errors, errorCode, errorMsg);
return Response.status(Response.Status.BAD_REQUEST)
.entity(new GenericEntity<ParsecErrorResponse<JaxbError>>(errorResponse) { }).build();
}
@GET
@Path("/workspaces")
@ApiOperation(value = "Get workspaces where authenticated user is active",
response = WorkspaceDTO.class,
responseContainer = "List",
authorizations = {@Authorization(value = "authorization")})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of Workspaces. It can be an empty list."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 500, message = "Internal server error")
})
@Produces(MediaType.APPLICATION_JSON)
public Response getWorkspaces() {
Workspace[] workspaces = userManager.getWorkspacesWhereCallerIsActive();
List<WorkspaceDTO> workspaceDTOs = new ArrayList<>();
for (Workspace workspace : workspaces) {
workspaceDTOs.add(mapper.map(workspace, WorkspaceDTO.class));
}
return Response.ok(new GenericEntity<List<WorkspaceDTO>>((List<WorkspaceDTO>) workspaceDTOs) {
}).build();
}
public static Type getGenericResponseType(Method invoked,
Class<?> serviceCls,
Object targetObject,
Class<?> targetType,
Exchange exchange) {
if (targetObject == null) {
return null;
}
Type type = null;
if (GenericEntity.class.isAssignableFrom(targetObject.getClass())) {
type = processGenericTypeIfNeeded(serviceCls, targetType, ((GenericEntity<?>)targetObject).getType());
} else if (invoked == null
|| !invoked.getReturnType().isAssignableFrom(targetType)) {
// when a method has been invoked it is still possible that either an ExceptionMapper
// or a ResponseHandler filter overrides a response entity; if it happens then
// the Type is the class of the response object, unless this new entity is assignable
// to invoked.getReturnType(); same applies to the case when a method returns Response
type = targetObject.getClass();
} else {
type = processGenericTypeIfNeeded(serviceCls, targetType, invoked.getGenericReturnType());
}
return type;
}
@GET
@Path("providers")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of auth providers"),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 500, message = "Internal server error")
})
@ApiOperation(value = "Get detailed providers",
response = OAuthProviderDTO.class,
responseContainer = "List")
@Produces(MediaType.APPLICATION_JSON)
public Response getDetailedProviders() {
List<OAuthProvider> providers = oAuthManager.getProviders();
List<OAuthProviderDTO> dtos = new ArrayList<>();
for (OAuthProvider provider : providers) {
dtos.add(mapper.map(provider, OAuthProviderDTO.class));
}
return Response.ok(new GenericEntity<List<OAuthProviderDTO>>(dtos) {
}).build();
}
@Test
public void testPostCollectionGenericEntity() throws Exception {
String endpointAddress =
"http://localhost:" + PORT + "/bookstore/collections3";
WebClient wc = WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
GenericEntity<List<Book>> collectionEntity = createGenericEntity();
BookInvocationCallback callback = new BookInvocationCallback();
Future<Book> future = wc.post(collectionEntity, callback);
Book book = future.get();
assertEquals(200, wc.getResponse().getStatus());
assertSame(book, callback.value());
assertNotSame(collectionEntity.getEntity().get(0), book);
assertEquals(collectionEntity.getEntity().get(0).getName(), book.getName());
}
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
public GenericEntity<List<AsynchronousProcess>> list() {
AsynchronousJobPool pool = getJobPool();
List<AsynchronousJob> jobs = pool.getAll();
List<AsynchronousProcess> processes = new ArrayList<>(jobs.size());
for (AsynchronousJob job : jobs) {
GenericContainerRequest request = (GenericContainerRequest)job.getContext().get("org.everrest.async.request");
Principal principal = request.getUserPrincipal();
processes.add(new AsynchronousProcess(
principal != null ? principal.getName() : null,
job.getJobId(),
request.getRequestUri().getPath(),
job.isDone() ? "done" : "running"));
}
return new GenericEntity<List<AsynchronousProcess>>(processes) {
};
}
@GET
@ApiOperation(value = "Get change requests for a given milestone",
response = ChangeRequestDTO.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of created ChangeRequestDTOs. It can be an empty list."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 500, message = "Internal server error")
})
@Produces(MediaType.APPLICATION_JSON)
@Path("{milestoneId}/requests")
public Response getRequestsByMilestone(
@ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
@ApiParam(required = true, value = "Milestone id") @PathParam("milestoneId") int milestoneId)
throws EntityNotFoundException, UserNotActiveException, AccessRightException, WorkspaceNotEnabledException {
List<ChangeRequest> changeRequests = changeManager.getChangeRequestsByMilestone(workspaceId, milestoneId);
List<ChangeRequestDTO> changeRequestDTOs = new ArrayList<>();
for (ChangeRequest changeRequest : changeRequests) {
changeRequestDTOs.add(mapper.map(changeRequest, ChangeRequestDTO.class));
}
return Response.ok(new GenericEntity<List<ChangeRequestDTO>>((List<ChangeRequestDTO>) changeRequestDTOs) {
}).build();
}
@GET
@ApiOperation(value = "Get change orders for a given milestone",
response = ChangeOrderDTO.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of created ChangeOrderDTOs. It can be an empty list."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 500, message = "Internal server error")
})
@Produces(MediaType.APPLICATION_JSON)
@Path("{milestoneId}/orders")
public Response getOrdersByMilestone(
@ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
@ApiParam(required = true, value = "Milestone id") @PathParam("milestoneId") int milestoneId)
throws EntityNotFoundException, UserNotActiveException, AccessRightException, WorkspaceNotEnabledException {
List<ChangeOrder> changeOrders = changeManager.getChangeOrdersByMilestone(workspaceId, milestoneId);
List<ChangeOrderDTO> changeOrderDTOs = new ArrayList<>();
for (ChangeOrder changeOrder : changeOrders) {
changeOrderDTOs.add(mapper.map(changeOrder, ChangeOrderDTO.class));
}
return Response.ok(new GenericEntity<List<ChangeOrderDTO>>((List<ChangeOrderDTO>) changeOrderDTOs) {
}).build();
}
private Response filterAttributes(List<InstanceAttribute> attributes) {
List<InstanceAttributeDTO> attributeDTOList = new ArrayList<>();
Set<String> seen=new HashSet<>();
for (InstanceAttribute attribute : attributes) {
if(attribute==null)
continue;
InstanceAttributeDTO dto = mapper.map(attribute, InstanceAttributeDTO.class);
if(seen.add(dto.getType()+"."+dto.getName())) {
dto.setValue(null);
dto.setMandatory(false);
dto.setLocked(false);
dto.setLovName(null);
attributeDTOList.add(dto);
}
}
return Response.ok(new GenericEntity<List<InstanceAttributeDTO>>((List<InstanceAttributeDTO>) attributeDTOList) {
}).build();
}
@GET
@ApiOperation(value = "Get detailed workspace list for authenticated user",
response = WorkspaceDetailsDTO.class,
responseContainer = "List",
authorizations = {@Authorization(value = "authorization")})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of WorkspaceDetailsDTOs. It can be an empty list."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 500, message = "Internal server error")
})
@Path("/more")
@Produces(MediaType.APPLICATION_JSON)
public Response getDetailedWorkspacesForConnectedUser()
throws EntityNotFoundException {
List<WorkspaceDetailsDTO> workspaceListDTO = new ArrayList<>();
for (Workspace workspace : userManager.getWorkspacesWhereCallerIsActive()) {
workspaceListDTO.add(mapper.map(workspace, WorkspaceDetailsDTO.class));
}
return Response.ok(new GenericEntity<List<WorkspaceDetailsDTO>>((List<WorkspaceDetailsDTO>) workspaceListDTO) {
}).build();
}
@GET
@ApiOperation(value = "Get change issues for given parameters",
response = ChangeIssueDTO.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of ChangeIssueDTOs. It can be an empty list."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 500, message = "Internal server error")
})
@Produces(MediaType.APPLICATION_JSON)
public Response getIssues(
@ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId)
throws EntityNotFoundException, UserNotActiveException, WorkspaceNotEnabledException {
List<ChangeIssue> changeIssues = changeManager.getChangeIssues(workspaceId);
List<ChangeIssueDTO> changeIssueDTOs = new ArrayList<>();
for (ChangeIssue issue : changeIssues) {
ChangeIssueDTO changeIssueDTO = mapper.map(issue, ChangeIssueDTO.class);
changeIssueDTO.setWritable(changeManager.isChangeItemWritable(issue));
changeIssueDTOs.add(changeIssueDTO);
}
return Response.ok(new GenericEntity<List<ChangeIssueDTO>>((List<ChangeIssueDTO>) changeIssueDTOs) {
}).build();
}
@GET
@ApiOperation(value = "Get roles in given workspace",
response = RoleDTO.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of RoleDTOs. It can be an empty list."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 500, message = "Internal server error")
})
@Produces(MediaType.APPLICATION_JSON)
public Response getRolesInWorkspace(
@ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId)
throws EntityNotFoundException, UserNotActiveException, WorkspaceNotEnabledException {
Role[] roles = roleService.getRoles(workspaceId);
List<RoleDTO> rolesDTO = new ArrayList<>();
for (Role role :roles) {
rolesDTO.add(mapRoleToDTO(role));
}
return Response.ok(new GenericEntity<List<RoleDTO>>((List<RoleDTO>) rolesDTO) {
}).build();
}
@Path("get-backups")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAvailableBackups() throws Exception
{
Collection<BackupMetaData> backups = context.getExhibitor().getBackupManager().getAvailableBackups();
Collection<NameAndModifiedDate> transformed = Collections2.transform
(
backups,
new Function<BackupMetaData, NameAndModifiedDate>()
{
@Override
public NameAndModifiedDate apply(BackupMetaData backup)
{
return new NameAndModifiedDate(backup.getName(), backup.getModifiedDate());
}
}
);
ArrayList<NameAndModifiedDate> cleaned = Lists.newArrayList(transformed);// move out of Google's TransformingRandomAccessList
GenericEntity<Collection<NameAndModifiedDate>> entity = new GenericEntity<Collection<NameAndModifiedDate>>(cleaned){};
return Response.ok(entity).build();
}
@Override
protected Response convert(final JsonMappingException exception, final String id) {
final List<ValidationErrorXO> errors = exception.getPath().stream()
.map(reference -> new ValidationErrorXO(reference.getFieldName(), exception.getOriginalMessage()))
.collect(Collectors.toList());
return Response.status(Status.BAD_REQUEST)
.entity(new GenericEntity<List<ValidationErrorXO>>(errors)
{
@Override
public String toString() {
return getEntity().toString();
}
})
.type(MediaType.APPLICATION_JSON)
.build();
}
@Override
protected Response convert(final E exception, final String id) {
final Response.ResponseBuilder builder = Response.status(getStatus(exception));
final List<ValidationErrorXO> errors = getValidationErrors(exception);
if (errors != null && !errors.isEmpty()) {
final Variant variant = getRequest().selectVariant(variants);
if (variant != null) {
builder.type(variant.getMediaType())
.entity(
new GenericEntity<List<ValidationErrorXO>>(errors)
{
@Override
public String toString() {
return getEntity().toString();
}
}
);
}
}
return builder.build();
}
/**
*
* @param query
* @param startTime
* @param endTime
* @param pageSize
* @param startRowkey
* @param treeAgg
* @param timeSeries
* @param intervalmin
* @param top
* @param filterIfMissing
* @param parallel
* @param metricName
* @param verbose
* @return
*/
@GET
@Path(JSONP_PATH)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public JSONWithPadding searchWithJsonp(@QueryParam("query") String query,
@QueryParam("startTime") String startTime, @QueryParam("endTime") String endTime,
@QueryParam("pageSize") int pageSize, @QueryParam("startRowkey") String startRowkey,
@QueryParam("treeAgg") boolean treeAgg, @QueryParam("timeSeries") boolean timeSeries,
@QueryParam("intervalmin") long intervalmin, @QueryParam("top") int top,
@QueryParam("filterIfMissing") boolean filterIfMissing,
@QueryParam("parallel") int parallel,
@QueryParam("metricName") String metricName,
@QueryParam("verbose") Boolean verbose,
@QueryParam("callback") String callback){
GenericServiceAPIResponseEntity result = search(query, startTime, endTime, pageSize, startRowkey, treeAgg, timeSeries, intervalmin, top, filterIfMissing, parallel, metricName, verbose);
return new JSONWithPadding(new GenericEntity<GenericServiceAPIResponseEntity>(result){}, callback);
}
@Test
public void testPostGetCollectionGenericEntityAndType() throws Exception {
String endpointAddress =
"http://localhost:" + PORT + "/bookstore/collections";
WebClient wc = WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
Book b1 = new Book("CXF in Action", 123L);
Book b2 = new Book("CXF Rocks", 124L);
List<Book> books = new ArrayList<>();
books.add(b1);
books.add(b2);
GenericEntity<List<Book>> genericCollectionEntity =
new GenericEntity<List<Book>>(books) {
};
GenericType<List<Book>> genericResponseType =
new GenericType<List<Book>>() {
};
List<Book> books2 = wc.post(genericCollectionEntity, genericResponseType);
assertNotNull(books2);
assertNotSame(books, books2);
assertEquals(2, books2.size());
Book b11 = books.get(0);
assertEquals(123L, b11.getId());
assertEquals("CXF in Action", b11.getName());
Book b22 = books.get(1);
assertEquals(124L, b22.getId());
assertEquals("CXF Rocks", b22.getName());
assertEquals(200, wc.getResponse().getStatus());
}
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@Path("/json-buf-sglin-sglout-response")
@POST
public Response postJsonBufSingleInSingleOutResponse(final Single<Buffer> requestContent) {
final BufferAllocator allocator = ctx.executionContext().bufferAllocator();
final Single<Buffer> response = requestContent.map(buf -> {
final Map<String, Object> responseContent =
new HashMap<>(SERIALIZER.deserializeAggregatedSingle(buf, STRING_OBJECT_MAP_TYPE));
responseContent.put("foo", "bar6");
return SERIALIZER.serialize(responseContent, allocator);
});
return accepted(new GenericEntity<Single<Buffer>>(response) { }).build();
}
@GET
@Path("/relationship_types")
@ApiOperation(value = "Get all relationship types", response = String.class,
responseContainer = "List")
@Timed
@CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS)
@Produces({MediaType.APPLICATION_JSON})
public Object getRelationships(@ApiParam(value = DocumentationStrings.JSONP_DOC,
required = false) @QueryParam("callback") String callback) {
List<String> relationships = getRelationshipTypeNames();
sort(relationships);
return JaxRsUtil.wrapJsonp(request.get(), new GenericEntity<List<String>>(relationships) {},
callback);
}
@Override
Response toResponse(final Throwable exception) {
final Map<String, String> map = singletonMap("exceptionClassName", exception.getClass().getName());
return status(555)
.header(CONTENT_TYPE, APPLICATION_JSON)
.entity(new GenericEntity<Single<Map<String, String>>>(succeeded(map)) { })
.build();
}
@GET
@ApiOperation(
value = "Returns application version information",
notes = "Returns a simple json object containing the name of the application and the version",
response = About.class
)
@AuthenticationNotRequired
public Response getVersion() {
return Response.ok(new GenericEntity<About>(new About()) { }).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllBooks() {
List<Book> books = bookRepository.getAllBooks();
GenericEntity<List<Book>> list = new GenericEntity<List<Book>>(books) {
};
return Response.ok(list).build();
}
@GET
@ApiOperation(value = "Get document revision aborted workflow history",
response = WorkflowDTO.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of aborted WorkflowDTOs. It can be an empty list."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 500, message = "Internal server error")
})
@Path("aborted-workflows")
@Produces(MediaType.APPLICATION_JSON)
public Response getAbortedWorkflowListInDocument(
@ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
@ApiParam(required = true, value = "Document master id") @PathParam("documentId") String documentId,
@ApiParam(required = true, value = "Document version") @PathParam("documentVersion") String documentVersion)
throws EntityNotFoundException, AccessRightException, UserNotActiveException, WorkspaceNotEnabledException {
Workflow[] abortedWorkflowList = documentWorkflowService.getAbortedWorkflow(new DocumentRevisionKey(workspaceId, documentId, documentVersion));
List<WorkflowDTO> abortedWorkflowDTOList = new ArrayList<>();
for (Workflow abortedWorkflow : abortedWorkflowList) {
abortedWorkflowDTOList.add(mapper.map(abortedWorkflow, WorkflowDTO.class));
}
Collections.sort(abortedWorkflowDTOList);
return Response.ok(new GenericEntity<List<WorkflowDTO>>(abortedWorkflowDTOList) {
}).build();
}
@Test
public void testJAXBElementBookCollection() throws Exception {
String address = "http://localhost:" + PORT + "/bookstore/jaxbelementxmlrootcollections";
Client client = ClientBuilder.newClient();
WebTarget target = client.target(address);
Book b1 = new Book("CXF in Action", 123L);
Book b2 = new Book("CXF Rocks", 124L);
List<JAXBElement<Book>> books = Arrays.asList(
new JAXBElement<Book>(new QName("bookRootElement"), Book.class, b1),
new JAXBElement<Book>(new QName("bookRootElement"), Book.class, b2));
GenericEntity<List<JAXBElement<Book>>> collectionEntity =
new GenericEntity<List<JAXBElement<Book>>>(books) { };
GenericType<List<JAXBElement<Book>>> genericResponseType =
new GenericType<List<JAXBElement<Book>>>() { };
List<JAXBElement<Book>> books2 =
target.request().accept("application/xml")
.post(Entity.entity(collectionEntity, "application/xml"), genericResponseType);
assertNotNull(books2);
assertNotSame(books, books2);
assertEquals(2, books2.size());
Book b11 = books.get(0).getValue();
assertEquals(123L, b11.getId());
assertEquals("CXF in Action", b11.getName());
Book b22 = books.get(1).getValue();
assertEquals(124L, b22.getId());
assertEquals("CXF Rocks", b22.getName());
}
@GET
@ApiOperation(value = "Get inverse product instances links",
response = ProductInstanceMasterDTO.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of ProductInstanceMasterDTO pointing to this document. It can be an empty list."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 500, message = "Internal server error")
})
@Path("{iteration}/inverse-product-instances-link")
@Produces(MediaType.APPLICATION_JSON)
public Response getInverseProductInstancesLinks(
@ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
@ApiParam(required = true, value = "Document master id") @PathParam("documentId") String documentId,
@ApiParam(required = true, value = "Document version") @PathParam("documentVersion") String documentVersion,
@ApiParam(required = true, value = "Document iteration") @PathParam("iteration") int iteration)
throws UserNotActiveException, EntityNotFoundException, WorkspaceNotEnabledException {
DocumentRevisionKey docKey = new DocumentRevisionKey(workspaceId, documentId, documentVersion);
Set<ProductInstanceMaster> productInstanceMasterList = productService.getInverseProductInstancesLink(docKey);
Set<ProductInstanceMasterDTO> productInstanceMasterDTOs = new HashSet<>();
for (ProductInstanceMaster productInstanceMaster : productInstanceMasterList) {
productInstanceMasterDTOs.add(mapper.map(productInstanceMaster, ProductInstanceMasterDTO.class));
}
return Response.ok(new GenericEntity<List<ProductInstanceMasterDTO>>(new ArrayList<>(productInstanceMasterDTOs)) {
}).build();
}
@GET
@ApiOperation(value = "Get workflow's aborted workflow list",
response = WorkflowDTO.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of WorkflowDTOs. It can be an empty list."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 500, message = "Internal server error")
})
@Path("{workflowId}/aborted")
@Produces(MediaType.APPLICATION_JSON)
public Response getWorkflowAbortedWorkflowList(
@ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
@ApiParam(required = true, value = "Workflow id") @PathParam("workflowId") int workflowId)
throws EntityNotFoundException, UserNotActiveException, AccessRightException, WorkspaceNotEnabledException {
Workflow[] abortedWorkflowList = workflowService.getWorkflowAbortedWorkflowList(workspaceId, workflowId);
List<WorkflowDTO> abortedWorkflowDTOList = new ArrayList<>();
for (Workflow abortedWorkflow : abortedWorkflowList) {
abortedWorkflowDTOList.add(mapper.map(abortedWorkflow, WorkflowDTO.class));
}
Collections.sort(abortedWorkflowDTOList);
return Response.ok(new GenericEntity<List<WorkflowDTO>>((List<WorkflowDTO>) abortedWorkflowDTOList) {
}).build();
}
/**
* Process post.
*
* @return the response
*/
@POST
public Response processPost() {
StringBuilder builder = new StringBuilder();
try {
service();
builder.append("SUCCESS");
} catch (ServletException | IOException e) {
builder.append("FAILURE due to: " + e);
}
GenericEntity<String> entity = new GenericEntity<String>(builder.toString()) {
};
return Response.ok(entity).build();
}