Java Code Examples for org.apache.http.HttpStatus#SC_CONFLICT

The following examples show how to use org.apache.http.HttpStatus#SC_CONFLICT . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StorageAdapterClient.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
private void CheckStatusCode(IHttpResponse response, IHttpRequest request) throws BaseException {
    if (response.isSuccessStatusCode()) {
        return;
    }
    log.info(String.format("StorageAdapter returns %s for request %s",
            response.getStatusCode(), request.getUri().toString()));
    switch (response.getStatusCode()) {
        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceNotFoundException(
                    response.getContent() + ", request URL = " + request.getUri().toString());

        case HttpStatus.SC_CONFLICT:
            throw new ConflictingResourceException(
                    response.getContent() + ", request URL = " + request.getUri().toString());

        default:
            throw new ExternalDependencyException(
                    String.format("Http request failed, status code = %s, content = %s, request URL = %s", response.getStatusCode(), response.getContent(), request.getUri().toString()));
    }
}
 
Example 2
Source File: HC4DavExchangeSession.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
protected void moveMessage(String sourceUrl, String targetFolder) throws IOException {
    String targetPath = URIUtil.encodePath(getFolderPath(targetFolder)) + '/' + UUID.randomUUID().toString();
    HttpMove method = new HttpMove(URIUtil.encodePath(sourceUrl), targetPath, false);
    // allow rename if a message with the same name exists
    method.setHeader("Allow-Rename", "t");
    try (CloseableHttpResponse response = httpClientAdapter.execute(method)) {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_PRECONDITION_FAILED ||
            statusCode == HttpStatus.SC_CONFLICT) {
            throw new DavMailException("EXCEPTION_UNABLE_TO_MOVE_MESSAGE");
        } else if (statusCode != HttpStatus.SC_CREATED) {
            throw HttpClientAdapter.buildHttpResponseException(method, response);
        }
    } finally {
        method.releaseConnection();
    }
}
 
Example 3
Source File: ElasticSearchTransporterTest.java    From bender with Apache License 2.0 6 votes vote down vote up
private String getResponse() {
  EsResponse resp = new EsResponse();
  resp.errors = true;

  EsResponse.Item item = new EsResponse.Item();
  item.index = new EsResponse.Index();
  item.index.status = HttpStatus.SC_CONFLICT;
  item.index.error = new EsResponse.Error();
  item.index.error.reason = "unit test failure";
  item.index.error.type = "failure";
  item.index.error.caused_by = new EsResponse.Cause();
  item.index.error.caused_by.reason = "failure";
  item.index.error.caused_by.type = "internal";
  resp.items = Arrays.asList(item);

  Gson gson = new Gson();
  return gson.toJson(resp);
}
 
Example 4
Source File: FirewallResourceController.java    From pubsub with Apache License 2.0 6 votes vote down vote up
@Override
protected void startAction() throws Exception {
  log.info("Creating firewall");
  Firewall firewallRule =
      new Firewall()
          .setName(FIREWALL_NAME)
          .setDescription(
              "A firewall rule to allow the driver to coordinate load test instances.")
          .setAllowed(
              ImmutableList.of(
                  new Firewall.Allowed()
                      .setIPProtocol("tcp")
                      .setPorts(Collections.singletonList("5000"))));
  try {
    compute.firewalls().insert(project, firewallRule).execute();
  } catch (GoogleJsonResponseException e) {
    log.info("Firewall error: " + e);
    if (e.getStatusCode() != HttpStatus.SC_CONFLICT) {
      throw e;
    }
  }
}
 
Example 5
Source File: KeywhizClient.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Maps some of the common HTTP errors to the corresponding exceptions.
 */
private void throwOnCommonError(int status) throws IOException {
  switch (status) {
    case HttpStatus.SC_BAD_REQUEST:
      throw new MalformedRequestException();
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
      throw new UnsupportedMediaTypeException();
    case HttpStatus.SC_NOT_FOUND:
      throw new NotFoundException();
    case HttpStatus.SC_UNAUTHORIZED:
      throw new UnauthorizedException();
    case HttpStatus.SC_FORBIDDEN:
      throw new ForbiddenException();
    case HttpStatus.SC_CONFLICT:
      throw new ConflictException();
    case HttpStatus.SC_UNPROCESSABLE_ENTITY:
      throw new ValidationException();
  }
  if (status >= 400) {
    throw new IOException("Unexpected status code on response: " + status);
  }
}
 
