Java 类javax.ws.rs.core.Response.Status 实例源码

项目:Equella    文件:FileResourceImpl.java   
/**
 * @param stagingUuid
 * @param parentFolder May or may not be present. This folder must already
 *            exist.
 * @param folder Mandatory
 * @return
 */
@Override
public Response createFolderPost(String stagingUuid, String parentFolder, GenericFileBean folder)
{
    final StagingFile stagingFile = getStagingFile(stagingUuid);
    ensureFileExists(stagingFile, parentFolder);

    final String filename = folder.getFilename();
    final String newPath = PathUtils.filePath(parentFolder, filename);

    boolean exists = fileSystemService.fileExists(stagingFile, newPath);
    fileSystemService.mkdir(stagingFile, newPath);

    // was: .entity(convertFile(stagingFile, newPath, false))
    ResponseBuilder resp = Response.status(exists ? Status.OK : Status.CREATED);
    if( !exists )
    {
        resp = resp.location(itemLinkService.getFileDirURI(stagingFile, URLUtils.urlEncode(newPath, false)));
    }
    return resp.build();
}
项目:oscm    文件:VersionFilterTest.java   
@SuppressWarnings("boxing")
@Test
public void testVersionFilterVersionNotExisting() {

    try {
        UriInfo info = mock(UriInfo.class);
        MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
        ContainerRequestContext request = mock(
                ContainerRequestContext.class);
        when(info.getPathParameters()).thenReturn(map);
        when(request.getUriInfo()).thenReturn(info);

        VersionFilter filter = new VersionFilter();
        filter.filter(request);
    } catch (WebApplicationException e) {
        assertEquals(Status.NOT_FOUND.getStatusCode(),
                e.getResponse().getStatus());
    }
}
项目:incubator-servicecomb-java-chassis    文件:TestJaxrsProducerResponseMapper.java   
@Test
public void mapResponse_withHeaders() {
  MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
  headers.add("h", "v");

  new Expectations() {
    {
      jaxrsResponse.getStatusInfo();
      result = Status.OK;
      jaxrsResponse.getEntity();
      result = "result";
      jaxrsResponse.getHeaders();
      result = headers;
    }
  };
  Response response = mapper.mapResponse(null, jaxrsResponse);
  Assert.assertEquals(Status.OK, response.getStatus());
  Assert.assertEquals("result", response.getResult());
  Assert.assertEquals(1, response.getHeaders().getHeaderMap().size());
  Assert.assertThat(response.getHeaders().getHeader("h"), Matchers.contains("v"));
}
项目:dotwebstack-framework    文件:LdIntegrationTest.java   
@Test
public void get_GetBreweryCollection_ThroughLdApi() {
  // Arrange
  Model model = new ModelBuilder().subject(DBEERPEDIA.BREWERIES).add(RDFS.LABEL,
      DBEERPEDIA.BREWERIES_LABEL).build();
  SparqlHttpStub.returnGraph(model);
  MediaType mediaType = MediaType.valueOf("text/turtle");

  // Act
  Response response = target.path("/dbp/ld/v1/graph-breweries").request().accept(mediaType).get();

  // Assert
  assertThat(response.getStatus(), equalTo(Status.OK.getStatusCode()));
  assertThat(response.getMediaType(), equalTo(mediaType));
  assertThat(response.getLength(), greaterThan(0));
  assertThat(response.readEntity(String.class),
      containsString(DBEERPEDIA.BREWERIES_LABEL.stringValue()));
}
项目:incubator-servicecomb-java-chassis    文件:ServiceRegistryClientImpl.java   
@Override
public boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId) {
  Holder<HttpClientResponse> holder = new Holder<>();
  IpPort ipPort = ipPortManager.getAvailableAddress();

  CountDownLatch countDownLatch = new CountDownLatch(1);
  RestUtils.delete(ipPort,
      String.format(Const.REGISTRY_API.MICROSERVICE_INSTANCE_OPERATION_ONE, microserviceId, microserviceInstanceId),
      new RequestParam(),
      syncHandler(countDownLatch, HttpClientResponse.class, holder));
  try {
    countDownLatch.await();
    if (holder.value != null) {
      if (holder.value.statusCode() == Status.OK.getStatusCode()) {
        return true;
      }
      LOGGER.warn(holder.value.statusMessage());
    }
  } catch (Exception e) {
    LOGGER.error("unregister microservice instance {}/{} failed",
        microserviceId,
        microserviceInstanceId,
        e);
  }
  return false;
}
项目:acmeair    文件:LoginREST.java   
@GET
@Path("/logout")
@Produces("text/plain")
@ApiResponses(value = { @ApiResponse(code = 500, message = "CustomerService Internal Server Error") })
public String logout(@QueryParam("login") String login, @CookieParam("sessionid") String sessionid) {
    try {
        customerService.invalidateSession(sessionid);
        // The following call will trigger query against all partitions, disable for now
        //          customerService.invalidateAllUserSessions(login);

        // TODO:  Want to do this with setMaxAge to zero, but to do that I need to have the same path/domain as cookie
        // created in login.  Unfortunately, until we have a elastic ip and domain name its hard to do that for "localhost".
        // doing this will set the cookie to the empty string, but the browser will still send the cookie to future requests
        // and the server will need to detect the value is invalid vs actually forcing the browser to time out the cookie and
        // not send it to begin with
        //                NewCookie sessCookie = new NewCookie(SESSIONID_COOKIE_NAME, "");
        return "logged out";
    }
    catch (Exception e) {
        throw new InvocationException(Status.INTERNAL_SERVER_ERROR, "Internal Server Error");
    }
}
项目:incubator-servicecomb-java-chassis    文件:OperationLocator.java   
public void locate(String microserviceName, String path, String httpMethod, MicroservicePaths microservicePaths) {
  // 在静态路径中查找
  operation = locateStaticPathOperation(path, httpMethod, microservicePaths.getStaticPathOperationMap());
  if (operation != null) {
    // 全部定位完成
    return;
  }

  // 在动态路径中查找
  operation = locateDynamicPathOperation(path, microservicePaths.getDynamicPathOperationList(), httpMethod);
  if (operation != null) {
    return;
  }

  Status status = Status.NOT_FOUND;
  if (resourceFound) {
    status = Status.METHOD_NOT_ALLOWED;
  }
  LOGGER.error("locate path failed, status:{}, http method:{}, path:{}, microserviceName:{}",
      status,
      httpMethod,
      path,
      microserviceName);
  throw new InvocationException(status, status.getReasonPhrase());
}
项目:scott-eu    文件:ServiceProviderService1.java   
@GET
@Path("{robotId}")
@Produces({ MediaType.TEXT_HTML })
public Response getRobotAsHtml(
    @PathParam("serviceProviderId") final String serviceProviderId, @PathParam("robotId") final String robotId
    ) throws ServletException, IOException, URISyntaxException
{
    // Start of user code getRobotAsHtml_init
    // End of user code

    final Robot aRobot = TwinManager.getRobot(httpServletRequest, serviceProviderId, robotId);

    if (aRobot != null) {
        httpServletRequest.setAttribute("aRobot", aRobot);
        // Start of user code getRobotAsHtml_setAttributes
        // End of user code

        RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/se/ericsson/cf/scott/sandbox/robot.jsp");
        rd.forward(httpServletRequest,httpServletResponse);
    }

    throw new WebApplicationException(Status.NOT_FOUND);
}
项目:acmeair-modular    文件:BookingsREST.java   
@POST
@Consumes({"application/x-www-form-urlencoded"})
@Path("/cancelbooking")
@Produces("text/plain")
public Response cancelBookingsByNumber(
        @FormParam("number") String number,
        @FormParam("userid") String userid) {
    try {
        bs.cancelBooking(userid, number);
        return Response.ok("booking " + number + " deleted.").build();

    }
    catch (Exception e) {
        e.printStackTrace();
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
}
项目:microprofile-opentracing    文件:OpentracingClientTests.java   
/**
 * Common code for handling error and exception tests.
 * @param service The REST service path.
 */
private void assertErrorTest(String service) {
    Response response = executeRemoteWebServiceRaw(TestServerWebServices.REST_TEST_SERVICE_PATH,
        service, Status.INTERNAL_SERVER_ERROR);
    response.close();

    TestSpanTree spans = executeRemoteWebServiceTracerTree();

    Map<String, Object> expectedTags = getExpectedSpanTagsForError(service, Tags.SPAN_KIND_SERVER);

    TestSpanTree expectedTree = new TestSpanTree(
        new TreeNode<>(
            new TestSpan(
                getOperationName(
                    Tags.SPAN_KIND_SERVER,
                    HttpMethod.GET,
                    TestServerWebServices.class,
                    service
                ),
                expectedTags,
                Collections.emptyList()
            )
        )
    );
    assertEqualTrees(spans, expectedTree);
}
项目:neoscada    文件:ItemResourceImpl.java   
@Override
public Response readAllCsv ( final String contextId )
{
    final DataContext context = this.provider.getContext ( contextId );

    if ( context == null )
    {
        logger.trace ( "Context '{}' not found", contextId ); //$NON-NLS-1$
        throw new WebApplicationException ( Status.NOT_FOUND );
    }

    final SortedMap<String, DataItemValue> values = context.getAllValues ();

    final StreamingOutput out = new StreamingOutput () {

        @Override
        public void write ( final OutputStream output ) throws IOException, WebApplicationException
        {
            streamAsCSV ( new PrintWriter ( new OutputStreamWriter ( output, StandardCharsets.UTF_8 ) ), values, ",", "\r\n" ); //$NON-NLS-1$  //$NON-NLS-2$
        }
    };
    return Response.ok ( out ).header ( "Content-Disposition", "attachment; filename=\"data.csv\"" ).build (); //$NON-NLS-1$
}
项目:cf-mta-deploy-service    文件:CFExceptionMapper.java   
@Override
public Response toResponse(Throwable t) {
    if (t instanceof WebApplicationException) {
        return ((WebApplicationException) t).getResponse();
    }

    Status status = Status.INTERNAL_SERVER_ERROR;
    String message = Messages.ERROR_EXECUTING_REST_API_CALL;

    if (t instanceof ContentException) {
        status = Status.BAD_REQUEST;
    } else if (t instanceof NotFoundException) {
        status = Status.NOT_FOUND;
    } else if (t instanceof ConflictException) {
        status = Status.CONFLICT;
    }

    if (t instanceof SLException || t instanceof VirusScannerException) {
        message = t.getMessage();
    }

    LOGGER.error(Messages.ERROR_EXECUTING_REST_API_CALL, t);
    return Response.status(status).entity(message).type(MediaType.TEXT_PLAIN_TYPE).build();
}
项目:oscm    文件:DefinitionRepresentationTest.java   
@Test
public void testValidationNegativeSuspend() throws Exception {

    DefinitionRepresentation trigger = new DefinitionRepresentation();
    trigger.setAction("SUBSCRIBE_TO_SERVICE");
    trigger.setTargetURL("<http://");
    trigger.setDescription("abc");
    trigger.setType("REST_SERVICE");
    trigger.setAction("SUBSCRIBE_TO_SERVICE");

    try {
        trigger.validateContent();
        fail();
    } catch (WebApplicationException e) {
        assertEquals(Status.BAD_REQUEST.getStatusCode(), e.getResponse()
                .getStatus());
    }
}
项目:Equella    文件:ItemResourceImpl.java   
@Override
public Response edit(String uuid, int version, String stagingUuid, String lockId, boolean keepLocked,
    String waitForIndex, String taskUuid, ItemBean itemBean)
{
    // TODO: remove this HAX
    final EquellaItemBean equellaItemBean = EquellaItemBean.copyFrom(itemBean);
    replacePlaceholderUuids(equellaItemBean);
    equellaItemBean.setUuid(uuid);
    equellaItemBean.setVersion(version);
    boolean ensureOnIndexList = Boolean.parseBoolean(waitForIndex);

    ItemIdKey itemIdKey = itemDeserializerService.edit(equellaItemBean, stagingUuid, lockId, !keepLocked,
        ensureOnIndexList);
    if( ensureOnIndexList )
    {
        freeTextService.waitUntilIndexed(itemIdKey);
    }
    return Response.status(Status.OK).location(itemLinkService.getItemURI(itemIdKey)).build();
}
项目:Pet-Supply-Store    文件:NonBalancedCRUDOperations.java   
/**
 * Returns the entity with the specified id. Returns null if it does not exist.
 * @param id Id of the entity to find.
 * @param client The REST client to use.
 * @param <T> Type of entity to handle.
 * @throws NotFoundException If 404 was returned.
 * @throws TimeoutException If 408 was returned.
 * @return The entity; null if it does not exist.
 */
public static <T> T getEntity(RESTClient<T> client, long id) throws NotFoundException, TimeoutException {
    Response response = client.getService().path(client.getApplicationURI()).path(client.getEndpointURI()).
            path(String.valueOf(id)).request(MediaType.APPLICATION_JSON).get();
    if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
        throw new NotFoundException();
    } else if (response.getStatus() == Status.REQUEST_TIMEOUT.getStatusCode()) {
        throw new TimeoutException();
    }
    T entity = null;
    try {
        entity = response.readEntity(client.getEntityClass());
    } catch (NullPointerException | ProcessingException e) {
        LOG.warn("Response did not conform to expected entity type.");
    }
    if (response != null) {
        response.close();
    }
    return entity;
}
项目:scott-eu    文件:ResourceShapeService.java   
@GET
@Path("{resourceShapePath}")
@Produces({ MediaType.TEXT_HTML })
public Response getResourceShapeAsHtml(
        @PathParam("resourceShapePath") final String resourceShapePath
    ) throws ServletException, IOException, URISyntaxException, OslcCoreApplicationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException
{
    final Class<?> resourceClass = Application.getResourceShapePathToResourceClassMap().get(resourceShapePath);
    ResourceShape aResourceShape = null;

    if (resourceClass != null)
    {
        aResourceShape = (ResourceShape) resourceClass.getMethod("createResourceShape").invoke(null);
        httpServletRequest.setAttribute("aResourceShape", aResourceShape);

        RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/se/ericsson/cf/scott/sandbox/resourceshape.jsp");
        rd.forward(httpServletRequest,httpServletResponse);
    }
    throw new WebApplicationException(Status.NOT_FOUND);
}
项目:oscm    文件:RestResourceTest.java   
@Test
public void testPutWithETag() throws Exception {

    MockRepresentation content = new MockRepresentation();
    content.setId(1L);
    content.setETag(1L);

    MockRequestParameters params = new MockRequestParameters();
    params.setId(1L);
    params.setMatch("1");

    UriInfo uriinfo = mock(UriInfo.class);
    MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
    map.putSingle(CommonParams.PARAM_VERSION, "v" + Integer.valueOf(CommonParams.VERSION_1).toString());
    Mockito.when(uriinfo.getPathParameters()).thenReturn(map);

    Response response = put(uriinfo, backendPutETag, content, params);

    assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
}
项目:echo    文件:Search.java   
/**
    * Method handling HTTP GET requests. The returned object will be sent
    * to the client as "text/plain" media type.
    *
    * @return String that will be returned as a text/plain response.
    */
