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

The following examples show how to use javax.ws.rs.core.MediaType. These examples are extracted from open source projects. 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 Project: o2oa   Source File: MeetingAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "列示我参与从当前日期开始指定日期范围的会议,或者被邀请,或者是申请人,或者是审核人,管理员可以看到所有.", action = ActionListComingDay.class)
@GET
@Path("list/coming/day/{count}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listComingDay(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		@PathParam("count") Integer count) {
	ActionResult<List<ActionListComingDay.Wo>> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionListComingDay().execute(effectivePerson, count);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 2
Source Project: o2oa   Source File: DataAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "更新指定Document的Data数据.", action = ActionUpdateWithDocumentPath1.class)
@PUT
@Path("document/{id}/{path0}/{path1}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void updateWithDocumentWithPath1(@Suspended final AsyncResponse asyncResponse,
		@Context HttpServletRequest request, @JaxrsParameterDescribe("文档ID") @PathParam("id") String id,
		@JaxrsParameterDescribe("0级路径") @PathParam("path0") String path0,
		@JaxrsParameterDescribe("1级路径") @PathParam("path1") String path1, JsonElement jsonElement) {
	ActionResult<ActionUpdateWithDocumentPath1.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionUpdateWithDocumentPath1().execute(effectivePerson, id, path0, path1, jsonElement);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, jsonElement);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 3
Source Project: o2oa   Source File: WorkAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "指定文件增加一个副本.", action = ActionAddSplit.class)
@PUT
@Path("{id}/add/split")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void addSplit(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		@JaxrsParameterDescribe("工作标识") @PathParam("id") String id, JsonElement jsonElement) {
	ActionResult<List<ActionAddSplit.Wo>> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionAddSplit().execute(effectivePerson, id, jsonElement);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 4
Source Project: onos   Source File: PortPairResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests deleting a port pair.
 */
@Test
public void testDelete() {
    expect(portPairService.removePortPair(anyObject()))
    .andReturn(true).anyTimes();
    replay(portPairService);

    WebTarget wt = target();

    String location = "port_pairs/78dcd363-fc23-aeb6-f44b-56dc5e2fb3ae";

    Response deleteResponse = wt.path(location)
            .request(MediaType.APPLICATION_JSON_TYPE, MediaType.TEXT_PLAIN_TYPE)
            .delete();
    assertThat(deleteResponse.getStatus(),
               is(HttpURLConnection.HTTP_NO_CONTENT));
}
 
Example 5
@JaxrsMethodDescribe(value = "获取所有已经上传成功的文件列表", action = ActionListAll.class)
@GET
@Path("list/all")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listAllAttendanceImportFileInfo(@Suspended final AsyncResponse asyncResponse,
		@Context HttpServletRequest request) {
	ActionResult<List<ActionListAll.Wo>> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	Boolean check = true;

	if (check) {
		try {
			result = new ActionListAll().execute(request, effectivePerson);
		} catch (Exception e) {
			result = new ActionResult<>();
			Exception exception = new ExceptionAttendanceImportFileProcess(e, "获取所有已经上传成功的文件时发生异常!");
			result.error(exception);
			logger.error(e, effectivePerson, request, null);
		}
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 6
Source Project: o2oa   Source File: CodeAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "级联验证code验证码", action = ActionValidateCascade.class)
@GET
@Path("validate/mobile/{mobile}/answer/{answer}/cascade")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void validateCascade(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		@JaxrsParameterDescribe("手机号") @PathParam("mobile") String mobile,
		@JaxrsParameterDescribe("验证码") @PathParam("answer") String answer) {
	ActionResult<ActionValidateCascade.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionValidateCascade().execute(mobile, answer);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 7
Source Project: openregistry   Source File: SystemOfRecordRolesResource.java    License: Apache License 2.0 6 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_XML)
public Response processIncomingRole(@PathParam("sorSourceId") final String sorSourceId,
                                    @PathParam("sorPersonId") final String sorPersonId,
                                    final RoleRepresentation roleRepresentation) {

    final SorPerson sorPerson = (SorPerson) findPersonAndRoleOrThrowNotFoundException(sorSourceId, sorPersonId, null).get("person");
    final SorRole sorRole = buildSorRoleFrom(sorPerson, roleRepresentation);
    final ServiceExecutionResult<SorRole> result = this.personService.validateAndSaveRoleForSorPerson(sorPerson, sorRole);
    if (!result.getValidationErrors().isEmpty()) {
        //HTTP 400
        return Response.status(Response.Status.BAD_REQUEST).
                entity(new ErrorsResponseRepresentation(ValidationUtils.buildValidationErrorsResponseAsList(result.getValidationErrors())))
                .type(MediaType.APPLICATION_XML).build();
    }

    //HTTP 201
    return Response.created(this.uriInfo.getAbsolutePathBuilder()
            .path(result.getTargetObject().getSorId())
            .build())
            .build();
}
 
Example 8
Source Project: hadoop   Source File: TestHsWebServicesJobsQuery.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryStartTimeEndNegative() throws JSONException,
    Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs")
      .queryParam("startedTimeEnd", String.valueOf(-1000))
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
  assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject msg = response.getEntity(JSONObject.class);
  JSONObject exception = msg.getJSONObject("RemoteException");
  assertEquals("incorrect number of elements", 3, exception.length());
  String message = exception.getString("message");
  String type = exception.getString("exception");
  String classname = exception.getString("javaClassName");
  WebServicesTestUtils.checkStringMatch("exception message",
      "java.lang.Exception: startedTimeEnd must be greater than 0", message);
  WebServicesTestUtils.checkStringMatch("exception type",
      "BadRequestException", type);
  WebServicesTestUtils.checkStringMatch("exception classname",
      "org.apache.hadoop.yarn.webapp.BadRequestException", classname);
}
 
Example 9
Source Project: emodb   Source File: UserAccessControlClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void createRole(String apiKey, CreateEmoRoleRequest request)
        throws EmoRoleExistsException {
    checkNotNull(request, "request");
    EmoRoleKey roleKey = checkNotNull(request.getRoleKey(), "roleKey");
    try {
        URI uri = _uac.clone()
                .segment("role")
                .segment(roleKey.getGroup())
                .segment(roleKey.getId())
                .build();
        _client.resource(uri)
                .type(APPLICATION_X_CREATE_ROLE_TYPE)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey)
                .post(JsonHelper.asJson(request));
    } catch (EmoClientException e) {
        throw convertException(e);
    }
}
 
