Java Code Examples for javax.ws.rs.core.MediaType#APPLICATION_JSON

The following examples show how to use javax.ws.rs.core.MediaType#APPLICATION_JSON . 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: ImAction.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "会话对象.", action = ActionGetConversation.class)
@GET
@Path("conversation/{id}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void conversation(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
                               @JaxrsParameterDescribe("会话id") @PathParam("id") String id) {
    ActionResult<ActionGetConversation.Wo> result = new ActionResult<>();
    EffectivePerson effectivePerson = this.effectivePerson(request);
    try {
        result = new ActionGetConversation().execute( effectivePerson, id );
    } catch (Exception e) {
        logger.error(e, effectivePerson, request, null);
        result.error(e);
    }
    asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 2
Source File: PartTemplateResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@DELETE
@ApiOperation(value = "Remove attached file from part master template",
        response = Response.class)
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Successful file deletion of PartMasterTemplateDTO"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Path("{templateId}/files/{fileName}")
@Consumes(MediaType.APPLICATION_JSON)
public Response removeAttachedFileFromPartTemplate(
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
        @ApiParam(required = true, value = "Template id") @PathParam("templateId") String templateId,
        @ApiParam(required = true, value = "File name") @PathParam("fileName") String fileName)
        throws EntityNotFoundException, AccessRightException, UserNotActiveException, WorkspaceNotEnabledException {

    String fileFullName = workspaceId + "/part-templates/" + templateId + "/" + fileName;
    productService.removeFileFromTemplate(fileFullName);
    return Response.noContent().build();
}
 
Example 3
Source File: PortalAction.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "创建新的Portal.需要对Portal模块的管理权限", action = ActionCreate.class)
@POST
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void create(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		JsonElement jsonElement) {
	ActionResult<ActionCreate.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionCreate().execute(effectivePerson, jsonElement);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, jsonElement);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 4
Source File: HierarchyService.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@POST
@Path("/deleteHierarchy")
@Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
@UserConstraint(functionalities = { SpagoBIConstants.HIERARCHIES_MANAGEMENT })
public String deleteHierarchy(@Context HttpServletRequest req) throws SQLException {
	// delete hierarchy
	Connection connection = null;
	try {

		JSONObject requestVal = RestUtilities.readBodyAsJSONObject(req);

		String dimension = requestVal.getString("dimension");
		String hierarchyName = requestVal.getString("name");

		// 1 - get datasource label name
		Hierarchies hierarchies = HierarchiesSingleton.getInstance();
		String dataSourceName = hierarchies.getDataSourceOfDimension(dimension);
		IDataSourceDAO dataSourceDAO = DAOFactory.getDataSourceDAO();
		IDataSource dataSource = dataSourceDAO.loadDataSourceByLabel(dataSourceName);

		// 2 - Execute DELETE
		connection = dataSource.getConnection();
		HierarchyUtils.deleteHierarchy(dimension, hierarchyName, dataSource, connection);

	} catch (Throwable t) {
		connection.rollback();
		logger.error("An unexpected error occured while deleting custom hierarchy");
		throw new SpagoBIServiceException("An unexpected error occured while deleting custom hierarchy", t);
	} finally {
		if (connection != null && !connection.isClosed())
			connection.close();
	}

	return "{\"response\":\"ok\"}";
}
 