@DELETE
public Response deleteHandler(@Context UriInfo uriInfo) {
    String href = uriInfo.getQueryParameters().getFirst("href");
    if(href != null) {
        Catalogue.deleteCatalogueEntry(href);
        return Response.status(Status.OK).build();
    }
    else {
        return Response.status(Status.BAD_REQUEST).build();
    }
}
项目:abhot    文件:RollUpResource.java   
@GET
@Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
public Response list()
{
    try
    {
        List<RollupTask> tasks = store.read();

        StringBuilder json = new StringBuilder();
        json.append('[');
        for (RollupTask task : tasks)
        {
            json.append(task.getJson()).append(",");
        }

        if (json.length() > 1)
            json.deleteCharAt(json.length() - 1);
        json.append(']');

        ResponseBuilder responseBuilder = Response.status(Status.OK).entity(json.toString());
        setHeaders(responseBuilder);
        return responseBuilder.build();
    }
    catch (RollUpException e)
    {
        logger.error("Failed to list roll-ups.", e);
        return setHeaders(Response.status(Status.INTERNAL_SERVER_ERROR).entity(new ErrorResponse(e.getMessage()))).build();
    }
}
项目:Equella    文件:ScrapbookResource.java   
@PUT
@Path("/{uuid}")
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update an scrapbook item")
public Response update(@ApiParam(value = "Scrapbook item uuid") @PathParam("uuid") String uuid,
    @ApiParam(value = "Scrapbook item") ScrapbookItemBean itemBean, @Context UriInfo info)
{
    return Response.status(Status.OK)
        .location(getScrapbookItemURI(createOrUpdateScrapbookItem(uuid, itemBean, info).getItemId())).build();
}
项目:dotwebstack-framework    文件:SwaggerUtilsTest.java   
@Test
public void extractApiOperation_ReturnsValidApiOperation_WithSpecifiedGet() throws IOException {
  path = "/endpoint";

  ApiOperation apiOperation = SwaggerUtils.extractApiOperation(swagger, path, method);

  Operation operation = apiOperation.getOperation();

  assertThat(apiOperation.getMethod(), is(HttpMethod.GET));
  assertThat(apiOperation.getApiPath().normalised(), is(path));
  assertThat(operation.getParameters(), hasSize(2));
  assertThat(operation.getResponses(), hasKey(Integer.toString(Status.OK.getStatusCode())));
}
项目:scott-eu    文件:ServiceProviderCatalogSingleton.java   
/**
 * Retrieve a list of products from Bugzilla and construct a service provider for each.
 *
 * Each product ID is added to the parameter map which will be used during service provider
 * creation to create unique URI paths for each Bugzilla product.  See @Path definition at
 * the top of BugzillaChangeRequestService.
 *
 * @param httpServletRequest
 */
