public UserNotFoundException() {
   super(
       Response.status(Response.Status.NOT_FOUND)
           .entity(new LibrosError(Response.Status.NOT_FOUND.getStatusCode(), MESSAGE))
           .type(MediaType.LIBROS_API_ERROR)
           .build());
 }
  @Test
  public void testDeleteTraitNonExistent() throws Exception {
    final String traitName = "blah_trait";

    ClientResponse clientResponse =
        service
            .path(ENTITIES)
            .path("random")
            .path(TRAITS)
            .path(traitName)
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(HttpMethod.DELETE, ClientResponse.class);
    Assert.assertEquals(clientResponse.getStatus(), Response.Status.NOT_FOUND.getStatusCode());

    String responseAsString = clientResponse.getEntity(String.class);
    Assert.assertNotNull(responseAsString);

    JSONObject response = new JSONObject(responseAsString);
    Assert.assertNotNull(response.get(AtlasClient.ERROR));
    Assert.assertEquals(
        response.getString(AtlasClient.ERROR),
        "trait=" + traitName + " should be defined in type system before it can be deleted");
    Assert.assertNotNull(response.get(AtlasClient.STACKTRACE));
  }
 public String execute(
     HttpServletRequest request, HttpServletResponse response, WebClient client) {
   log.debug("Update person");
   String result = "/searchPerson.jsp";
   String firstName = (String) request.getParameter("name");
   String lastName = (String) request.getParameter("surname");
   String date = (String) request.getParameter("date");
   String login = (String) request.getParameter("log");
   String email = (String) request.getParameter("mail");
   Person person = new Person(firstName, lastName, date);
   person.setLogin(login);
   person.setEmail(email);
   int i = client.path("/PersonService/updatePerson").put(person).getStatus();
   client.reset();
   if (i == Response.Status.OK.getStatusCode()) {
     request.setAttribute("person", person);
     return result;
   }
   if (i == Response.Status.NOT_FOUND.getStatusCode()) {
     log.debug("Person with login " + person.getLogin() + " not found");
     request.setAttribute("error", "Person with login " + person.getLogin() + " not found");
     result = "/error.jsp";
   }
   if (i == Response.Status.CONFLICT.getStatusCode()) {
     log.debug("Error occured while updating person");
     request.setAttribute("error", "Error occured while updating person");
     result = "/error.jsp";
   }
   return result;
 }
Ejemplo n.º 4
0
 public static Response notFound(final String message) {
   return RuntimeDelegateImpl.getInstance()
       .createResponseBuilder()
       .status(Response.Status.NOT_FOUND.getStatusCode())
       .entity(message)
       .build();
 }
Ejemplo n.º 5
0
  @Test
  public void testGetProductOperationNotFound() throws Exception {

    Response response = restService.getTrackerOperation(SOURCE, OPERATION_ID2.toString());

    assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
  }
  @Test
  public void testException() throws Exception {
    LocalAtlasClient atlasClient = new LocalAtlasClient(serviceState, entityResource);

    Response response = mock(Response.class);
    when(entityResource.submit(any(HttpServletRequest.class)))
        .thenThrow(new WebApplicationException(response));
    when(response.getEntity())
        .thenReturn(
            new JSONObject() {
              {
                put("stackTrace", "stackTrace");
              }
            });
    when(response.getStatus()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode());
    try {
      atlasClient.createEntity(new Referenceable(random()));
      fail("Expected AtlasServiceException");
    } catch (AtlasServiceException e) {
      assertEquals(e.getStatus(), ClientResponse.Status.BAD_REQUEST);
    }

    when(entityResource.updateByUniqueAttribute(
            anyString(), anyString(), anyString(), any(HttpServletRequest.class)))
        .thenThrow(new WebApplicationException(response));
    when(response.getStatus()).thenReturn(Response.Status.NOT_FOUND.getStatusCode());
    try {
      atlasClient.updateEntity(random(), random(), random(), new Referenceable(random()));
      fail("Expected AtlasServiceException");
    } catch (AtlasServiceException e) {
      assertEquals(e.getStatus(), ClientResponse.Status.NOT_FOUND);
    }
  }
  @Test
  public void testDeleteNonExistedStorageProperty() throws Exception {
    String key = "x";
    doThrow(PropertyNotFoundException.from(key)).when(mockFacade).deleteStorageProperty(key);

    Response response = service.deleteStorageProperty(key);
    assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
    assertEquals(response.getEntity().toString(), "{message=Property 'x' not found}");
  }