Example 6
Source File: AuthServerLogic.java    From divide with Apache License 2.0 6 votes vote down vote up
public Credentials userSignUp(Credentials credentials) throws DAOException{
    if (getUserByEmail(dao,credentials.getEmailAddress())!=null){
        throw new DAOException(HttpStatus.SC_CONFLICT,"User Already Exists");
    }
    ServerCredentials toSave = new ServerCredentials(credentials);

    toSave.decryptPassword(keyManager.getPrivateKey()); //decrypt the password
    String de = toSave.getPassword();
    String ha = BCrypt.hashpw(de, BCrypt.gensalt(10));

    toSave.setOwnerId(dao.count(Credentials.class.getName()) + 1);
    toSave.setPassword(ha); //hash the password for storage
    toSave.setAuthToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), toSave));
    toSave.setRecoveryToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), toSave));

    dao.save(toSave);

    return toSave;
}
 
Example 7
Source File: StorageResourceController.java    From pubsub with Apache License 2.0 5 votes vote down vote up
private void createStorageBucket() throws IOException {
  try {
    storage.buckets().insert(project, new Bucket().setName(bucketName(project))).execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() != HttpStatus.SC_CONFLICT) {
      throw e;
    }
  }
}
 
Example 8
Source File: HttpResponseExceptionMappingService.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
public BackgroundException map(final Throwable failure, final StringBuilder buffer, final int statusCode) {
    switch(statusCode) {
        case HttpStatus.SC_UNAUTHORIZED:
            return new LoginFailureException(buffer.toString(), failure);
        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            return new ProxyLoginFailureException(buffer.toString(), failure);
        case HttpStatus.SC_FORBIDDEN:
        case HttpStatus.SC_NOT_ACCEPTABLE:
            return new AccessDeniedException(buffer.toString(), failure);
        case HttpStatus.SC_CONFLICT:
            return new ConflictException(buffer.toString(), failure);
        case HttpStatus.SC_NOT_FOUND:
        case HttpStatus.SC_GONE:
        case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
            return new NotfoundException(buffer.toString(), failure);
        case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
        case HttpStatus.SC_INSUFFICIENT_STORAGE:
        case HttpStatus.SC_PAYMENT_REQUIRED:
            return new QuotaException(buffer.toString(), failure);
        case HttpStatus.SC_UNPROCESSABLE_ENTITY:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_REQUEST_URI_TOO_LONG:
        case HttpStatus.SC_METHOD_NOT_ALLOWED:
        case HttpStatus.SC_NOT_IMPLEMENTED:
            return new InteroperabilityException(buffer.toString(), failure);
        case HttpStatus.SC_REQUEST_TIMEOUT:
        case HttpStatus.SC_GATEWAY_TIMEOUT:
            return new ConnectionTimeoutException(buffer.toString(), failure);
        case HttpStatus.SC_LOCKED:
            return new LockedException(buffer.toString(), failure);
        case HttpStatus.SC_BAD_GATEWAY:
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
        case 429:
            // Too Many Requests. Rate limiting
        case 509:
            // Bandwidth Limit Exceeded
            return new RetriableAccessDeniedException(buffer.toString(), failure);
        default:
            return new InteroperabilityException(buffer.toString(), failure);
    }
}
 
Example 9
Source File: MCRDNBURNRestClient.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Registers a new URN.
 * <br><br>
 * 201 Created: URN-Record is successfully created.<br>
 * 303 See other: At least one of the given URLs is already registered under another URN,
 * which means you should use this existing URN instead of assigning a new one<br>
 * 409 Conflict: URN-Record already exists and can not be created again.<br>
 *
 * @return the status code of the request
 */
