Java Code Examples for javax.ws.rs.core.Response.Status

The following are top voted examples for showing how to use javax.ws.rs.core.Response.Status. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Equella   File: FileResourceImpl.java   View source code 6 votes vote down vote up
/**
 * @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();
}
 
Example 2
Project: oscm   File: VersionFilterTest.java   View source code 6 votes vote down vote up
@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());
    }
}
 
Example 3
Project: incubator-servicecomb-java-chassis   File: TestJaxrsProducerResponseMapper.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 4
Project: dotwebstack-framework   File: LdIntegrationTest.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 5
Project: incubator-servicecomb-java-chassis   File: ServiceRegistryClientImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 6
Project: acmeair   File: LoginREST.java   View source code 6 votes vote down vote up
@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");
    }
}
 
Example 7
Project: incubator-servicecomb-java-chassis   File: OperationLocator.java   View source code 6 votes vote down vote up
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());
}
 
Example 8
Project: scott-eu   File: ServiceProviderService1.java   View source code 6 votes vote down vote up
@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);
}
 
Example 9
Project: acmeair-modular   File: BookingsREST.java   View source code 6 votes vote down vote up
@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();
	}
}
 
Example 10
Project: microprofile-opentracing   File: OpentracingClientTests.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 11
Project: neoscada   File: ItemResourceImpl.java   View source code 6 votes vote down vote up
@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$
}
 
Example 12
Project: cf-mta-deploy-service   File: CFExceptionMapper.java   View source code 6 votes vote down vote up
@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();
}
 
Example 13
Project: oscm   File: DefinitionRepresentationTest.java   View source code 6 votes vote down vote up
@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());
    }
}
 
Example 14
Project: Equella   File: ItemResourceImpl.java   View source code 6 votes vote down vote up
@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();
}
 
Example 15
Project: Pet-Supply-Store   File: NonBalancedCRUDOperations.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 16
Project: scott-eu   File: ResourceShapeService.java   View source code 6 votes vote down vote up
@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);
}
 
Example 17
Project: oscm   File: RestResourceTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 18
Project: echo   File: Search.java   View source code 5 votes vote down vote up
/**
    * 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();
	}
}
 
Example 19
Project: abhot   File: RollUpResource.java   View source code 5 votes vote down vote up
@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();
	}
}
 
Example 20
Project: Equella   File: ScrapbookResource.java   View source code 5 votes vote down vote up
@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();
}
 
Example 21
Project: dotwebstack-framework   File: SwaggerUtilsTest.java   View source code 5 votes vote down vote up
@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())));
}
 
Example 22
Project: scott-eu   File: ServiceProviderCatalogSingleton.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 23
Project: dotwebstack-framework   File: OpenApiIntegrationTest.java   View source code 5 votes vote down vote up
@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()));
}
 
Example 24
Project: Equella   File: FileResourceImpl.java   View source code 5 votes vote down vote up
protected void ensureStaging(String stagingUuid)
{
	if( !stagingService.stagingExists(stagingUuid)
		|| !fileSystemService.fileExists(new StagingFile(stagingUuid), null) )
	{
		throw new WebApplicationException(Status.NOT_FOUND);
	}
}
 
Example 25
Project: incubator-servicecomb-java-chassis   File: TestSwaggerProducerOperation.java   View source code 5 votes vote down vote up
@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());
}
 
Example 26
Project: dotwebstack-framework   File: RedirectionRequestHandlerTest.java   View source code 5 votes vote down vote up
@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)));
}
 
Example 27
Project: incubator-servicecomb-java-chassis   File: TestDefaultProducerResponseMapperFactory.java   View source code 5 votes vote down vote up
@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());
}
 
Example 28
Project: microprofile-opentracing   File: OpentracingClientTests.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 29
Project: incubator-servicecomb-java-chassis   File: TestException.java   View source code 5 votes vote down vote up
@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()));
}
 
Example 30
Project: hadoop   File: RMWebServices.java   View source code 5 votes vote down vote up
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();
}
 
Example 31
Project: acmeair-modular   File: BookingsREST.java   View source code 5 votes vote down vote up
@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();
	}
}
 
Example 32
Project: Equella   File: ScrapbookResource.java   View source code 5 votes vote down vote up
@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();
}
 
Example 33
Project: scott-eu   File: ServiceProviderCatalogSingleton.java   View source code 5 votes vote down vote up
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);
        }
    }
}
 
Example 34
Project: incubator-servicecomb-java-chassis   File: TestJaxrsConsumerResponseMapper.java   View source code 5 votes vote down vote up
@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());
}
 
Example 35
Project: microprofile-opentracing   File: OpentracingClientTests.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 36
Project: dremio-oss   File: SettingsResource.java   View source code 5 votes vote down vote up
@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();
}
 
Example 37
Project: incubator-servicecomb-java-chassis   File: HttpStatusManager.java   View source code 5 votes vote down vote up
public HttpStatusManager() {
  for (Status status : Status.values()) {
    statusMap.put(status.getStatusCode(), status);
  }

  SPIServiceUtils.getAllService(StatusType.class).forEach(this::addStatusType);
}
 
Example 38
Project: acmeair-modular   File: BookingsREST.java   View source code 5 votes vote down vote up
@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();
	}
}
 
Example 39
Project: Pet-Supply-Store   File: AbstractCRUDEndpoint.java   View source code 5 votes vote down vote up
/**
 * 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();
	}
}
 
Example 40
Project: incubator-servicecomb-java-chassis   File: ServiceRegistryClientImpl.java   View source code 5 votes vote down vote up
@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;
}