Example 5
Source File: JsonValuejectionEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/verifyInjectedAudience")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("Tester")
public JsonObject verifyInjectedAudience(@QueryParam("aud") String audience) {
    boolean pass = false;
    String msg;
    // aud
    List<JsonString> audValue = aud.getValuesAs(JsonString.class);
    if(audValue == null || audValue.size() == 0) {
        msg = Claims.aud.name()+"value is null or empty, FAIL";
    }
    else if(audValue.get(0).getString().equals(audience)) {
        msg = Claims.aud.name()+" PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.aud.name(), audValue, audience);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example 6
Source File: ContextService.java    From semanticMDR with GNU General Public License v3.0 6 votes vote down vote up
@PUT
@Path("/property")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateProperty(
		@CookieParam(AuthenticationService.SID) String sessionID,
		@PathParam("contextid") String contextID,
		PropertyModel propertyModel) {
	WebUtil.checkUserSession(sessionID);
	Repository repository = RepositoryManager.getInstance().getRepository();

	Context context = repository.getContext(contextID);
	Property property = context.getProperty(propertyModel.getId());
	// Currently, only name and definition can be updated
	property.setName(propertyModel.getName());
	property.setDefinition(propertyModel.getDefinition());
	return Response.ok().build();
}
 
Example 7
Source File: ExecuteResource.java    From airpal with Apache License 2.0 6 votes vote down vote up
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response executeQuery(@Auth AirpalUser user, ExecutionRequest request) throws IOException
{
    if (user != null) {
        final UUID queryUuid = executionClient.runQuery(
                request,
                user,
                user.getDefaultSchema(),
                user.getQueryTimeout());

        return Response.ok(new ExecutionSuccess(queryUuid)).build();
    }

    return Response.status(Response.Status.NOT_FOUND)
                   .entity(new ExecutionError("No Airpal user found"))
                   .build();
}
 
Example 8
Source File: QueryResource.java    From airpal with Apache License 2.0 5 votes vote down vote up
@GET
@Path("saved")
@Produces(MediaType.APPLICATION_JSON)
public Response getSaved(
        @Auth AirpalUser user,
        @QueryParam("table") List<PartitionedTable> tables)
{
    if (user != null) {
        return Response.ok(queryStore.getSavedQueries(user)).build();
    }

    return Response.ok(Collections.<SavedQuery>emptyList()).build();
}
 
Example 9
Source File: DossierTemplateManagement.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@GET
@Path("/{id}/parts/{partno}/formscript")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get formscript of a DossierPart", response = DossierPartContentInputUpdateModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the formscript", response = DossierPartContentInputUpdateModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })

public Response getFormScript(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") String id, @PathParam("partno") String partno);
 
Example 10
Source File: UserManagement.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@GET
@Path("/{id}/sites")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getSites(@Context HttpServletRequest request, @Context HttpHeaders header, @Context Company company,
		@Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
		@PathParam("id") long id);
 
Example 11
Source File: EFormManagement.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@DELETE
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@ApiOperation(value = "get eForm from serviceFileTemplate", response = ServiceInfoInputModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a ServiceInfo entity was added", response = ServiceInfoInputModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response deleteEFromById(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") long id);
 
Example 12
Source File: YamlResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/preview/baseline")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiOperation("Get baseline from YAML configuration")
/* TODO: Will return baseline from yamlPreviewApi together with detection in the future. */
public Response yamlPreviewBaselineApi(
    @QueryParam("start") long start,
    @QueryParam("end") long end,
    @QueryParam("urn") @NotNull String urn,
    @QueryParam("tuningStart") long tuningStart,
    @QueryParam("tuningEnd") long tuningEnd,
    @ApiParam("jsonPayload") @NotNull String payload,
    @QueryParam("ruleName") String ruleName) {
  try {
    validatePayload(payload);
    DetectionConfigDTO detectionConfig = buildDetectionConfigFromYaml(tuningStart, tuningEnd, payload, null);
    Preconditions.checkNotNull(detectionConfig);
    detectionConfig.setId(Long.MAX_VALUE);

    // There is a side effect to update detectionConfig when loading the pipeline.
    this.loader.from(this.provider, detectionConfig, start, end);
    TimeSeries baseline = getBaseline(detectionConfig, start, end, urn, ruleName);

    return Response.ok(makeTimeSeriesMap(baseline)).build();
  } catch (Exception e) {
    LOG.error("Error getting baseline with payload " + payload, e);
  }
  return Response.ok().build();
}
 
