下面列出了怎么用javax.ws.rs.core.Response的API类实例代码及写法,或者点击链接到github查看源代码。
@POST
@Consumes({MediaType.TEXT_PLAIN})
public Response notificationEndpoint(@HeaderParam("x-amz-sns-message-type") String messageType, String message) throws JsonProcessingException {
if (messageType == null) {
return Response.status(400).build();
}
if (messageType.equals(NOTIFICATION_TYPE)) {
SnsNotification notification = readObject(SnsNotification.class, message);
Quark quark = readObject(Quark.class, notification.getMessage());
LOGGER.infov("Quark[{0}, {1}] collision with the shield.", quark.getFlavor(), quark.getSpin());
} else if (messageType.equals(SUBSCRIPTION_CONFIRMATION_TYPE)) {
SnsSubscriptionConfirmation subConf = readObject(SnsSubscriptionConfirmation.class, message);
sns.confirmSubscription(cs -> cs.topicArn(topicArn).token(subConf.getToken()));
LOGGER.info("Subscription confirmed. Ready for quarks collisions.");
} else if (messageType.equals(UNSUBSCRIPTION_CONFIRMATION_TYPE)) {
LOGGER.info("We are unsubscribed");
} else {
return Response.status(400).entity("Unknown messageType").build();
}
return Response.ok().build();
}
@POST
@Path("/{plan}/instances/{instance}/logs")
@Consumes( {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces( {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@ApiOperation(hidden = true, value = "")
public Response addBuildPlanLogEntry(@PathParam("plan") final String plan,
@PathParam("instance") final String instance, @Context final UriInfo uriInfo,
final CreatePlanInstanceLogEntryRequest logEntry) {
LOGGER.debug("Invoking addBuildPlanLogEntry");
final String entry = logEntry.getLogEntry();
if (entry == null || entry.length() <= 0) {
LOGGER.info("Log entry is empty!");
return Response.status(Status.BAD_REQUEST).build();
}
PlanInstance pi = planService.resolvePlanInstance(csar, serviceTemplate, null, plan, instance, PLAN_TYPE);
final PlanInstanceEvent event = new PlanInstanceEvent("INFO", "PLAN_LOG", entry);
planService.addLogToPlanInstance(pi, event);
final URI resourceUri = uriInfo.getAbsolutePath();
return Response.ok(resourceUri).build();
}
@GET
@RolesAllowed({ Role.USER, Role.ADMIN })
@Path("/{thingUID}/status")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets thing's status.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class),
@ApiResponse(code = 404, message = "Thing not found.") })
public Response getStatus(
@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language,
@PathParam("thingUID") @ApiParam(value = "thing") String thingUID) throws IOException {
ThingUID thingUIDObject = new ThingUID(thingUID);
// Check if the Thing exists, 404 if not
Thing thing = thingRegistry.get(thingUIDObject);
if (thing == null) {
logger.info("Received HTTP GET request for thing config status at '{}' for the unknown thing '{}'.",
uriInfo.getPath(), thingUID);
return getThingNotFoundResponse(thingUID);
}
ThingStatusInfo thingStatusInfo = thingStatusInfoI18nLocalizationService.getLocalizedThingStatusInfo(thing,
localeService.getLocale(language));
return Response.ok().entity(thingStatusInfo).build();
}
@Test
public void testEventPost_shouldSendExecuteTaskIfItIsNotCompleted() throws Exception {
final EventData testEventData = new EventData("event0", "java.lang.String", "42", "runtime");
when(eventsDAO.findBySMIdAndName("standard-machine", "event0")).thenReturn(new Event("event0", "java.lang.String", Event.EventStatus.pending, "1", null, null));
EventData[] expectedEvents = new EventData[]{new EventData("event0", "java.lang.String", "42", "runtime")};
when(eventsDAO.findTriggeredOrCancelledEventsNamesBySMId("standard-machine")).thenReturn(Collections.singletonList("event0"));
when(executionNodeTaskDispatcher.forwardExecutionMessage(anyString(), anyObject())).thenReturn(Response.Status.ACCEPTED.getStatusCode());
workFlowExecutionController.postEvent(testEventData, "standard-machine");
StateMachine stateMachine = stateMachinesDAO.findById("standard-machine");
State state = stateMachinesDAO.findById("standard-machine").getStates().stream().filter((s) -> s.getId() == 4L).findFirst().orElse(null);
state.setStatus(Status.errored);
//post the event again, this should send msg to router again for execution
workFlowExecutionController.postEvent(testEventData, "standard-machine");
verify(executionNodeTaskDispatcher, times(2)).forwardExecutionMessage(anyString(), anyObject());
verifyNoMoreInteractions(executionNodeTaskDispatcher);
}
@Test
public void shouldGetIdentityProvider() {
final String domainId = "domain-id";
final Domain mockDomain = new Domain();
mockDomain.setId(domainId);
final String identityProviderId = "identityProvider-id";
final IdentityProvider mockIdentityProvider = new IdentityProvider();
mockIdentityProvider.setId(identityProviderId);
mockIdentityProvider.setName("identityProvider-name");
mockIdentityProvider.setReferenceType(ReferenceType.DOMAIN);
mockIdentityProvider.setReferenceId(domainId);
doReturn(Maybe.just(mockDomain)).when(domainService).findById(domainId);
doReturn(Maybe.just(mockIdentityProvider)).when(identityProviderService).findById(identityProviderId);
final Response response = target("domains").path(domainId).path("identities").path(identityProviderId).request().get();
assertEquals(HttpStatusCode.OK_200, response.getStatus());
final IdentityProvider identityProvider = readEntity(response, IdentityProvider.class);
assertEquals(domainId, identityProvider.getReferenceId());
assertEquals(identityProviderId, identityProvider.getId());
}
@Test
public void testDeleteAnalysisSuccess() throws IOException {
String network = "network1";
String analysis = "analysis1";
Main.getWorkMgr().initNetwork(network, null);
Main.getWorkMgr()
.configureAnalysis(
network, true, analysis, ImmutableMap.of("foo", "{}"), ImmutableList.of(), false);
// should succeed first time
try (Response response = getTarget(network, analysis).delete()) {
assertThat(response.getStatus(), equalTo(OK.getStatusCode()));
}
// should fail second time
try (Response response = getTarget(network, analysis).delete()) {
assertThat(response.getStatus(), equalTo(NOT_FOUND.getStatusCode()));
}
}
/**
* OPTIONSメソッド.
* @return JAX-RS Response
*/
@OPTIONS
public Response options() {
// アクセス制御
this.checkAccessContext(this.getAccessContext(), BoxPrivilege.READ);
return DcCoreUtils.responseBuilderForOptions(
HttpMethod.GET,
HttpMethod.PUT,
HttpMethod.DELETE,
com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.MKCOL,
com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.PROPFIND,
com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.PROPPATCH,
com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.ACL
).build();
}
@Test(description = "Test the device enrollment success scenario.")
public void testEnrollDeviceSuccess() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser"))
.toReturn(AUTHENTICATED_USER);
EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
demoDevice.setEnrolmentInfo(enrolmentInfo);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(demoDevice);
Response response = this.deviceAgentService.enrollDevice(demoDevice);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"The response status should be 200");
Mockito.reset(this.deviceManagementProviderService);
}
@POST
@Path("/{name}/increase")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void increase(
@PathParam("name") String name,
Integer permits,
@Suspended AsyncResponse response) {
getPrimitive(name).thenCompose(semaphore -> semaphore.increasePermits(permits != null ? permits : 1)).whenComplete((result, error) -> {
if (error == null) {
response.resume(Response.ok(result).build());
} else {
LOGGER.warn("An error occurred", error);
response.resume(Response.serverError());
}
});
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/genJson")
public Response generateJSONFromLastestJSON(@QueryParam("collectionCode") String collectionCode,
@DefaultValue(DownloadType.TEXT_JSON) @QueryParam("jsonType") String jsonType) throws UnknownHostException {
logger.info("Received request for collection: " + collectionCode + " with jsonType = " + jsonType);
JsonDeserializer jsonD = new JsonDeserializer();
String fileName = jsonD.generateJSON2JSON_100K_BasedOnTweetCount(collectionCode, DownloadJsonType.getDownloadJsonTypeFromString(jsonType));
fileName = PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.PERSISTER_DOWNLOAD_URL) + collectionCode+"/"+fileName;
logger.info("Done processing request for collection: " + collectionCode + ", returning created file: " + fileName);
//return Response.ok(fileName).build();
JSONObject obj = new JSONObject();
obj.putAll(ResultStatus.getUIWrapper(collectionCode, null, fileName, true));
logger.info("Returning JSON object: " + ResultStatus.getUIWrapper(collectionCode, null, fileName, true));
return Response.ok(obj.toJSONString()).build();
}
@GET
@RolesAllowed({"IbisObserver", "IbisDataAdmin", "IbisAdmin", "IbisTester"})
@Path("/configurations/{configuration}/flow")
@Produces(MediaType.TEXT_PLAIN)
public Response getAdapterFlow(@PathParam("configuration") String configurationName, @QueryParam("dot") boolean dot) throws ApiException {
Configuration configuration = getIbisManager().getConfiguration(configurationName);
if(configuration == null){
throw new ApiException("Configuration not found!");
}
FlowDiagramManager flowDiagramManager = getFlowDiagramManager();
try {
ResponseBuilder response = Response.status(Response.Status.OK);
if(dot) {
response.entity(flowDiagramManager.generateDot(configuration)).type(MediaType.TEXT_PLAIN);
} else {
response.entity(flowDiagramManager.get(configuration)).type("image/svg+xml");
}
return response.build();
} catch (SAXException | TransformerException | IOException e) {
throw new ApiException(e);
}
}
@POST
@Path("/add")
@SubmarineApi
public Response add(SysUser sysUser) {
LOG.info("add({})", sysUser.toString());
try {
userService.add(sysUser);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return new JsonResponse.Builder<>(Response.Status.OK).success(false)
.message("Save user failed!").build();
}
return new JsonResponse.Builder<SysUser>(Response.Status.OK)
.success(true).message("Save user successfully!").result(sysUser).build();
}
public List<String> getUserProfiles(Properties properties) throws Throwable {
List<String> usernames = null;
try {
String userProfileType = properties.getProperty("typeCode");
IUserProfile prototype = (IUserProfile) this.getUserProfileManager().getEntityPrototype(userProfileType);
if (null == prototype) {
throw new ApiException(IApiErrorCodes.API_PARAMETER_VALIDATION_ERROR,
"Profile Type '" + userProfileType + "' does not exist", Response.Status.CONFLICT);
}
String langCode = properties.getProperty(SystemConstants.API_LANG_CODE_PARAMETER);
String filtersParam = properties.getProperty("filters");
BaseFilterUtils filterUtils = new BaseFilterUtils();
EntitySearchFilter[] filters = filterUtils.getFilters(prototype, filtersParam, langCode);
usernames = this.getUserProfileManager().searchId(userProfileType, filters);
} catch (ApiException ae) {
throw ae;
} catch (Throwable t) {
_logger.error("Error searching usernames", t);
//ApsSystemUtils.logThrowable(t, this, "getUserProfiles");
throw new ApsSystemException("Error searching usernames", t);
}
return usernames;
}
@PUT
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
public Response modifyI18NMessage(SbiI18NMessages message) {
I18NMessagesDAO I18NMessagesDAO = null;
try {
I18NMessagesDAO = DAOFactory.getI18NMessageDAO();
// If updating Default Message Label, find others with particular Label and update them as well
SbiI18NMessages messageBeforeUpdate = I18NMessagesDAO.getSbiI18NMessageById(message.getId());
if (!message.getLabel().equals(messageBeforeUpdate.getLabel())) {
I18NMessagesDAO.updateNonDefaultI18NMessagesLabel(messageBeforeUpdate, message);
}
I18NMessagesDAO.updateI18NMessage(message);
String encodedI18NMessage = URLEncoder.encode("" + message.getId(), "UTF-8");
return Response.created(new URI("/2.0/i18nMessages/" + encodedI18NMessage)).entity(encodedI18NMessage).build();
} catch (Exception e) {
logger.error("Error while updating I18NMessage", e);
throw new SpagoBIRestServiceException("Error while updating I18NMessage", buildLocaleFromSession(), e);
}
}
@GET
@Path("/{applicationId}/keys")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Retrieve all application keys", notes = "Retrieve keys (Consumer key/secret) of application ", response = ApplicationKeyListDTO.class, authorizations = {
@Authorization(value = "OAuth2Security", scopes = {
@AuthorizationScope(scope = "apim:app_manage", description = "Retrieve, Manage applications"),
@AuthorizationScope(scope = "apim:subscribe", description = "Subscribe API")
})
}, tags={ "Application Keys", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. Keys are returned. ", response = ApplicationKeyListDTO.class),
@ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error ", response = ErrorDTO.class),
@ApiResponse(code = 404, message = "Not Found. The resource does not exist. ", response = ErrorDTO.class),
@ApiResponse(code = 412, message = "Precondition Failed. The request has not been performed because one of the preconditions is not met. ", response = ErrorDTO.class) })
public Response applicationsApplicationIdKeysGet(@ApiParam(value = "Application Identifier consisting of the UUID of the Application. ",required=true) @PathParam("applicationId") String applicationId) throws APIManagementException{
return delegate.applicationsApplicationIdKeysGet(applicationId, securityContext);
}
@GET
@Path("/{type}/{id}/location")
@Override
public Response getDeviceLocation(
@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
DeviceInformationManager informationManager;
DeviceLocation deviceLocation;
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(id);
deviceIdentifier.setType(type);
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
deviceLocation = informationManager.getDeviceLocation(deviceIdentifier);
} catch (DeviceDetailsMgtException e) {
String msg = "Error occurred while getting the device location.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.OK).entity(deviceLocation).build();
}
/**
* ADDDIRECTORY endpoint is an admin-level endpoint meant to add a directory for cached analysis
* by NNA.
*/
@GET
@Path("/addDirectory")
@Produces({MediaType.TEXT_PLAIN})
public Response addDirectory() {
try {
final NameNodeLoader nnLoader = (NameNodeLoader) context.getAttribute(NNA_NN_LOADER);
before();
String directory = request.getParameter("dir");
nnLoader.getSuggestionsEngine().addDirectoryToAnalysis(directory);
return Response.ok(directory + " added for analysis.", MediaType.TEXT_PLAIN).build();
} catch (Exception ex) {
return handleException(ex);
} finally {
after();
}
}
@Test
public void createUser() {
assertNull(adminClient.getService(RealmService.class).
search(new RealmQuery.Builder().keyword("*").build()).getResult().get(0).getPasswordPolicy());
UserCR userCR = new UserCR();
userCR.setRealm(SyncopeConstants.ROOT_REALM);
userCR.setUsername(getUUIDString());
userCR.setPassword("password");
Response response = adminClient.getService(UserService.class).create(userCR);
assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
UserTO user = response.readEntity(new GenericType<ProvisioningResult<UserTO>>() {
}).getEntity();
assertNotNull(user);
}
@Test
public void testToResponse_simpleException() {
Exception e = new Exception();
Response response = rem.toResponse(e);
MultivaluedMap<String,Object> responseMap = response.getHeaders();
Assert.assertEquals(500, response.getStatus());
Assert.assertEquals(6, responseMap.size());
Assert.assertEquals(Lists.newArrayList(true), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
Assert.assertEquals(Lists.newArrayList("*"), responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
Assert.assertEquals(Lists.newArrayList(864000), responseMap.get(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
Assert.assertEquals(Lists.newArrayList("500-1"), responseMap.get(Constants.ERROR_CODE));
Assert.assertEquals(Lists.newArrayList("null/null"), responseMap.get(Constants.RESPONSE_ORIGIN));
Assert.assertEquals(Lists.newArrayList("X-SSL-ClientCert-Subject, X-ProxiedEntitiesChain, X-ProxiedIssuersChain, Accept, Accept-Encoding"),
responseMap.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS));
}
@Test
public void loginCredNoPasswordTest() throws Exception {
Response response = target().path("session").queryParam("username", USERNAME).request().post(Entity.json(""));
assertEquals(response.getStatus(), 401);
verify(tokenManager, never()).generateAuthToken(anyString());
Map<String, NewCookie> cookies = response.getCookies();
assertEquals(0, cookies.size());
}
@Test
public void shouldReturnErrorInJsonFormat() {
String response = given().header("Accept", "application/json")
.contentType(ContentType.JSON)
.port(getHttpPort())
.expect()
.statusCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.body("errorMessage", IsEqual.equalTo("Test exception."))
.when()
.get(BASE_PATH + "/debug/throw")
.asString();
logger.info(response);
}
@Test(description = "Test update device scenario when the device is null.")
public void testUpdateDeviceWithNoDevice() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, null);
Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"The response status should be 400");
}
@Override
public Response toResponse(AccessDeniedException ex) {
return ResultStash.builder()
.setStatus(Response.Status.FORBIDDEN)
.addActionError(ex.getMessage(), "access.denied")
.buildResponse();
}
@DELETE
@Path("/delete/{product}/{version}")
@Produces(MediaType.APPLICATION_JSON)
public Response softDeleteSingleVersion(@PathParam("product") final String product,
@PathParam("version") final String version) {
final DBCollection collection = this.mongoLegacyDb.getCollection("summary");
final DBCollection targetCollection = this.mongoLegacyDb.getCollection("deletedSummary");
final Pattern productReg = java.util.regex.Pattern.compile("^" + product + "/" + version + "$");
final BasicDBObject query = new BasicDBObject("_id", productReg);
final DBCursor cursor = collection.find(query);
DBObject doc;
while (cursor.hasNext()) {
doc = cursor.next();
// kill the old id
doc.removeField("_id");
try {
targetCollection.insert(doc);
} catch (final Throwable e) {
return Response.status(500).build();
}
}
collection.remove(query);
return Response.ok().build();
}
protected boolean isTemporarilyDisabledByBruteForce(AuthenticationFlowContext context, UserModel user) {
if (context.getRealm().isBruteForceProtected()) {
if (context.getProtector().isTemporarilyDisabled(context.getSession(), context.getRealm(), user)) {
context.getEvent().user(user);
context.getEvent().error(Errors.USER_TEMPORARILY_DISABLED);
Response challengeResponse = challenge(context, tempDisabledError());
context.forceChallenge(challengeResponse);
return true;
}
}
return false;
}
@GET
@Produces("application/xml")
public Response getJaxbBook() {
Book b = new Book();
b.setId(System.currentTimeMillis());
b.setName("JCache");
return Response.ok(b).tag("123").cacheControl(CacheControl.valueOf("max-age=50000")).build();
}
public PublicKeyContainer createEnvironmentKeyPair( final RelationLinkDto envLink ) throws PeerException
{
WebClient client = null;
Response response;
try
{
remotePeer.checkRelation();
String path = "/pek";
client = WebClientBuilder.buildPeerWebClient( peerInfo, path, provider );
client.type( MediaType.APPLICATION_JSON );
client.accept( MediaType.APPLICATION_JSON );
response = client.post( envLink );
}
catch ( Exception e )
{
LOG.error( e.getMessage(), e );
throw new PeerException( String.format( "Error creating peer environment key: %s", e.getMessage() ) );
}
finally
{
WebClientBuilder.close( client );
}
return WebClientBuilder.checkResponse( response, PublicKeyContainer.class );
}
@Test
void testMoveError() {
when(mockResourceService.get(root)).thenAnswer(inv -> supplyAsync(() -> {
throw new TrellisRuntimeException("Expected");
}));
final Response res = target(RESOURCE_PATH).request().header("Destination", getBaseUri() + NON_EXISTENT_PATH)
.method("MOVE");
assertEquals(SC_INTERNAL_SERVER_ERROR, res.getStatus(), "Unexpected response code!");
}
@Test
void shouldFailStringQueryNotFound() {
fixture.returns(Response.serverError().type(TEXT_PLAIN_TYPE).entity("failed").build());
StringApi api = fixture.builder().build(StringApi.class);
GraphQlClientException thrown = catchThrowableOfType(api::greeting, GraphQlClientException.class);
then(thrown).hasMessage("expected successful status code but got 500 Internal Server Error:\nfailed");
}
@Test
public void filterServerError() throws Exception {
response.setStatusInfo(Response.Status.INTERNAL_SERVER_ERROR);
EasyMock.expect(method.getMethodAnnotations()).andReturn(new Annotation[] {annotation});
replayAll();
CreateQuerySessionIDFilter.QUERY_ID.set("1234");
filter.filter(request, response);
NewCookie responseCookie = (NewCookie) response.getHeaders().getFirst("Set-Cookie");
assertNull("Cookie present when we shouldn't have one.", responseCookie);
verifyAll();
}