Example 10
Source Project: wings   Source File: PlannerResource.java    License: Apache License 2.0 6 votes vote down vote up
@POST
@Path("getParameters")
@Produces(MediaType.APPLICATION_JSON)
public StreamingOutput getParameters(
    @JsonProperty("template_bindings") final TemplateBindings tbindings) {
  if(this.wp != null) {
    return new StreamingOutput() {
      @Override
      public void write(OutputStream os) throws IOException,
          WebApplicationException {
        PrintWriter out = new PrintWriter(os);
        wp.printSuggestedParametersJSON(tbindings, noexplain, out);
        out.flush();
      }
    };
  }
  return null;
}
 
Example 11
Source Project: openregistry   Source File: SystemOfRecordPeopleResource.java    License: Apache License 2.0 6 votes vote down vote up
@PUT
@Path("{sorPersonId}")
@Consumes(MediaType.APPLICATION_XML)
public Response updateIncomingPerson(@PathParam("sorSourceId") final String sorSourceId, @PathParam("sorPersonId") final String sorPersonId, final PersonRequestRepresentation request) {
    final SorPerson sorPerson = findPersonOrThrowNotFoundException(sorSourceId, sorPersonId);
    PeopleResourceUtils.buildModifiedSorPerson(request, sorPerson,this.referenceRepository);

    try {
        ServiceExecutionResult<SorPerson> result = this.personService.updateSorPerson(sorPerson);

        if (!result.getValidationErrors().isEmpty()) {
            //HTTP 400
            logger.info("The incoming person payload did not pass validation. Validation errors: " + result.getValidationErrors());
            return Response.status(Response.Status.BAD_REQUEST).
                    entity(new ErrorsResponseRepresentation(ValidationUtils.buildValidationErrorsResponseAsList(result.getValidationErrors())))
                    .type(MediaType.APPLICATION_XML).build();
        }
    }
    catch (IllegalStateException e) {
        return Response.status(409).entity(new ErrorsResponseRepresentation(Arrays.asList(e.getMessage())))
                .type(MediaType.APPLICATION_XML).build();
    }

    //HTTP 204
    return null;
}
 