protected static void initServiceProviders (HttpServletRequest httpServletRequest)
{
    try {
        // Start of user code initServiceProviders
        // End of user code

        String basePath = OSLC4JUtils.getServletURI();

        ServiceProviderInfo [] serviceProviderInfos = WarehouseControllerManager.getServiceProviderInfos(httpServletRequest);
        //Register each service provider
        for (ServiceProviderInfo serviceProviderInfo : serviceProviderInfos) {
            String identifier = serviceProviderIdentifier(serviceProviderInfo.serviceProviderId);
            if (!serviceProviders.containsKey(identifier)) {
                String serviceProviderName = serviceProviderInfo.name;
                String title = String.format("Service Provider '%s'", serviceProviderName);
                String description = String.format("%s (id: %s; kind: %s)",
                    "Service Provider",
                    identifier,
                    "Service Provider");
                Publisher publisher = null;
                Map<String, Object> parameterMap = new HashMap<String, Object>();
                parameterMap.put("serviceProviderId", serviceProviderInfo.serviceProviderId);
                final ServiceProvider aServiceProvider = ServiceProvidersFactory.createServiceProvider(basePath, title, description, publisher, parameterMap);
                registerServiceProvider(aServiceProvider, serviceProviderInfo.serviceProviderId);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new WebApplicationException(e,Status.INTERNAL_SERVER_ERROR);
    }
}
项目:dotwebstack-framework    文件:OpenApiIntegrationTest.java   
@Test
public void get_NotAcceptable_WhenRequestingWrongMediaType() {
  // Act
  Response response =
      target.path("/dbp/api/v1/breweries").request(MediaType.APPLICATION_OCTET_STREAM).get();

  // Assert
  assertThat(response.getStatus(), equalTo(Status.NOT_ACCEPTABLE.getStatusCode()));
}
项目:Equella    文件:FileResourceImpl.java   
protected void ensureStaging(String stagingUuid)
{
    if( !stagingService.stagingExists(stagingUuid)
        || !fileSystemService.fileExists(new StagingFile(stagingUuid), null) )
    {
        throw new WebApplicationException(Status.NOT_FOUND);
    }
}
项目:incubator-servicecomb-java-chassis    文件:TestSwaggerProducerOperation.java   
@Test
public void processException_InvocationTargetException(@Mocked SwaggerInvocation invocation) {
  Error error = new Error("abc");
  InvocationTargetException targetException = new InvocationTargetException(error);

  Response response = swaggerProducerOperation.processException(invocation, targetException);
  Assert.assertSame(Status.OK, response.getStatus());
  Assert.assertEquals("response from error: abc", response.getResult());
}
项目:dotwebstack-framework    文件:RedirectionRequestHandlerTest.java   
@Test
public void apply_ReturnValidRedirection() throws URISyntaxException {
  // Arrange
  when(uri.getPath()).thenReturn("/" + DBEERPEDIA.NL_HOST + DBEERPEDIA.BREWERY_ID_PATH);

  // Act
  Response response = redirectionRequestHandler.apply(containerRequestContext);

  // Assert
  assertThat(response.getStatus(), equalTo(Status.SEE_OTHER.getStatusCode()));
  assertThat(response.getLocation(), equalTo(new URI(DBEERPEDIA.BREWERY_DOC_PATH)));
}
项目:incubator-servicecomb-java-chassis    文件:TestDefaultProducerResponseMapperFactory.java   
@Test
public void createResponseMapper() {
  ProducerResponseMapper mapper = factory.createResponseMapper(null, String.class, Integer.class);
  Response result = mapper.mapResponse(Status.OK, 1);

  Assert.assertSame(Status.OK, result.getStatus());
  Assert.assertEquals("1", result.getResult());
}
项目:microprofile-opentracing    文件:OpentracingClientTests.java   
/**
 * Test that async endpoint exposes active span
 */
@Test
@RunAsClient
private void testAsyncLocalSpan() throws InterruptedException {
    Response response = executeRemoteWebServiceRaw(TestServerWebServices.REST_TEST_SERVICE_PATH,
        TestServerWebServices.REST_ASYNC_LOCAL_SPAN, Status.OK);
    response.close();
    TestSpanTree spans = executeRemoteWebServiceTracerTree();
    TestSpanTree expectedTree = new TestSpanTree(
        new TreeNode<>(
            new TestSpan(
                getOperationName(
                    Tags.SPAN_KIND_SERVER,
                    HttpMethod.GET,
                    TestServerWebServices.class,
                    TestServerWebServices.REST_ASYNC_LOCAL_SPAN
                ),
                getExpectedSpanTags(
                    Tags.SPAN_KIND_SERVER,
                    HttpMethod.GET,
                    TestServerWebServices.REST_TEST_SERVICE_PATH,
                    TestServerWebServices.REST_ASYNC_LOCAL_SPAN,
                    null,
                    Status.OK.getStatusCode()
                ),
                Collections.emptyList()
            ),
            new TreeNode<>(
                new TestSpan(
                    TestServerWebServices.REST_LOCAL_SPAN,
                    getExpectedLocalSpanTags(),
                    Collections.emptyList()
                )
            )
        )
    );
    assertEqualTrees(spans, expectedTree);
}
项目:incubator-servicecomb-java-chassis    文件:TestException.java   
@Test
public void testInvocationException() {
  InvocationException oExceptionIn = new InvocationException(Status.OK, "I am gone now");
  oExceptionIn = ExceptionFactory.convertConsumerException(new Throwable());
  Assert.assertEquals(490, oExceptionIn.getStatusCode());

  oExceptionIn = ExceptionFactory.convertConsumerException(new Throwable(), "abc");
  Assert.assertEquals(490, oExceptionIn.getStatusCode());
  Assert.assertEquals("abc", ((CommonExceptionData) oExceptionIn.getErrorData()).getMessage());

  oExceptionIn = ExceptionFactory.convertProducerException(new Throwable());
  Assert.assertEquals(590, oExceptionIn.getStatusCode());

  oExceptionIn = ExceptionFactory.convertProducerException(new Throwable(), "abcd");
  Assert.assertEquals(590, oExceptionIn.getStatusCode());
  Assert.assertEquals("abcd", ((CommonExceptionData) oExceptionIn.getErrorData()).getMessage());

  oExceptionIn =
      ExceptionFactory.convertConsumerException(new InvocationException(Status.OK, new String("fake-object")));
  Assert.assertEquals(200, oExceptionIn.getStatusCode());

  oExceptionIn = ExceptionFactory.convertConsumerException(new InvocationTargetException(new Throwable()));
  Assert.assertNotEquals("java.lang.Throwable", oExceptionIn.getMessage());

  InvocationException oTemp = new InvocationException(Status.OK, new CommonExceptionData("testObject"));
  Assert.assertEquals("OK", oTemp.getReasonPhrase());
  Assert.assertEquals("CommonExceptionData [message=testObject]", (oTemp.getErrorData().toString()));
}
项目:hadoop    文件:RMWebServices.java   
private Response createDelegationToken(DelegationToken tokenData,
    HttpServletRequest hsr, UserGroupInformation callerUGI)
    throws AuthorizationException, IOException, InterruptedException,
    Exception {

  final String renewer = tokenData.getRenewer();
  GetDelegationTokenResponse resp;
  try {
    resp =
        callerUGI
          .doAs(new PrivilegedExceptionAction<GetDelegationTokenResponse>() {
            @Override
            public GetDelegationTokenResponse run() throws IOException,
                YarnException {
              GetDelegationTokenRequest createReq =
                  GetDelegationTokenRequest.newInstance(renewer);
              return rm.getClientRMService().getDelegationToken(createReq);
            }
          });
  } catch (Exception e) {
    LOG.info("Create delegation token request failed", e);
    throw e;
  }

  Token<RMDelegationTokenIdentifier> tk =
      new Token<RMDelegationTokenIdentifier>(resp.getRMDelegationToken()
        .getIdentifier().array(), resp.getRMDelegationToken().getPassword()
        .array(), new Text(resp.getRMDelegationToken().getKind()), new Text(
        resp.getRMDelegationToken().getService()));
  RMDelegationTokenIdentifier identifier = tk.decodeIdentifier();
  long currentExpiration =
      rm.getRMContext().getRMDelegationTokenSecretManager()
        .getRenewDate(identifier);
  DelegationToken respToken =
      new DelegationToken(tk.encodeToUrlString(), renewer, identifier
        .getOwner().toString(), tk.getKind().toString(), currentExpiration,
        identifier.getMaxDate());
  return Response.status(Status.OK).entity(respToken).build();
}
项目:acmeair-modular    文件:BookingsREST.java   
@POST
@Consumes({"application/x-www-form-urlencoded"})
@Path("/cancelbooking")
@Produces("text/plain")
public Response cancelBookingsByNumber(
        @FormParam("number") String number,
        @FormParam("userid") String userid) {
    try {
        bs.cancelBooking(userid, number);
        return Response.ok("booking " + number + " deleted.").build();

    }
    catch (Exception e) {
        e.printStackTrace();
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
}
项目:Equella    文件:ScrapbookResource.java   
@POST
@Path("/")
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create new scrapbook item")
public Response create(@ApiParam(value = "Scrapbook item") ScrapbookItemBean itemBean, @Context UriInfo info)
{
    return Response.status(Status.CREATED)
        .location(getScrapbookItemURI(createOrUpdateScrapbookItem(null, itemBean, info).getItemId())).build();
}
项目:scott-eu    文件:ServiceProviderCatalogSingleton.java   
public static void deregisterServiceProvider(final String serviceProviderId)
{
    synchronized(serviceProviders)
    {
        final ServiceProvider deregisteredServiceProvider =
            serviceProviders.remove(serviceProviderIdentifier(serviceProviderId));

        if (deregisteredServiceProvider != null)
        {
            final SortedSet<URI> remainingDomains = new TreeSet<URI>();

            for (final ServiceProvider remainingServiceProvider : serviceProviders.values())
            {
                remainingDomains.addAll(getServiceProviderDomains(remainingServiceProvider));
            }

            final SortedSet<URI> removedServiceProviderDomains = getServiceProviderDomains(deregisteredServiceProvider);

            removedServiceProviderDomains.removeAll(remainingDomains);
            serviceProviderCatalog.removeDomains(removedServiceProviderDomains);
            serviceProviderCatalog.removeServiceProvider(deregisteredServiceProvider);
        }
        else
        {
            throw new WebApplicationException(Status.NOT_FOUND);
        }
    }
}
项目:incubator-servicecomb-java-chassis    文件:TestJaxrsConsumerResponseMapper.java   
@Test
public void mapResponse_withoutHeaders() {
  Response response = Response.create(Status.OK, "ret");
  mapper.mapResponse(response);

  Assert.assertEquals(Status.OK.getStatusCode(), status);
  Assert.assertEquals("ret", entity);
  Assert.assertEquals(0, headers.size());
}
项目:microprofile-opentracing    文件:OpentracingClientTests.java   
/**
 * Execute the nested web service.
 * @param uniqueId Some unique ID.
 * @param nestDepth How deep to nest the calls.
 * @param nestBreadth Breadth of first level of nested calls.
 * @param failNest Whether to fail the nested call.
 * @param async Whether to execute nested requests asynchronously.
 */
private void executeNested(int uniqueId, int nestDepth, int nestBreadth, boolean failNest, boolean async) {
    Map<String, Object> queryParameters = getNestedQueryParameters(uniqueId,
            nestDepth, nestBreadth, failNest, async);

    Response response = executeRemoteWebServiceRaw(
        TestServerWebServices.REST_TEST_SERVICE_PATH,
        TestServerWebServices.REST_NESTED,
        queryParameters,
        Status.OK
    );
    response.close();
}
项目:dremio-oss    文件:SettingsResource.java   
@GET
@Path("{id}")
public Response getSetting(@PathParam("id") String id) {
  if(!options.isValid(id)){
    return Response.status(Status.NOT_FOUND).build();
  }
  return Response.ok(toSetting(options.getOption(id))).build();
}
项目:incubator-servicecomb-java-chassis    文件:HttpStatusManager.java   
public HttpStatusManager() {
  for (Status status : Status.values()) {
    statusMap.put(status.getStatusCode(), status);
  }

  SPIServiceUtils.getAllService(StatusType.class).forEach(this::addStatusType);
}
项目:acmeair-modular    文件:BookingsREST.java   
@POST
@Consumes({"application/x-www-form-urlencoded"})
@Path("/bookflights")
@Produces("text/plain")
public /*BookingInfo*/ Response bookFlights(
        @FormParam("userid") String userid,
        @FormParam("toFlightId") String toFlightId,
        @FormParam("toFlightSegId") String toFlightSegId,
        @FormParam("retFlightId") String retFlightId,
        @FormParam("retFlightSegId") String retFlightSegId,
        @FormParam("oneWayFlight") boolean oneWay) {
    try {

        String bookingIdTo = bs.bookFlight(userid, toFlightSegId, toFlightId);

        String bookingInfo = "";

        String bookingIdReturn = null;
        if (!oneWay) {
            bookingIdReturn = bs.bookFlight(userid, retFlightSegId, retFlightId);
            bookingInfo = "{\"oneWay\":false,\"returnBookingId\":\"" + bookingIdReturn + "\",\"departBookingId\":\"" + bookingIdTo + "\"}";
        } else {
            bookingInfo = "{\"oneWay\":true,\"departBookingId\":\"" + bookingIdTo + "\"}";
        }
        return Response.ok(bookingInfo).build();
    }
    catch (Exception e) {
        e.printStackTrace();
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
}
项目:Pet-Supply-Store    文件:AbstractCRUDEndpoint.java   
/**
 * Update the entity with ID id with the attributes of the passed entity.
 * You are free to choose for which attributes you allow updates and which attributes to ignore.
 * Will always ignore the ID in the passed entity and use the separate ID instead.
 * @param id The id of the entity to update.
 * @param entity The values of the entity to update.
 * @return Status Code 200 if update succeeded, 404 if it didn't.
 */
@PUT
@Path("/{id:[0-9][0-9]*}")
public Response update(@PathParam("id") Long id, final T entity) {
    boolean updated = false;
    if (id != null && entity != null) {
        updated = updateEntity(id, entity);
    }
    if (updated) {
        return Response.ok().build();
    } else {
        return Response.status(Status.NOT_FOUND).build();
    }
}
项目:incubator-servicecomb-java-chassis    文件:ServiceRegistryClientImpl.java   
@Override
public HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId) {
  Holder<HttpClientResponse> holder = new Holder<>();
  IpPort ipPort = ipPortManager.getAvailableAddress();

  CountDownLatch countDownLatch = new CountDownLatch(1);
  RestUtils.put(ipPort,
      String.format(Const.REGISTRY_API.MICROSERVICE_HEARTBEAT, microserviceId, microserviceInstanceId),
      new RequestParam().setTimeout(ServiceRegistryConfig.INSTANCE.getHeartBeatRequestTimeout()),
      syncHandler(countDownLatch, HttpClientResponse.class, holder));

  try {
    countDownLatch.await();
    if (holder.value != null) {
      HeartbeatResponse response = new HeartbeatResponse();
      response.setMessage(holder.value.statusMessage());
      if (holder.value.statusCode() == Status.OK.getStatusCode()) {
        response.setOk(true);
        return response;
      }
      LOGGER.warn(holder.value.statusMessage());
      return response;
    }
  } catch (Exception e) {
    LOGGER.error("update microservice instance {}/{} heartbeat failed",
        microserviceId,
        microserviceInstanceId,
        e);
  }
  return null;
}