javax.ws.rs.core.MediaType#APPLICATION_JSON源码实例Demo

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

源代码1 项目: o2oa   文件: ImAction.java
@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));
}
 
源代码2 项目: eplmp   文件: PartTemplateResource.java
@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();
}
 
源代码3 项目: o2oa   文件: PortalAction.java
@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));
}
 
源代码4 项目: semanticMDR   文件: ContextService.java
@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();
}
 
源代码5 项目: airpal   文件: ExecuteResource.java
@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();
}
 
@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;
}
 
源代码7 项目: airpal   文件: QueryResource.java
@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();
}
 
源代码8 项目: opencps-v2   文件: DossierTemplateManagement.java
@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);
 
源代码9 项目: opencps-v2   文件: UserManagement.java
@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);
 
源代码10 项目: Knowage-Server   文件: HierarchyService.java
@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\"}";
}
 
源代码11 项目: incubator-pinot   文件: YamlResource.java
@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();
}
 
源代码12 项目: onos   文件: OpenstackManagementWebResource.java
/**
 * 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();
}
 
源代码13 项目: opencps-v2   文件: EFormManagement.java
@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);
 
源代码14 项目: jaxrs-analyzer   文件: AbstractResources.java
@GET
@Path("string")
@Produces(MediaType.APPLICATION_JSON)
public Object getString() {
    return new Object();
}
 
@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;
}
 
@GET
@Produces(MediaType.APPLICATION_JSON)
EventSubscriptionDto getEventSubscription();
 
@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);
 
源代码18 项目: javamoney-examples   文件: InternetBanking.java
@POST
@Path("/withdraw/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
MonetaryAmount withDraw(BankAccount account);
 
源代码19 项目: syncope   文件: UserRequestService.java
/**
 * 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);
 
源代码20 项目: olat   文件: ENWebService.java
/**
 * 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);
}