Example 12
Source Project: mobi   Source File: OntologyRest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns IRIs in the imports closure for the ontology identified by the provided IDs.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return IRIs in the ontology identified by the provided IDs.
 */
@GET
@Path("{recordId}/imported-iris")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Gets the IRIs from the imported ontologies of the identified ontology.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getIRIsInImportedOntologies(@Context ContainerRequestContext context,
                                            @PathParam("recordId") String recordIdStr,
                                            @QueryParam("branchId") String branchIdStr,
                                            @QueryParam("commitId") String commitIdStr) {
    try {
        return doWithImportedOntologies(context, recordIdStr, branchIdStr, commitIdStr, this::getAllIRIs);
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example 13
@GET
@Path(WebConstants.CLUSTERWIDE_MAJORCOUNTERS + "/{clusterName}")
@Produces(MediaType.APPLICATION_JSON)
public Response getClusterWideMajorCounters(@PathParam(CLUSTER_NAME) String clusterName) {
	try {
		Cluster cluster = cache.getCluster(clusterName);
		MajorCounters majorCounters = MajorCounters.getInstance();
		Map<String, String> counters = majorCounters.getMajorCounters(cluster);

		counters.putAll(metrics.getFaultyBlocks(cluster));
		return Response.ok(Constants.gson.toJson(counters)).build();
	} catch (Exception e) {
		LOGGER.error("Unable to get cluster wide major counters", e);
		return Response.status(Status.INTERNAL_SERVER_ERROR).build();
	}
}
 
Example 14
Source Project: boost   Source File: InventoryHealth.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public boolean isHealthy() {
    if (config.isInMaintenance()) {
        return false;
    }
    try {
        String url = invUtils.buildUrl("http", "localhost",
                // Integer.parseInt(System.getProperty("default.http.port")),
                9080, "/system/properties");
        Client client = ClientBuilder.newClient();
        Response response = client.target(url).request(MediaType.APPLICATION_JSON).get();
        if (response.getStatus() != 200) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 15
Source Project: atomix   Source File: AtomicCounterResource.java    License: Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/{name}")
@Consumes(MediaType.TEXT_PLAIN)
public void set(
    @PathParam("name") String name,
    Long value,
    @Suspended AsyncResponse response) {
  getPrimitive(name).thenCompose(counter -> counter.set(value)).whenComplete((result, error) -> {
    if (error == null) {
      response.resume(Response.ok().build());
    } else {
      LOGGER.warn("{}", error);
      response.resume(Response.serverError().build());
    }
  });
}
 
Example 16
Source Project: cougar   Source File: ContentTypeNormaliserImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public MediaType getNormalisedResponseMediaType(HttpServletRequest request) {
    // Negotiate Response format
    MediaType responseMediaType;
    String responseFormat = getResponseFormat(request);
    try {
        List<MediaType> acceptMT = MediaTypeUtils.parseMediaTypes(responseFormat);

        responseMediaType = MediaTypeUtils.getResponseMediaType(allContentTypes, acceptMT);
        if (responseMediaType == null) {
            throw new CougarValidationException(ServerFaultCode.AcceptTypeNotValid, "Could not agree a response media type");
        } else if (responseMediaType.isWildcardType() || responseMediaType.isWildcardSubtype()) {
            throw new CougarServiceException(ServerFaultCode.ResponseContentTypeNotValid,
                    "Service configuration error - response media type must not be a wildcard - " + responseMediaType);
        }

    } catch (IllegalArgumentException e) {
        throw new CougarValidationException(ServerFaultCode.MediaTypeParseFailure, "Unable to parse supplied media types (" + responseFormat + ")",e);
    }
    return responseMediaType;
}
 
Example 17
Source Project: onos   Source File: RegionsResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests updating a region with PUT.
 */
@Test
public void testRegionPut() {
    mockRegionAdminService.updateRegion(anyObject(), anyObject(),
            anyObject(), anyObject());
    expectLastCall().andReturn(region1).anyTimes();
    replay(mockRegionAdminService);

    WebTarget wt = target();
    InputStream jsonStream = RegionsResourceTest.class
            .getResourceAsStream("post-region.json");

    Response response = wt.path("regions/" + region1.id().toString())
            .request(MediaType.APPLICATION_JSON_TYPE)
            .put(Entity.json(jsonStream));
    assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK));

    verify(mockRegionAdminService);
}
 
Example 18
Source Project: o2oa   Source File: FileAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "复制资源文件到新的应用.", action = ActionCopy.class)
@GET
@Path("{flag}/appInfo/{appInfoFlag}")
@Consumes(MediaType.APPLICATION_JSON)
public void copy(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		@JaxrsParameterDescribe("标识") @PathParam("flag") String flag,
		@JaxrsParameterDescribe("应用标识") @PathParam("appInfoFlag") String appInfoFlag) {
	ActionResult<ActionCopy.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = ((ActionCopy)proxy.getProxy(ActionCopy.class)).execute(effectivePerson, flag, appInfoFlag);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 19
Source Project: MaximoForgeViewerPlugin   Source File: ForgeRS.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@POST
   @Produces(MediaType.APPLICATION_JSON)
   @Path("bucket/{bucketKey}")
   public Response bucketCreate(
    	@Context HttpServletRequest request,
	@PathParam("bucketKey") String bucketKey,
	@QueryParam("policy") String policy,
	@QueryParam("region") String region
) 
	throws IOException, 
	       URISyntaxException 
   {
   	APIImpl impl = getAPIImpl( request );
   	if( impl == null )
   	{
           return Response.status( Response.Status.UNAUTHORIZED ).build();     
   	}
   	Result result = impl.bucketCreate( bucketKey, policy, region );
   	return formatReturn( result );
   }
 
Example 20
Source Project: entity-fishing   Source File: NerdRestService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see NerdRestProcessGeneric#getVersion()
 */
@GET
@Path(NerdPaths.VERSION)
@Produces(MediaType.APPLICATION_JSON)
public Response getVersion() {
    Response response = null;
    try {
        response = Response.status(Response.Status.OK)
                .entity(NerdRestProcessGeneric.getVersion())
                .type(MediaType.APPLICATION_JSON)
                .build();

    } catch (Exception e) {
        LOGGER.error("An unexpected exception occurs. ", e);
        response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }

    return response;
}
 
Example 21
@JaxrsMethodDescribe(value = "列示满足过滤条件查询的工作汇报信息,[已归档],上一页", action = ActionListMyArchivePrevWithFilter.class)
@PUT
@Path("archive/list/{id}/prev/{count}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listMyArchivePrevWithFilter(@Suspended final AsyncResponse asyncResponse,
		@Context HttpServletRequest request, @JaxrsParameterDescribe("最后一条信息数据的ID") @PathParam("id") String id,
		@JaxrsParameterDescribe("每页显示的条目数量") @PathParam("count") Integer count, JsonElement jsonElement) {
	EffectivePerson effectivePerson = this.effectivePerson(request);
	ActionResult<List<ActionListMyArchivePrevWithFilter.Wo>> result = new ActionResult<>();
	try {
		result = new ActionListMyArchivePrevWithFilter().execute(request, effectivePerson, id, count, jsonElement);
	} catch (Exception e) {
		result = new ActionResult<>();
		result.error(e);
		logger.warn("system excute ExcuteGet got an exception. ");
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 22
Source Project: ice   Source File: RemoteCoreProxy.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * (non-Javadoc)
 * 
 * @see ICore#connect()
 */
@Override
public String connect() {

	// Only load the resource if the hostname is valid
	if (host != null) {
		baseResource = client.resource(host + ":" + serverPort + "/ice");
	} else {
		return "-1";
	}
	String response = baseResource.accept(MediaType.TEXT_PLAIN)
			.header("X-FOO", "BAR").get(String.class);

	logger.info("RemoteCoreProxy connection information: ");
	logger.info("\tHostname: " + host);
	logger.info("\tPort: " + serverPort);
	logger.info("\tUnique Client Id: " + response);

	return response;
}
 
Example 23
Source Project: io   Source File: UserDataGetTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * UserDataの取得で$formatにatomを指定した場合レスポンスがxml形式になること.
 */
@Test
public final void UserDataの取得で$formatにatomを指定した場合レスポンスがxml形式になること() {

    try {
        createUserData();

        // ユーザデータの取得
        TResponse response = getUserData(cellName, boxName, colName, entityTypeName,
                userDataId, AbstractCase.MASTER_TOKEN_NAME, "?\\$format=atom", HttpStatus.SC_OK);

        assertEquals(MediaType.APPLICATION_ATOM_XML, response.getHeader(HttpHeaders.CONTENT_TYPE));
        response.bodyAsXml();
    } finally {
        deleteUserData(userDataId);
    }
}
 
Example 24
@Test
public void empty() {
	ClientResponse res;
	res = request("rdf/update")
		.get(ClientResponse.class);
	assertEquals("Should return 405 response code", 405, res.getStatus());
	Form f = new Form();
	f.add("update", "");
	res = request("rdf/update")
		.type(MediaType.APPLICATION_FORM_URLENCODED)
		.entity(f)
		.post(ClientResponse.class);
	assertEquals("Should return 400 response code", 400, res.getStatus());
	res = request("rdf/update")
		.type(RDFMediaType.SPARQL_UPDATE)
		.post(ClientResponse.class);
	assertEquals("Should return 200 response code", 400, res.getStatus());
}
 
Example 25
Source Project: o2oa   Source File: WorkAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "添加人工环节处理人,不会自动产生,需要processing之后才会执行.", action = ActionManualAppendIdentity.class)
@PUT
@Path("{id}/manual/append/identity")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void manualAppendIdentity(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		@JaxrsParameterDescribe("工作标识") @PathParam("id") String id, JsonElement jsonElement) {
	ActionResult<ActionManualAppendIdentity.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionManualAppendIdentity().execute(effectivePerson, id, jsonElement);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 26
@JaxrsMethodDescribe(value = "新建或者更新工作汇报详细信息", action = ActionSave.class)
@POST
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void post(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		JsonElement jsonElement) {
	EffectivePerson effectivePerson = this.effectivePerson(request);
	ActionResult<ActionSave.Wo> result = new ActionResult<>();
	try {
		result = new ActionSave().execute(request, effectivePerson, jsonElement);
	} catch (Exception e) {
		result = new ActionResult<>();
		result.error(e);
		logger.warn("system excute ExcuteGet got an exception. ");
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example 27
Source Project: eplmp   Source File: PartResource.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@GET
@ApiOperation(value = "Get part revision",
        response = PartRevisionDTO.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful retrieval of PartRevisionDTO"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Produces(MediaType.APPLICATION_JSON)
public Response getPartRevision(
        @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);
    PartRevisionDTO partRevisionDTO = Tools.mapPartRevisionToPartDTO(partRevision);

    PartIterationKey iterationKey = new PartIterationKey(revisionKey, partRevision.getLastIterationNumber());
    List<ModificationNotification> notifications = productService.getModificationNotifications(iterationKey);
    List<ModificationNotificationDTO> notificationDTOs = Tools.mapModificationNotificationsToModificationNotificationDTO(notifications);
    partRevisionDTO.setNotifications(notificationDTOs);

    return Response.ok(partRevisionDTO).build();
}
 
Example 28
Source Project: open-Autoscaler   Source File: CouchDBScalingRestApi.java    License: Apache License 2.0 5 votes vote down vote up
@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response createDocument(@Context final HttpServletRequest httpServletRequest,
			 String jsonString) {

//		String jsonStr = "{\"ok\": true,\"id\": \"2d642054-5675-44b2-9304-af58b1648365\",\"rev\": \"2-24c637da3fa1164b1a5fe05a35456e1c\"}";
		
		String jsonStr = CouchDBDocumentManager.getInstance().addDocument(jsonString).toString();
		return RestApiResponseHandler.getResponse(201, jsonStr);

	}
 
Example 29
Source Project: ameba   Source File: StatusMapper.java    License: MIT License 5 votes vote down vote up
private MediaType parseMediaType(List<MediaType> types) {
    if (types != null && types.size() > 0) {
        return types.get(0);
    } else {
        return MediaType.TEXT_HTML_TYPE;
    }
}
 
Example 30
@POST
@Path("/createUser")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void createUser(@FormParam("user") String user, @FormParam("password") String password, @FormParam("email") String email,
                       @FormParam("name") String name, @FormParam("active") boolean active) throws GenericException {
	try {
		log.debug("createUser({}, {}, {}, {}, {})", new Object[]{user, password, email, name, active});
		AuthModule am = ModuleManager.getAuthModule();
		am.createUser(null, user, password, email, name, active);
		log.debug("createUser: void");
	} catch (Exception e) {
		throw new GenericException(e);
	}
}