private Optional<Date> registerNew(MCRPIRegistrationInfo urn) {
    MCREpicurLite elp = epicurProvider.apply(urn);
    String elpXML = elp.asXMLString();
    String baseServiceURL = getBaseServiceURL(urn);
    CloseableHttpResponse response = MCRHttpsClient.put(baseServiceURL, APPLICATION_XML.toString(), elpXML);

    StatusLine statusLine = response.getStatusLine();

    if (statusLine == null) {
        LOGGER.warn("PUT request for {} returns no status line.", baseServiceURL);
        return Optional.empty();
    }

    int putStatus = statusLine.getStatusCode();

    String identifier = urn.getIdentifier();
    URL url = elp.getUrl();
    switch (putStatus) {
        case HttpStatus.SC_CREATED:
            LOGGER.info("URN {} registered to {}", identifier, url);
            return Optional.ofNullable(response.getFirstHeader("Last-Modified"))
                .map(Header::getValue)
                .map(DateTimeFormatter.RFC_1123_DATE_TIME::parse)
                .map(Instant::from)
                .map(Date::from);
        case HttpStatus.SC_SEE_OTHER:
            LOGGER.warn("At least one of the given URLs is already registered under another URN, "
                + "which means you should use this existing URN instead of assigning a new one.");
            LOGGER.warn("URN {} could NOT registered to {}.", identifier, url);
            break;
        case HttpStatus.SC_CONFLICT:
            LOGGER.warn("URN-Record already exists and can not be created again.");
            LOGGER.warn("URN {} could NOT registered to {}.", identifier, url);
            break;
        default:
            LOGGER.warn("Could not handle urnInfo request: status={}, urn={}, url={}.", putStatus, identifier, url);
            LOGGER.warn("Epicur Lite:");
            LOGGER.warn(elpXML);
            break;
    }

    return Optional.empty();
}
 
Example 10
Source File: GCEComputeResourceController.java    From pubsub with Apache License 2.0 4 votes vote down vote up
/** Creates the instance template and managed instance group for the given zone and type. */
private void createManagedInstanceGroup() throws Exception {
  // Create the Instance Template
  try {
    compute.instanceTemplates().insert(project, defaultInstanceTemplate()).execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() != HttpStatus.SC_CONFLICT) {
      throw e;
    }
    log.info(
        "Instance Template already exists for "
            + params.getClientType()
            + ", using existing template.");
  }

  // Create the Managed Instance Group
  while (true) {
    try {
      compute
          .instanceGroupManagers()
          .insert(
              project,
              params.getZone(),
              (new InstanceGroupManager())
                  .setName(instanceName())
                  .setInstanceTemplate(
                      "projects/" + project + "/global/instanceTemplates/" + instanceName())
                  .setTargetSize(0))
          .execute();
      return;
    } catch (GoogleJsonResponseException e1) {
      if (e1.getStatusCode() == HttpStatus.SC_CONFLICT) {
        log.info(
            "Instance Group already exists for "
                + params.getClientType()
                + ", using existing template.");
        return;
      }
      if (!e1.getDetails().getErrors().get(0).getReason().equals("resourceNotReady")) {
        throw e1;
      }
      log.debug("Instance template not ready for " + params.getClientType() + " trying again.");
      Thread.sleep(100);
    }
  }
}
 
Example 11
Source File: S3DaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public void restoreObjects(final S3FileTransferRequestParamsDto params, int expirationInDays, String archiveRetrievalOption)
{
    LOGGER.info("Restoring a list of objects in S3... s3KeyPrefix=\"{}\" s3BucketName=\"{}\" s3KeyCount={}", params.getS3KeyPrefix(),
        params.getS3BucketName(), params.getFiles().size());

    if (!CollectionUtils.isEmpty(params.getFiles()))
    {
        // Initialize a key value pair for the error message in the catch block.
        String key = params.getFiles().get(0).getPath().replaceAll("\\\\", "/");

        try
        {
            // Create an S3 client.
            AmazonS3Client s3Client = getAmazonS3(params);

            // Create a restore object request.
            RestoreObjectRequest requestRestore = new RestoreObjectRequest(params.getS3BucketName(), null, expirationInDays);
            // Make Bulk the default archive retrieval option if the option is not provided
            requestRestore.setGlacierJobParameters(new GlacierJobParameters().withTier(
                StringUtils.isNotEmpty(archiveRetrievalOption) ? archiveRetrievalOption : Tier.Bulk.toString()));

            try
            {
                for (File file : params.getFiles())
                {
                    key = file.getPath().replaceAll("\\\\", "/");
                    ObjectMetadata objectMetadata = s3Operations.getObjectMetadata(params.getS3BucketName(), key, s3Client);

                    // Request a restore for objects that are not already being restored.
                    if (BooleanUtils.isNotTrue(objectMetadata.getOngoingRestore()))
                    {
                        requestRestore.setKey(key);

                        try
                        {
                            // Try the S3 restore operation on this file.
                            s3Operations.restoreObject(requestRestore, s3Client);
                        }
                        catch (AmazonS3Exception amazonS3Exception)
                        {
                            // If this exception has a status code of 409, log the information and continue to the next file.
                            if (amazonS3Exception.getStatusCode() == HttpStatus.SC_CONFLICT)
                            {
                                LOGGER.info("Restore already in progress for file with s3Key=\"{}\".", key);
                            }
                            // Else, we need to propagate the exception to the next level of try/catch block.
                            else
                            {
                                throw new Exception(amazonS3Exception);
                            }
                        }
                    }
                }
            }
            finally
            {
                s3Client.shutdown();
            }
        }
        catch (Exception e)
        {
            if (StringUtils.contains(e.getMessage(), "Retrieval option is not supported by this storage class"))
            {
                throw new IllegalArgumentException(String
                    .format("Failed to initiate a restore request for \"%s\" key in \"%s\" bucket. Reason: %s", key, params.getS3BucketName(),
                        e.getMessage()), e);
            }
            else
            {
                throw new IllegalStateException(String
                    .format("Failed to initiate a restore request for \"%s\" key in \"%s\" bucket. Reason: %s", key, params.getS3BucketName(),
                        e.getMessage()), e);
            }
        }
    }
}
 