Ejemplo n.º 8
0
  /** Test task delete. */
  @Test
  public final void testTaskDelete() {
    Response rs;
    rs = target("/v1.0/tasks/" + UUID.randomUUID()).request().delete();
    Assert.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rs.getStatus());

    Task testTask = TestDataIT.createTask();
    testTask.setApplicationId(apps.get((int) (Math.random() * apps.size())));
    rs =
        target("/v1.0/tasks")
            .request(Constants.INDIGOMIMETYPE)
            .post(Entity.entity(testTask, Constants.INDIGOMIMETYPE));
    String id = rs.readEntity(Task.class).getId();
    rs = target("/v1.0/tasks/" + id).request().delete();
    Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), rs.getStatus());
    rs = target("/v1.0/tasks/" + id).request().delete();
    Assert.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rs.getStatus());
  }
  @Test
  public void testDeleteProblemFileFailing() {
    WebResource resource = resource();
    resource.path("testClientId").path("target").path("problem").delete();
    ClientResponse response =
        resource.path("testClientId").path("target").path("problem").delete(ClientResponse.class);

    assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
  }
 public Integer findCode(Exception exception) throws Exception {
   Integer code = null;
   HttpStatus status = AnnotationUtils.findAnnotation(exception.getClass(), HttpStatus.class);
   if (status != null) {
     code = status.value().getStatusCode();
   } else if (exception.getClass().equals(NotFoundException.class)) {
     code = Response.Status.NOT_FOUND.getStatusCode();
   }
   return code;
 }
