javax.ws.rs.core.GenericEntity Java Examples

The following examples show how to use javax.ws.rs.core.GenericEntity. 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: ValidationExceptionMapperSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #2
Source File: AttributesResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
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();
}
 
Example #3
Source File: InjectionUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: WorkspaceResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #5
Source File: ChangeIssuesResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #6
Source File: AdminResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #7
Source File: AccountResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #8
Source File: IndexResource.java    From exhibitor with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #9
Source File: JaxbExceptionMapper.java    From parsec-libraries with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #10
Source File: DefaultVerifierExtensionUploader.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #11
Source File: JsonMappingExceptionMapper.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #12
Source File: JAXRS20ClientServerBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #13
Source File: AsynchronousJobService.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@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) {
    };
}
 
Example #14
Source File: JAXRS20ClientServerBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #15
Source File: MilestonesResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #16
Source File: GenericEntityServiceResource.java    From Eagle with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @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);
}
 
Example #17
Source File: RoleResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #18
Source File: HelloWorldJaxRsResource.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
/**
 * 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&lt;Buffer&gt;} 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();
}
 
Example #19
Source File: MilestonesResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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();
}
 
Example #20
Source File: JsonProcessingExceptionMapper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Response convert(final JsonProcessingException exception, final String id) {
  return Response.status(Status.BAD_REQUEST)
      .entity(new GenericEntity<>(new ValidationErrorXO(
          "Could not process the input: " + exception.getOriginalMessage()), ValidationErrorXO.class))
      .type(MediaType.APPLICATION_JSON)
      .build();
}
 
Example #21
Source File: ResultService.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
@POST
public Response processPost(){
	StringBuilder builder = new StringBuilder();
	try {
		doPost();
		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();
}
 
Example #22
Source File: CypherUtilService.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/curies")
@ApiOperation(value = "Get the curie map", response = String.class, responseContainer = "Map")
@Timed
@CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS)
@Produces({MediaType.APPLICATION_JSON})
public Object getCuries(
    @ApiParam(value = DocumentationStrings.JSONP_DOC, required = false) @QueryParam("callback") String callback) {
  return JaxRsUtil.wrapJsonp(request.get(),
      new GenericEntity<Map<String, String>>(cypherUtil.getCurieMap()) {}, callback);
}
 
Example #23
Source File: PartResource.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@GET
@ApiOperation(value = "Get part revisions where given part revision is used as a component",
        response = PartRevisionDTO.class,
        responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful retrieval of PartRevisionDTOs. It can be an empty list."),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Path("/used-by-as-component")
@Produces(MediaType.APPLICATION_JSON)
public Response getUsedByAsComponent(
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
        @ApiParam(required = true, value = "Part number") @PathParam("partNumber") String partNumber,
        @ApiParam(required = true, value = "Part version") @PathParam("partVersion") String partVersion)
        throws EntityNotFoundException, UserNotActiveException, AccessRightException, WorkspaceNotEnabledException {

    List<PartIteration> partIterations = productService.getUsedByAsComponent(new PartRevisionKey(workspaceId, partNumber, partVersion));

    Set<PartRevision> partRevisions = new HashSet<>();

    for (PartIteration partIteration : partIterations) {
        partRevisions.add(partIteration.getPartRevision());
    }
    List<PartRevisionDTO> partRevisionDTOs = getPartRevisionDTO(partRevisions);

    return Response.ok(new GenericEntity<List<PartRevisionDTO>>((List<PartRevisionDTO>) partRevisionDTOs) {
    }).build();
}
 
Example #24
Source File: GraphService.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/properties")
@ApiOperation(value = "Get all property keys", response = String.class,
    responseContainer = "List")
@Timed
@CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS)
@Produces({MediaType.APPLICATION_JSON})
public Object getProperties(@ApiParam(value = DocumentationStrings.JSONP_DOC,
    required = false) @QueryParam("callback") String callback) {
  List<String> propertyKeys = new ArrayList<>(api.getAllPropertyKeys());
  sort(propertyKeys);
  return JaxRsUtil.wrapJsonp(request.get(), new GenericEntity<List<String>>(propertyKeys) {},
      callback);
}
 
Example #25
Source File: AbstractGenericBookStoreSpring.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@GET
@Path("/books/superbooks2")
public GenericEntity<List<T>> getSuperBookCollectionGenericEntity() {
    return new GenericEntity<List<T>>((List<T>)Collections.singletonList(
        new SuperBook("Super", 124L, true))) {
    };
}
 
Example #26
Source File: ValidationExceptionMapper.java    From jaxrs-beanvalidation-javaee7 with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(final ValidationException exception) {
    if (exception instanceof ConstraintViolationException) {
        LOGGER.log(Level.FINER, LocalizationMessages.CONSTRAINT_VIOLATIONS_ENCOUNTERED(), exception);

        final ConstraintViolationException cve = (ConstraintViolationException) exception;
        final Response.ResponseBuilder response = Response.status(getStatus(cve));

        // Entity
        final List<Variant> variants = Variant.mediaTypes(
                MediaType.APPLICATION_XML_TYPE,
                MediaType.APPLICATION_JSON_TYPE).build();
        final Variant variant = request.get().selectVariant(variants);
        if (variant != null) {
            response.type(variant.getMediaType());
        } else {
            /*
             * default media type which will be used only when none media type from {@value variants} is in
             * accept header of original request.
             */
            response.type(MediaType.TEXT_PLAIN_TYPE);
        }
        response.entity(
                new GenericEntity<List<ValidationError>>(
                        getEntity(cve.getConstraintViolations()),
                        new GenericType<List<ValidationError>>() {}.getType()
                )
        );

        return response.build();
    } else {
        LOGGER.log(Level.WARNING, LocalizationMessages.VALIDATION_EXCEPTION_RAISED(), exception);

        return Response.serverError().entity(exception.getMessage()).build();
    }
}
 