Example 12
Source File: HttpRequestHandler.java    From Asqatasun with GNU Affero General Public License v3.0 4 votes vote down vote up
private int computeStatus(int status) {
    switch (status) { 
        case HttpStatus.SC_FORBIDDEN:
        case HttpStatus.SC_METHOD_NOT_ALLOWED:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_UNAUTHORIZED:
        case HttpStatus.SC_PAYMENT_REQUIRED:
        case HttpStatus.SC_NOT_FOUND:
        case HttpStatus.SC_NOT_ACCEPTABLE:
        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        case HttpStatus.SC_REQUEST_TIMEOUT:
        case HttpStatus.SC_CONFLICT:
        case HttpStatus.SC_GONE:
        case HttpStatus.SC_LENGTH_REQUIRED:
        case HttpStatus.SC_PRECONDITION_FAILED:
        case HttpStatus.SC_REQUEST_TOO_LONG:
        case HttpStatus.SC_REQUEST_URI_TOO_LONG:
        case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
        case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
        case HttpStatus.SC_EXPECTATION_FAILED:
        case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
        case HttpStatus.SC_METHOD_FAILURE:
        case HttpStatus.SC_UNPROCESSABLE_ENTITY:
        case HttpStatus.SC_LOCKED:
        case HttpStatus.SC_FAILED_DEPENDENCY:
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        case HttpStatus.SC_NOT_IMPLEMENTED:
        case HttpStatus.SC_BAD_GATEWAY:
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
        case HttpStatus.SC_GATEWAY_TIMEOUT:
        case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
        case HttpStatus.SC_INSUFFICIENT_STORAGE:
            return 0;
        case HttpStatus.SC_CONTINUE:
        case HttpStatus.SC_SWITCHING_PROTOCOLS:
        case HttpStatus.SC_PROCESSING:
        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
        case HttpStatus.SC_ACCEPTED:
        case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
        case HttpStatus.SC_NO_CONTENT:
        case HttpStatus.SC_RESET_CONTENT:
        case HttpStatus.SC_PARTIAL_CONTENT:
        case HttpStatus.SC_MULTI_STATUS:
        case HttpStatus.SC_MULTIPLE_CHOICES:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_NOT_MODIFIED:
        case HttpStatus.SC_USE_PROXY:
        case HttpStatus.SC_TEMPORARY_REDIRECT:
            return 1;
        default : 
            return 1;
    }
}
 
Example 13
Source File: HttpLocalizedOperationResult.java    From gocd with Apache License 2.0 4 votes vote down vote up
@Override
public void conflict(String message) {
    this.message = message;
    httpCode = HttpStatus.SC_CONFLICT;
}
 
Example 14
Source File: HttpStatusCodeHelper.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static boolean isConflict(final int statusCode){
    return statusCode == HttpStatus.SC_CONFLICT;
}