Ejemplo n.º 11
0
  @Test
  public void deleteProxy_unknown() {
    when(aclServiceDao.getProxy(IpInterval.parse("10.0.0.0/32")))
        .thenThrow(EmptyResultDataAccessException.class);

    final Response response = subject.deleteProxy("10.0.0.0/32");
    assertThat(response.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));

    verify(aclServiceDao, never()).deleteProxy(Matchers.any(IpInterval.class));
  }
  @Test
  public void testGetNonExistedCodenvyProperty() throws Exception {
    String key = "x";
    Config testConfig = new Config(ImmutableMap.of("y", "a"));
    doReturn(testConfig).when(configManager).loadInstalledCodenvyConfig();

    Response response = service.getCodenvyProperty(key);
    assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
    assertEquals(response.getEntity().toString(), "{message=Property 'x' not found}");
  }
  @Path("/Client/{cid}")
  @GET
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Response getAssociatedPersons(
      @HeaderParam("Authorization") String authorization, @PathParam("cid") String cid)
      throws Exception {
    clientService = ClientService.instance();

    Response authorizationResponse = processAuthorization(authorization);
    if (authorizationResponse != null) {
      return authorizationResponse;
    }

    try {

      log.info("getting the client");
      OxAuthClient client = clientService.getClientByInum(cid);

      if (client == null) {
        // sets HTTP status code 404 Not Found
        return getErrorResponse(
            "Resource " + cid + " not found", Response.Status.NOT_FOUND.getStatusCode());
      }

      log.info("mapping client attributes");
      ClientAssociation clientAssociation = MapperUtil.map(client, null);
      log.info("getting URL");
      URI location = new URI("/ClientAssociation/Client/" + cid);
      log.info("returning response");
      return Response.ok(clientAssociation).location(location).build();

    } catch (EntryPersistenceException ex) {
      log.error("Exception: ", ex);
      return getErrorResponse(
          "Resource " + cid + " not found", Response.Status.NOT_FOUND.getStatusCode());
    } catch (Exception ex) {
      log.error("Exception: ", ex);
      return getErrorResponse(
          "Unexpected processing error, please check the input parameters",
          Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }
  }
  @Test
  public void testDeleteNonDownloadedArtifact() throws Exception {
    doReturn(artifact).when(service).createArtifact(artifact.getName());
    doThrow(new ArtifactNotFoundException(artifact, version))
        .when(mockFacade)
        .deleteDownloadedArtifact(artifact, version);

    Response response = service.deleteDownloadedArtifact(artifact.getName(), version.toString());
    assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
    assertEquals(response.getEntity().toString(), "{message=Artifact codenvy:1.0.0 not found}");
  }
  @Test
  public void testGetDefinitionForNonexistentType() throws Exception {
    WebResource resource = service.path("api/atlas/types").path("blah");

    ClientResponse clientResponse =
        resource
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(HttpMethod.GET, ClientResponse.class);
    assertEquals(clientResponse.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
  }
  @Test
  public void testUpdateNonexistentCodenvyProperty() throws Exception {
    List<String> nonexistentProperties = Arrays.asList("x1", "x2");
    doThrow(new PropertiesNotFoundException(nonexistentProperties))
        .when(mockFacade)
        .updateArtifactConfig(any(Artifact.class), anyMap());

    Response response = service.updateCodenvyProperties(null);
    assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
    assertEquals(
        response.getEntity().toString(), "{message=Properties not found, properties=[x1, x2]}");
  }
  public Podcast getPodcastById(Long id) throws AppException {
    PodcastEntity podcastById = podcastDao.getPodcastById(id);
    if (podcastById == null) {
      throw new AppException(
          Response.Status.NOT_FOUND.getStatusCode(),
          404,
          "The podcast you requested with id " + id + " was not found in the database",
          "Verify the existence of the podcast with the id " + id + " in the database",
          AppConstants.BLOG_POST_URL);
    }

    return new Podcast(podcastDao.getPodcastById(id));
  }
  @Path("/User/{uid}")
  @GET
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Response getAssociatedClients(
      @HeaderParam("Authorization") String authorization, @PathParam("uid") String uid)
      throws Exception {

    personService = PersonService.instance();

    Response authorizationResponse = processAuthorization(authorization);
    if (authorizationResponse != null) {
      return authorizationResponse;
    }

    try {

      GluuCustomPerson gluuPerson = personService.getPersonByInum(uid);
      if (gluuPerson == null) {
        // sets HTTP status code 404 Not Found
        return getErrorResponse(
            "Resource " + uid + " not found", Response.Status.NOT_FOUND.getStatusCode());
      }

      PersonAssociation personAssociation = MapperUtil.map(gluuPerson, null);

      URI location = new URI("/ClientAssociation/User/" + uid);

      return Response.ok(personAssociation).location(location).build();
    } catch (EntryPersistenceException ex) {
      log.error("Exception: ", ex);
      return getErrorResponse(
          "Resource " + uid + " not found", Response.Status.NOT_FOUND.getStatusCode());
    } catch (Exception ex) {
      log.error("Exception: ", ex);
      return getErrorResponse(
          "Unexpected processing error, please check the input parameters",
          Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }
  }
  @Test
  public void failsToListAllWithInvalidPageLink() throws Throwable {
    String pageLink = "randomPageLink";
    doThrow(new PageExpiredException(pageLink)).when(frontendClient).nextList(pageLink);

    Response response = listNetworks(Optional.absent(), Optional.absent(), Optional.of(pageLink));
    assertThat(response.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));

    String expectedErrorMessage = "Page " + pageLink + " has expired";

    ApiError errors = response.readEntity(ApiError.class);
    assertThat(errors.getCode(), is(ErrorCode.PAGE_EXPIRED.getCode()));
    assertThat(errors.getMessage(), is(expectedErrorMessage));
  }
Ejemplo n.º 20
0
  @Test
  public void testGet() {
    // invalid request
    Response response = service.get(null);
    assertNotNull(response);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    // invalid request
    response = service.get(new RequestBean<Long>(null, null));
    assertNotNull(response);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    // invalid request
    response = service.get(new RequestBean<Long>(null, new Long(1)));
    assertNotNull(response);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    // invalid request
    response = service.get(new RequestBean<Long>(new CredentialsBean(), new Long(1)));
    assertNotNull(response);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    // invalid request
    response = service.get(new RequestBean<Long>(new CredentialsBean("manager", "password"), null));
    assertNotNull(response);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    // valid request, not found
    response =
        service.get(
            new RequestBean<Long>(new CredentialsBean("manager", "password"), new Long(100)));
    assertNotNull(response);
    assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());

    // valid request, invalid id
    response =
        service.get(new RequestBean<Long>(new CredentialsBean("manager", "password"), new Long(0)));
    assertNotNull(response);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());

    // valid request
    response =
        service.get(new RequestBean<Long>(new CredentialsBean("manager", "password"), new Long(1)));
    assertNotNull(response);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

    MenuItemBean menuItem = (MenuItemBean) response.getEntity();
    assertNotNull(menuItem);
  }
 @Transactional("transactionManager")
 public void updatePartiallyPodcast(Podcast podcast) throws AppException {
   // do a validation to verify existence of the resource
   Podcast verifyPodcastExistenceById = verifyPodcastExistenceById(podcast.getId());
   if (verifyPodcastExistenceById == null) {
     throw new AppException(
         Response.Status.NOT_FOUND.getStatusCode(),
         404,
         "The resource you are trying to update does not exist in the database",
         "Please verify existence of data in the database for the id - " + podcast.getId(),
         AppConstants.BLOG_POST_URL);
   }
   copyPartialProperties(verifyPodcastExistenceById, podcast);
   podcastDao.updatePodcast(new PodcastEntity(verifyPodcastExistenceById));
 }
