@Test
  public void testCantAddDuplicatedResearcherUrl()
      throws InterruptedException, JSONException, URISyntaxException {
    String accessToken =
        getAccessToken(this.client1ClientId, this.client1ClientSecret, this.client1RedirectUri);
    assertNotNull(accessToken);
    Long now = System.currentTimeMillis();
    ResearcherUrl rUrlToCreate = new ResearcherUrl();
    rUrlToCreate.setUrl(new Url("http://newurl.com/" + now));
    rUrlToCreate.setUrlName("url-name-" + System.currentTimeMillis());
    rUrlToCreate.setVisibility(Visibility.PUBLIC);

    // Create it
    ClientResponse postResponse =
        memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus());

    // Add it again
    postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.CONFLICT.getStatusCode(), postResponse.getStatus());

    // Check it can be created by other client
    String otherClientToken =
        getAccessToken(this.client2ClientId, this.client2ClientSecret, this.client2RedirectUri);
    postResponse =
        memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, otherClientToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus());
  }
 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;
 }
  @Test
  public void testGetDownloadsShouldReturnConflictResponse() throws Exception {
    doThrow(new DownloadNotStartedException()).when(mockFacade).getDownloadIdInProgress();

    Response result = service.getDownloads();
    assertEquals(result.getStatus(), Response.Status.CONFLICT.getStatusCode());
  }
  @Test
  public void testStopDownloadShouldReturnConflictWhenDownloadNotStarted() throws Exception {
    doThrow(new DownloadNotStartedException()).when(mockFacade).stopDownload();

    Response result = service.stopDownload("id");
    assertEquals(result.getStatus(), Response.Status.CONFLICT.getStatusCode());
  }
  @Test
  public void testStartDownloadShouldReturnConflictWhenDownloadStarted() throws Exception {
    doThrow(new DownloadAlreadyStartedException())
        .when(mockFacade)
        .startDownload(artifact, version);

    Response result = service.startDownload(ARTIFACT_NAME, VERSION_NUMBER);
    assertEquals(result.getStatus(), Response.Status.CONFLICT.getStatusCode());
    verify(mockFacade).startDownload(artifact, version);
  }
  /** ******************* Create related methods implementation ********************* */
  @Transactional("transactionManager")
  public Long createPodcast(Podcast podcast) throws AppException {

    validateInputForCreation(podcast);

    // verify existence of resource in the db (feed must be unique)
    PodcastEntity podcastByFeed = podcastDao.getPodcastByFeed(podcast.getFeed());
    if (podcastByFeed != null) {
      throw new AppException(
          Response.Status.CONFLICT.getStatusCode(),
          409,
          "Podcast with feed already existing in the database with the id " + podcastByFeed.getId(),
          "Please verify that the feed and title are properly generated",
          AppConstants.BLOG_POST_URL);
    }

    return podcastDao.createPodcast(new PodcastEntity(podcast));
  }
  @Test
  public void testDuplicateSubmit() throws Exception {
    HierarchicalTypeDefinition<ClassType> type =
        TypesUtil.createClassTypeDef(
            randomString(),
            ImmutableSet.<String>of(),
            TypesUtil.createUniqueRequiredAttrDef("name", DataTypes.STRING_TYPE));
    TypesDef typesDef =
        TypesUtil.getTypesDef(
            ImmutableList.<EnumTypeDefinition>of(),
            ImmutableList.<StructTypeDefinition>of(),
            ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(),
            ImmutableList.of(type));
    serviceClient.createType(typesDef);

    try {
      serviceClient.createType(typesDef);
      fail("Expected 409");
    } catch (AtlasServiceException e) {
      assertEquals(e.getStatus().getStatusCode(), Response.Status.CONFLICT.getStatusCode());
    }
  }
示例#8
0
    public String requestString(
        int timeout, String url, String method, Object body, Pair<String, ?>... parameters)
        throws IOException, ServerException, ForbiddenException, NotFoundException,
            UnauthorizedException, ConflictException {
      final String authToken = getAuthenticationToken();
      if ((parameters != null && parameters.length > 0) || authToken != null) {
        final UriBuilder ub = UriBuilder.fromUri(url);
        // remove sensitive information from url.
        ub.replaceQueryParam("token", null);

        if (parameters != null && parameters.length > 0) {
          for (Pair<String, ?> parameter : parameters) {
            String name = URLEncoder.encode(parameter.first, "UTF-8");
            String value =
                parameter.second == null
                    ? null
                    : URLEncoder.encode(String.valueOf(parameter.second), "UTF-8");
            ub.replaceQueryParam(name, value);
          }
        }
        url = ub.build().toString();
      }
      final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
      conn.setConnectTimeout(timeout > 0 ? timeout : 60000);
      conn.setReadTimeout(timeout > 0 ? timeout : 60000);
      try {
        conn.setRequestMethod(method);
        // drop a hint for server side that we want to receive application/json
        conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        if (authToken != null) {
          conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authToken);
        }
        if (body != null) {
          conn.addRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
          conn.setDoOutput(true);

          if (HttpMethod.DELETE.equals(
              method)) { // to avoid jdk bug described here
                         // http://bugs.java.com/view_bug.do?bug_id=7157360
            conn.setRequestMethod(HttpMethod.POST);
            conn.setRequestProperty("X-HTTP-Method-Override", HttpMethod.DELETE);
          }

          try (OutputStream output = conn.getOutputStream()) {
            output.write(DtoFactory.getInstance().toJson(body).getBytes());
          }
        }

        final int responseCode = conn.getResponseCode();
        if ((responseCode / 100) != 2) {
          InputStream in = conn.getErrorStream();
          if (in == null) {
            in = conn.getInputStream();
          }
          final String str;
          try (Reader reader = new InputStreamReader(in)) {
            str = CharStreams.toString(reader);
          }
          final String contentType = conn.getContentType();
          if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON)) {
            final ServiceError serviceError =
                DtoFactory.getInstance().createDtoFromJson(str, ServiceError.class);
            if (serviceError.getMessage() != null) {
              if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
                throw new ForbiddenException(serviceError);
              } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
                throw new NotFoundException(serviceError);
              } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
                throw new UnauthorizedException(serviceError);
              } else if (responseCode == Response.Status.CONFLICT.getStatusCode()) {
                throw new ConflictException(serviceError);
              } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
                throw new ServerException(serviceError);
              }
              throw new ServerException(serviceError);
            }
          }
          // Can't parse content as json or content has format other we expect for error.
          throw new IOException(
              String.format(
                  "Failed access: %s, method: %s, response code: %d, message: %s",
                  UriBuilder.fromUri(url).replaceQuery("token").build(),
                  method,
                  responseCode,
                  str));
        }
        final String contentType = conn.getContentType();
        if (!(contentType == null || contentType.startsWith(MediaType.APPLICATION_JSON))) {
          throw new IOException(conn.getResponseMessage());
        }

        try (Reader reader = new InputStreamReader(conn.getInputStream())) {
          return CharStreams.toString(reader);
        }
      } finally {
        conn.disconnect();
      }
    }