Example #27
Source File: DiscoveryResource.java    From soabase with Apache License 2.0 5 votes vote down vote up
@GET
@Path("deploymentGroups/{serviceName}")
@Produces(MediaType.APPLICATION_JSON)
public Response getDeploymentGroups(@PathParam("serviceName") String serviceName)
{
    Map<String, Boolean> groupStates = Maps.newTreeMap();
    for ( String group : features.getDeploymentGroupManager().getKnownGroups(serviceName) )
    {
        groupStates.put(group, features.getDeploymentGroupManager().isGroupEnabled(serviceName, group));
    }
    GenericEntity<Map<String, Boolean>> entity = new GenericEntity<Map<String, Boolean>>(groupStates){};
    return Response.ok(entity).build();
}
 
Example #28
Source File: ModelUtil.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
public static GenericEntity createGenericListEntity(List models, String type) {
	if (StringUtils.isEmpty(type)) {
		throw new IllegalArgumentException("Type cannot be empty!");
	}
	
	switch (type) {
	case TrpP2PaLA.TYPE:
		return new GenericEntity<List<TrpP2PaLA>>(models) {};
	default:
		throw new IllegalArgumentException("Invalid type: "+type);
	}
}
 
Example #29
Source File: PartResource.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@GET
@ApiOperation(value = "Get part revision'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("/aborted-workflows")
@Produces(MediaType.APPLICATION_JSON)
public Response getAbortedWorkflowListInPart(
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
        @ApiParam(required = true, value = "Part number") @PathParam("partNumber") String partNumber,
        @ApiParam(required = true, value = "Part version") @PathParam("partVersion") String partVersion)
        throws EntityNotFoundException, AccessRightException, UserNotActiveException, WorkspaceNotEnabledException {

    PartRevisionKey revisionKey = new PartRevisionKey(workspaceId, partNumber, partVersion);
    PartRevision partRevision = productService.getPartRevision(revisionKey);

    List<Workflow> abortedWorkflowList = partRevision.getAbortedWorkflows();
    List<WorkflowDTO> abortedWorkflowDTOs = new ArrayList<>();

    for (Workflow abortedWorkflow : abortedWorkflowList) {
        abortedWorkflowDTOs.add(mapper.map(abortedWorkflow, WorkflowDTO.class));
    }

    return Response.ok(new GenericEntity<List<WorkflowDTO>>((List<WorkflowDTO>) abortedWorkflowDTOs) {
    }).build();
}
 
Example #30
Source File: PartResource.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@GET
@ApiOperation(value = "Get product instance where part revision is in use",
        response = ProductInstanceMasterDTO.class,
        responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful retrieval of ProductInstanceMasterDTOs. It can be an empty list."),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Path("/used-by-product-instance-masters")
@Produces(MediaType.APPLICATION_JSON)
public Response getProductInstanceMasters(
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
        @ApiParam(required = true, value = "Part number") @PathParam("partNumber") String partNumber,
        @ApiParam(required = true, value = "Part version") @PathParam("partVersion") String partVersion)
        throws EntityNotFoundException, UserNotActiveException, AccessRightException, WorkspaceNotEnabledException {

    PartRevisionKey revisionKey = new PartRevisionKey(workspaceId, partNumber, partVersion);
    PartRevision partRevision = productService.getPartRevision(revisionKey);
    List<ProductInstanceMaster> productInstanceMasters = productInstanceService.getProductInstanceMasters(partRevision);
    List<ProductInstanceMasterDTO> productInstanceMasterDTOs = new ArrayList<>();

    for (ProductInstanceMaster productInstanceMaster : productInstanceMasters) {
        ProductInstanceMasterDTO productInstanceMasterDTO = mapper.map(productInstanceMaster, ProductInstanceMasterDTO.class);
        productInstanceMasterDTO.setProductInstanceIterations(null);
        productInstanceMasterDTO.setConfigurationItemId(productInstanceMaster.getInstanceOf().getId());
        productInstanceMasterDTOs.add(productInstanceMasterDTO);
    }
    return Response.ok(new GenericEntity<List<ProductInstanceMasterDTO>>((List<ProductInstanceMasterDTO>) productInstanceMasterDTOs) {
    }).build();
}