Ejemplo n.º 22
0
  public KeystoneAccess getToken(String token)
      throws KeystoneServerException, KeystoneConnectionException {

    Client client = Client.create(clientConfig);
    WebResource resource = client.resource(getTokensUrl(token));

    try {
      return sendGetRequest(resource, KeystoneAccess.class);
    } catch (KeystoneServerException ex) {
      if (ex.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
        // This indicates that the token was not found
        log.warn("Keystone v2 token not found {}", token);
        return null;
      }

      throw ex;
    }
  }
  @Test
  public void testGetInvalidEntityDefinition() throws Exception {
    WebResource resource = service.path(ENTITIES).path("blah");

    ClientResponse clientResponse =
        resource
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(HttpMethod.GET, ClientResponse.class);
    Assert.assertEquals(clientResponse.getStatus(), Response.Status.NOT_FOUND.getStatusCode());

    String responseAsString = clientResponse.getEntity(String.class);
    Assert.assertNotNull(responseAsString);

    JSONObject response = new JSONObject(responseAsString);
    Assert.assertNotNull(response.get(AtlasClient.ERROR));
    Assert.assertNotNull(response.get(AtlasClient.STACKTRACE));
  }
  @Test(dependsOnMethods = "testAddTrait")
  public void testAddExistingTrait() throws Exception {
    final String traitName = "PII_Trait" + randomString();

    Struct traitInstance = new Struct(traitName);
    String traitInstanceAsJSON = InstanceSerialization.toJson(traitInstance, true);
    LOG.debug("traitInstanceAsJSON = " + traitInstanceAsJSON);

    final String guid = tableId._getId();
    ClientResponse clientResponse =
        service
            .path(ENTITIES)
            .path(guid)
            .path(TRAITS)
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(HttpMethod.POST, ClientResponse.class, traitInstanceAsJSON);
    Assert.assertEquals(clientResponse.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
  }
  @Test
  public void testPutProblemFileFailing() throws URISyntaxException {
    WebResource resource = resource();
    resource.path("testClientId").path("target").path("problem").delete();

    File targetProblemFile = new File(ClassLoader.getSystemResource("pa_target_prob.txt").toURI());
    FormDataMultiPart targetProblemForm = new FormDataMultiPart();
    targetProblemForm.bodyPart(
        new FileDataBodyPart("file", targetProblemFile, MediaType.valueOf(MediaType.TEXT_PLAIN)));
    ClientResponse response =
        resource
            .path("testClientId")
            .path("target")
            .path("problem")
            .type(MediaType.MULTIPART_FORM_DATA_TYPE)
            .put(ClientResponse.class, targetProblemForm);

    assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
  }
Ejemplo n.º 26
0
  /**
   * Retrieves from Keystone server a tenant given its ID.
   *
   * @param id ID of the tenant
   * @return {@link KeystoneTenant} object
   * @throws KeystoneServerException
   * @throws KeystoneConnectionException
   */
  public KeystoneTenant getTenant(String id)
      throws KeystoneServerException, KeystoneConnectionException {
    log.debug("Keystone v2 get tenant {}", id);

    Client client = Client.create(clientConfig);
    WebResource resource = client.resource(getTenantUrl(id));

    try {
      return sendGetRequest(resource, KeystoneTenant.class);
    } catch (KeystoneServerException ex) {
      if (ex.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
        // This indicates that the tenant was not found.  Not an error
        // from MidoNet.
        log.info("Keystone v2 tenant not found {}", id);
        return null;
      }

      throw ex;
    }
  }
Ejemplo n.º 27
0
  @Test
  public void testGetCommand_ReturnsNotFoundResponseIfJobDoesNotExist() {
    // Setup
    Integer bogusJobId = 1;
    CommandJobService mockCommandJobService = createMockCommandJobService();
    expect(mockCommandJobService.getCommand(bogusJobId)).andReturn(null).atLeastOnce();

    WebShellResource sut = new WebShellResource();
    sut.setCommandJobService(mockCommandJobService);

    replay(mockCommandJobService);

    // Exercise
    Response response = sut.getCommand(bogusJobId);

    // Verify mocks
    verify(mockCommandJobService);

    // Verify that the HTTP response code was NOT FOUND (404).
    assertThat(response.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode());
  }
Ejemplo n.º 28
0
  @Test
  public void testSetCommandStatus_ReturnsNotFoundResponseIfJobDoesNotExist() {
    // Setup
    Integer bogusJobId = 1;
    CommandJobService mockCommandJobService = createMockCommandJobService();
    mockCommandJobService.cancelCommand(bogusJobId);
    expectLastCall().andThrow(new NoSuchCommandJobException(bogusJobId));

    WebShellResource sut = new WebShellResource();
    sut.setCommandJobService(mockCommandJobService);

    replay(mockCommandJobService);

    // Exercise
    Response response = sut.setCommandStatus(bogusJobId, Status.CANCELED.toString());

    // Verify mocks
    verify(mockCommandJobService);

    // Verify that the HTTP response code was NOT FOUND (404).
    assertThat(response.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode());
  }
  @Test
  public void testAddTraitWithNoRegistration() throws Exception {
    final String traitName = "PII_Trait" + randomString();
    HierarchicalTypeDefinition<TraitType> piiTrait =
        TypesUtil.createTraitTypeDef(traitName, ImmutableList.<String>of());
    String traitDefinitionAsJSON = TypesSerialization$.MODULE$.toJson(piiTrait, true);
    LOG.debug("traitDefinitionAsJSON = " + traitDefinitionAsJSON);

    Struct traitInstance = new Struct(traitName);
    String traitInstanceAsJSON = InstanceSerialization$.MODULE$.toJson(traitInstance, true);
    LOG.debug("traitInstanceAsJSON = " + traitInstanceAsJSON);

    ClientResponse clientResponse =
        service
            .path(ENTITIES)
            .path("random")
            .path(TRAITS)
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(HttpMethod.POST, ClientResponse.class, traitInstanceAsJSON);
    Assert.assertEquals(clientResponse.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
  }
  /** ******************* UPDATE-related methods implementation ********************* */
  @Transactional("transactionManager")
  public void updateFullyPodcast(Podcast podcast) throws AppException {
    // do a validation to verify FULL update with PUT
    if (isFullUpdate(podcast)) {
      throw new AppException(
          Response.Status.BAD_REQUEST.getStatusCode(),
          400,
          "Please specify all properties for Full UPDATE",
          "required properties - id, title, feed, lnkOnPodcastpedia, description",
          AppConstants.BLOG_POST_URL);
    }

    Podcast verifyPodcastExistenceById = verifyPodcastExistenceById(podcast.getId());
    if (verifyPodcastExistenceById == null) {
      throw new AppException(
          Response.Status.NOT_FOUND.getStatusCode(),
          404,
          "The resource you are trying to update does not exist in the database",
          "Please verify existence of data in the database for the id - " + podcast.getId(),
          AppConstants.BLOG_POST_URL);
    }

    podcastDao.updatePodcast(new PodcastEntity(podcast));
  }