Example 13
Source File: OpenstackManagementWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains a collection of all floating IPs.
 *
 * @return 200 OK with a collection of floating IPs, 404 not found
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("floatingips/all")
public Response allFloatingIps() {

    List<NetFloatingIP> floatingIps =
            Lists.newArrayList(osRouterAdminService.floatingIps());
    floatingIps.stream()
            .sorted(Comparator.comparing(NetFloatingIP::getFloatingIpAddress))
            .forEach(fip -> floatingipsNode.add(fip.getFloatingIpAddress()));

    return ok(root).build();
}
 
Example 14
Source File: InternetBanking.java    From javamoney-examples with Apache License 2.0 4 votes vote down vote up
@POST
@Path("/withdraw/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
MonetaryAmount withDraw(BankAccount account);
 
Example 15
Source File: DistroXAutoScaleClusterV1Endpoint.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@DELETE
@Path("crn/{crn}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = ClusterOpDescription.CLUSTER_DELETE_ALERTS, produces = MediaType.APPLICATION_JSON, notes = DistroXClusterNotes.NOTES)
void deleteAlertsForClusterCrn(@PathParam("crn") String clusterCrn);
 
Example 16
Source File: EventSubscriptionResource.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
EventSubscriptionDto getEventSubscription();
 
Example 17
Source File: LLCSegmentCompletionHandlers.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
@POST
@Path(SegmentCompletionProtocol.MSG_TYPE_COMMIT_END_METADATA)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String segmentCommitEndWithMetadata(@QueryParam(SegmentCompletionProtocol.PARAM_INSTANCE_ID) String instanceId,
    @QueryParam(SegmentCompletionProtocol.PARAM_SEGMENT_NAME) String segmentName,
    @QueryParam(SegmentCompletionProtocol.PARAM_SEGMENT_LOCATION) String segmentLocation,
    @QueryParam(SegmentCompletionProtocol.PARAM_OFFSET) long offset,
    @QueryParam(SegmentCompletionProtocol.PARAM_STREAM_PARTITION_MSG_OFFSET) String streamPartitionMsgOffset,
    @QueryParam(SegmentCompletionProtocol.PARAM_MEMORY_USED_BYTES) long memoryUsedBytes,
    @QueryParam(SegmentCompletionProtocol.PARAM_BUILD_TIME_MILLIS) long buildTimeMillis,
    @QueryParam(SegmentCompletionProtocol.PARAM_WAIT_TIME_MILLIS) long waitTimeMillis,
    @QueryParam(SegmentCompletionProtocol.PARAM_ROW_COUNT) int numRows,
    @QueryParam(SegmentCompletionProtocol.PARAM_SEGMENT_SIZE_BYTES) long segmentSizeBytes,
    FormDataMultiPart metadataFiles) {
  if (instanceId == null || segmentName == null || segmentLocation == null || metadataFiles == null
    || (offset == -1 && streamPartitionMsgOffset == null)) {
    LOGGER.error("Invalid call: offset={}, segmentName={}, instanceId={}, segmentLocation={}, streamPartitionMsgOffset={}",
        offset, segmentName, instanceId, segmentLocation, streamPartitionMsgOffset);
    // TODO: memoryUsedInBytes = 0 if not present in params. Add validation when we start using it
    return SegmentCompletionProtocol.RESP_FAILED.toJsonString();
  }

  SegmentCompletionProtocol.Request.Params requestParams = new SegmentCompletionProtocol.Request.Params();
  requestParams.withInstanceId(instanceId).withSegmentName(segmentName)
      .withSegmentLocation(segmentLocation).withSegmentSizeBytes(segmentSizeBytes)
      .withBuildTimeMillis(buildTimeMillis).withWaitTimeMillis(waitTimeMillis).withNumRows(numRows)
      .withMemoryUsedBytes(memoryUsedBytes);
  extractOffsetFromParams(requestParams, streamPartitionMsgOffset, offset);
  LOGGER.info("Processing segmentCommitEndWithMetadata:{}", requestParams.toString());

  SegmentMetadataImpl segmentMetadata;
  try {
    segmentMetadata = extractSegmentMetadataFromForm(metadataFiles, segmentName);
  } catch (Exception e) {
    LOGGER.error("Caught exception while extracting metadata for segment: {} from instance: {}", segmentName,
        instanceId, e);
    return SegmentCompletionProtocol.RESP_FAILED.toJsonString();
  }

  final boolean isSuccess = true;
  final boolean isSplitCommit = true;
  SegmentCompletionProtocol.Response response = _segmentCompletionManager
      .segmentCommitEnd(requestParams, isSuccess, isSplitCommit,
          CommittingSegmentDescriptor.fromSegmentCompletionReqParamsAndMetadata(requestParams, segmentMetadata));
  final String responseStr = response.toJsonString();
  LOGGER.info("Response to segmentCommitEndWithMetadata for segment:{} is:{}", segmentName, responseStr);
  return responseStr;
}
 
Example 18
Source File: AbstractResources.java    From jaxrs-analyzer with Apache License 2.0 4 votes vote down vote up
@GET
@Path("string")
@Produces(MediaType.APPLICATION_JSON)
public Object getString() {
    return new Object();
}
 
Example 19
Source File: ENWebService.java    From olat with Apache License 2.0 3 votes vote down vote up
/**
 * This attaches an enrollment element onto a given course, the element will be inserted underneath the supplied parentNodeId
 * 
 * @response.representation.mediaType application/x-www-form-urlencoded
 * @response.representation.doc The course node metadatas
 * @response.representation.200.qname {http://www.example.com}courseNodeVO
 * @response.representation.200.mediaType application/xml, application/json
 * @response.representation.200.doc The course node metadatas
 * @response.representation.200.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_COURSENODEVO}
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The course or parentNode not found
 * @param courseId
 *            The course resourceable's id
 * @param parentNodeId
 *            The node's id which will be the parent of this structure
 * @param position
 *            The node's position relative to its sibling nodes (optional)
 * @param shortTitle
 *            The node short title
 * @param longTitle
 *            The node long title
 * @param objectives
 *            The node learning objectives
 * @param visibilityExpertRules
 *            The rules to view the node (optional)
 * @param accessExpertRules
 *            The rules to access the node (optional)
 * @param groups
 *            send the message to the specified groups
 * @param cancelEnabled
 *            cancel enrollment enabled or not
 * @param request
 *            The HTTP request
 * @return The persisted contact element (fully populated)
 */
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response attachEnrollmenetPost(@PathParam("courseId") final Long courseId, @FormParam("parentNodeId") final String parentNodeId,
        @FormParam("position") final Integer position, @FormParam("shortTitle") @DefaultValue("undefined") final String shortTitle,
        @FormParam("longTitle") @DefaultValue("undefined") final String longTitle, @FormParam("objectives") @DefaultValue("undefined") final String objectives,
        @FormParam("visibilityExpertRules") final String visibilityExpertRules, @FormParam("accessExpertRules") final String accessExpertRules,
        @FormParam("groups") final String groups, @FormParam("cancelEnabled") @DefaultValue("false") final boolean cancelEnabled,
        @Context final HttpServletRequest request) {
    final EnrollmentConfigDelegate config = new EnrollmentConfigDelegate(groups, cancelEnabled);
    return attach(courseId, parentNodeId, "en", position, shortTitle, longTitle, objectives, visibilityExpertRules, accessExpertRules, config, request);
}
 
Example 20
Source File: UserRequestService.java    From syncope with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a user request form matching the given task id.
 *
 * @param username username of the logged user
 * @param taskId workflow task id
 * @return the form for the given task id
 */
@GET
@Path("forms/{username}/{taskId}")
@Produces({ MediaType.APPLICATION_JSON, RESTHeaders.APPLICATION_YAML, MediaType.APPLICATION_XML })
UserRequestForm getForm(
        @NotNull @PathParam("username") String username,
        @NotNull @PathParam("taskId") String taskId);