Java Code Examples for java.net.HttpURLConnection#HTTP_CONFLICT

The following examples show how to use java.net.HttpURLConnection#HTTP_CONFLICT . These examples are extracted from open source projects. 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
/**
 * Creates the queue if it does not already exist, using the specified request options and operation context.
 * 
 * @param options
 *            A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying
 *            <code>null</code> will use the default request options from the associated service client (
 *            {@link CloudQueueClient}).
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * 
 * @return A value of <code>true</code> if the queue is created in the storage service, otherwise <code>false</code>
 *         .
 * 
 * @throws StorageException
 *             If a storage service error occurred during the operation.
 */
@DoesServiceRequest
public boolean createIfNotExists(QueueRequestOptions options, OperationContext opContext) throws StorageException {
    options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient);

    boolean exists = this.exists(true, options, opContext);
    if (exists) {
        return false;
    }
    else {
        try {
            this.create(options, opContext);
            return true;
        }
        catch (StorageException e) {
            if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT
                    && StorageErrorCodeStrings.QUEUE_ALREADY_EXISTS.equals(e.getErrorCode())) {
                return false;
            }
            else {
                throw e;
            }
        }
    }
}
 
Example 2
protected Attributes writeEndMarkers(HttpURLConnection httpPost, DataOutputStream out)
    throws IOException, ParserConfigurationException, SAXException {
    endMarkers(out);

    int code = httpPost.getResponseCode();
    if (code == HttpURLConnection.HTTP_OK) {
        LOGGER.info("STOWRS server response message: HTTP Status-Code 200: OK for all the image set"); //$NON-NLS-1$
    } else if (code == HttpURLConnection.HTTP_ACCEPTED || code == HttpURLConnection.HTTP_CONFLICT) {
        LOGGER.warn("STOWRS server response message: HTTP Status-Code {}: {}", code, httpPost.getResponseMessage()); //$NON-NLS-1$
        // See http://dicom.nema.org/medical/dicom/current/output/chtml/part18/sect_6.6.html#table_6.6.1-1
        return SAXReader.parse(httpPost.getInputStream());
    } else {
        throw new HttpServerErrorException(String.format("STOWRS server response message: HTTP Status-Code %d: %s",
            code, httpPost.getResponseMessage()));
    }
    return null;
}
 
Example 3
Source Project: hono   File: StatusCodeMapper.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates an exception for a status code and detail message.
 *
 * @param statusCode The status code.
 * @param detailMessage The detail message.
 * @return The exception.
 * @throws IllegalArgumentException if the statusCode does not represent a valid error code (i.e. it is not &ge; 400 and &lt; 600)
 */
public static final ServiceInvocationException from(final int statusCode, final String detailMessage) {

    if (200 <= statusCode && statusCode < 300) {
        throw new IllegalArgumentException("status code " + statusCode + " does not represent an error");
    } else if (400 <= statusCode && statusCode < 500) {
        switch (statusCode) {
        case HttpURLConnection.HTTP_CONFLICT:
            return new ResourceConflictException(detailMessage);
        default:
            return new ClientErrorException(statusCode, detailMessage);
        }
    } else if (500 <= statusCode && statusCode < 600) {
        return new ServerErrorException(statusCode, detailMessage);
    } else {
        throw new IllegalArgumentException(String.format("illegal error code [%d], must be >= 400 and < 600", statusCode));
    }
}
 
Example 4
/**
 * Creates the table in the storage service with the specified request options and operation context, if it does not
 * already exist.
 *
 * @param options
 *            A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying
 *            <code>null</code> will use the default request options from the associated service client (
 *            {@link CloudTableClient}).
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 *
 * @return <code>true</code> if the table did not already exist and was created; otherwise <code>false</code> .
 *
 * @throws StorageException
 *             If a storage service error occurred during the operation.
 */
@DoesServiceRequest
public boolean createIfNotExists(TableRequestOptions options, OperationContext opContext) throws StorageException {
    options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient);

    boolean exists = this.exists(true, options, opContext);
    if (exists) {
        return false;
    }
    else {
        try {
            this.create(options, opContext);
            return true;
        }
        catch (StorageException e) {
            if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT
                    && StorageErrorCodeStrings.TABLE_ALREADY_EXISTS.equals(e.getErrorCode())) {
                return false;
            }
            else {
                throw e;
            }
        }
    }
}
 
Example 5
Source Project: crate   File: AzureStorageService.java    License: Apache License 2.0 6 votes vote down vote up
public void writeBlob(String container, String blobName, InputStream inputStream, long blobSize,
                      boolean failIfAlreadyExists)
    throws URISyntaxException, StorageException, IOException {
    LOGGER.trace(() -> new ParameterizedMessage("writeBlob({}, stream, {})", blobName, blobSize));
    final Tuple<CloudBlobClient, Supplier<OperationContext>> client = client();
    final CloudBlobContainer blobContainer = client.v1().getContainerReference(container);
    final CloudBlockBlob blob = blobContainer.getBlockBlobReference(blobName);
    try {
        final AccessCondition accessCondition =
            failIfAlreadyExists ? AccessCondition.generateIfNotExistsCondition() : AccessCondition.generateEmptyCondition();
        blob.upload(inputStream, blobSize, accessCondition, null, client.v2().get());
    } catch (final StorageException se) {
        if (failIfAlreadyExists && se.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT &&
            StorageErrorCodeStrings.BLOB_ALREADY_EXISTS.equals(se.getErrorCode())) {
            throw new FileAlreadyExistsException(blobName, null, se.getMessage());
        }
        throw se;
    }
    LOGGER.trace(() -> new ParameterizedMessage("writeBlob({}, stream, {}) - done", blobName, blobSize));
}
 
Example 6
@Override
public void handleBoxResponse(BoxResponse response) {
    if (response.isSuccess()) {
        if (response.getRequest() instanceof BoxRequestsFolder.CreateFolder) {
            BoxBrowseFragment browseFrag = getTopBrowseFragment();
            if (browseFrag != null) {
                browseFrag.onRefresh();
            }

        }
    } else {
        int resId = R.string.box_browsesdk_network_error;
        if (response.getException() instanceof BoxException) {
            if (((BoxException) response.getException()).getResponseCode() == HttpURLConnection.HTTP_CONFLICT) {
                resId = R.string.box_browsesdk_create_folder_conflict;
            } else {

            }
        }
        Toast.makeText(this, resId, Toast.LENGTH_LONG).show();
    }
}
 
Example 7
Source Project: actframework   File: EndpointTester.java    License: Apache License 2.0 6 votes vote down vote up
protected final void checkResponseCode(Response resp) {
    if (resp.code() < 300 && resp.code() > 199) {
        return;
    }
    switch (resp.code()) {
        case HttpURLConnection.HTTP_NOT_FOUND:
            throw NotFound.INSTANCE;
        case HttpURLConnection.HTTP_BAD_REQUEST:
            throw BadRequest.INSTANCE;
        case HttpURLConnection.HTTP_FORBIDDEN:
            throw Forbidden.INSTANCE;
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            throw Unauthorized.INSTANCE;
        case HttpURLConnection.HTTP_NOT_MODIFIED:
            throw NotModified.INSTANCE;
        case HttpURLConnection.HTTP_CONFLICT:
            throw Conflict.INSTANCE;
        default:
            H.Status status = H.Status.of(resp.code());
            if (status.isError()) {
                throw new ErrorResult(status);
            }
    }
}
 
Example 8
/**
 * Creates the directory if it does not exist, using the specified request options and operation context.
 * 
 * @param options
 *            A {@link FileRequestOptions} object that specifies any additional options for the request.
 *            Specifying <code>null</code> will use the default request options from the associated service client
 *            ({@link CloudFileClient}).
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * 
 * @return <code>true</code> if the directory did not already exist and was created; otherwise, <code>false</code>.
 * 
 * @throws StorageException
 *             If a storage service error occurred.
 * @throws URISyntaxException 
 */
@DoesServiceRequest
public boolean createIfNotExists(FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException {
    options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient);

    this.getShare().assertNoSnapshot();

    boolean exists = this.exists(true /* primaryOnly */, null /* accessCondition */, options, opContext);
    if (exists) {
        return false;
    }
    else {
        try {
            this.create(options, opContext);
            return true;
        }
        catch (StorageException e) {
            if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT
                    && StorageErrorCodeStrings.RESOURCE_ALREADY_EXISTS.equals(e.getErrorCode())) {
                return false;
            }
            else {
                throw e;
            }
        }
    }
}
 
Example 9
Source Project: java   File: LegacyEventBroadcaster.java    License: Apache License 2.0 5 votes vote down vote up
private boolean recordEvent(V1Event event, V1Patch patch, boolean updateExistingEvent) {
  V1Event newEvent = null;
  try {
    if (updateExistingEvent) {
      try {
        newEvent = this.eventSink.patch(event, patch);
      } catch (ApiException patchException) {
        if (patchException.getCode() == HttpURLConnection.HTTP_NOT_FOUND) { // not found
          event = new V1EventBuilder(event).build();
          event.getMetadata().setResourceVersion("");
          updateExistingEvent = false;
        }
      }
    }
    if (!updateExistingEvent) {
      try {
        newEvent = this.eventSink.create(event);
      } catch (ApiException e) {
        if (e.getCode()
            == HttpURLConnection
                .HTTP_CONFLICT) { // "409 Conflict" suggests the requested resource already exists
          logger.error("event already exists", e);
          return true;
        }
        return false;
      }
    }
  } finally {
    if (newEvent != null) {
      this.eventCorrelator.updateState(newEvent);
    }
  }
  return true;
}
 
Example 10
public static RuntimeException createError(int error, String response, String description)
{
	switch (error)
	{
		// 5xx error codes...
		case HttpURLConnection.HTTP_UNAVAILABLE:
			return new OsmServiceUnavailableException(error, response, description);

		// 4xx error codes...
		case HttpURLConnection.HTTP_NOT_FOUND:
		case HttpURLConnection.HTTP_GONE:
			return new OsmNotFoundException(error, response, description);
		case HttpURLConnection.HTTP_FORBIDDEN:
		case HttpURLConnection.HTTP_UNAUTHORIZED:
		/* 401 unauthorized is returned if the user is not authenticated at all
		 * 403 forbidden is returned if the user is authenticated, but does not have the 
		 *     permission to do the action*/
			return new OsmAuthorizationException(error, response, description);
		case HttpURLConnection.HTTP_CONFLICT:
			return new OsmConflictException(error, response, description);
		case HttpURLConnection.HTTP_BAD_REQUEST:
			return new OsmBadUserInputException(error, response, description);

		default:
			return createGenericError(error, response, description);
	}
}
 
Example 11
public void testError()
{
	for(int i = 0; i < 600; ++i)
	{
		RuntimeException e = OsmApiErrorFactory.createError(i, "test", "description");
		
		if(i >= 400 && i < 500) assertTrue(e instanceof OsmApiException);
		else assertTrue(e instanceof OsmConnectionException);
		
		switch(i)
		{
			case HttpURLConnection.HTTP_UNAVAILABLE:
				assertTrue(e instanceof OsmServiceUnavailableException);
				break;
			case HttpURLConnection.HTTP_NOT_FOUND:
			case HttpURLConnection.HTTP_GONE:
				assertTrue(e instanceof OsmNotFoundException);
				break;
			case HttpURLConnection.HTTP_FORBIDDEN:
				assertTrue(e instanceof OsmAuthorizationException);
				break;
			case HttpURLConnection.HTTP_CONFLICT:
				assertTrue(e instanceof OsmConflictException);
				break;
			case HttpURLConnection.HTTP_BAD_REQUEST:
				assertTrue(e instanceof OsmBadUserInputException);
				break;
		}
	}
}
 
Example 12
/**
 * Creates the container if it does not exist, using the specified request options and operation context.
 * 
 * @param accessType
 *            A {@link BlobContainerPublicAccessType} object that specifies whether data in the container may be
 *            accessed publicly and what level of access is to be allowed.
 * @param options
 *            A {@link BlobRequestOptions} object that specifies any additional options for the request.
 *            Specifying <code>null</code> will use the default request options from the associated service client
 *            ({@link CloudBlobClient}).
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * 
 * @return <code>true</code> if the container did not already exist and was created; otherwise, <code>false</code>.
 * 
 * @throws StorageException
 *             If a storage service error occurred.
 */
@DoesServiceRequest
public boolean createIfNotExists(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext opContext) throws StorageException {
    if (accessType == BlobContainerPublicAccessType.UNKNOWN) {
        throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.ARGUMENT_OUT_OF_RANGE_ERROR, "accessType", accessType));
    }

    options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient);

    boolean exists = this.exists(true /* primaryOnly */, null /* accessCondition */, options, opContext);
    if (exists) {
        return false;
    }
    else {
        try {
            this.create(accessType, options, opContext);
            return true;
        }
        catch (StorageException e) {
            if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT
                    && StorageErrorCodeStrings.CONTAINER_ALREADY_EXISTS.equals(e.getErrorCode())) {
                return false;
            }
            else {
                throw e;
            }
        }
    }
}
 
Example 13
Source Project: Sentry-Android   File: Sentry.java    License: MIT License 4 votes vote down vote up
/**
 * Map from HTTP status code to reason description.
 * Sentry HTTP breadcrumbs expect a text description of the HTTP status-code.
 * This function implements a look-up table with a default value for unknown status-codes.
 * @param statusCode an integer HTTP status code, expected to be in the range [200,505].
 * @return a non-empty string in all cases.
 */
private static String httpReason(int statusCode) {
    switch (statusCode) {
        // 2xx
        case HttpURLConnection.HTTP_OK: return "OK";
        case HttpURLConnection.HTTP_CREATED: return "Created";
        case HttpURLConnection.HTTP_ACCEPTED: return "Accepted";
        case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: return "Non-Authoritative Information";
        case HttpURLConnection.HTTP_NO_CONTENT: return "No Content";
        case HttpURLConnection.HTTP_RESET: return "Reset Content";
        case HttpURLConnection.HTTP_PARTIAL: return "Partial Content";

        // 3xx
        case HttpURLConnection.HTTP_MULT_CHOICE: return "Multiple Choices";
        case HttpURLConnection.HTTP_MOVED_PERM: return "Moved Permanently";
        case HttpURLConnection.HTTP_MOVED_TEMP: return "Temporary Redirect";
        case HttpURLConnection.HTTP_SEE_OTHER: return "See Other";
        case HttpURLConnection.HTTP_NOT_MODIFIED: return "Not Modified";
        case HttpURLConnection.HTTP_USE_PROXY: return "Use Proxy";

        // 4xx
        case HttpURLConnection.HTTP_BAD_REQUEST: return "Bad Request";
        case HttpURLConnection.HTTP_UNAUTHORIZED: return "Unauthorized";
        case HttpURLConnection.HTTP_PAYMENT_REQUIRED: return "Payment Required";
        case HttpURLConnection.HTTP_FORBIDDEN: return "Forbidden";
        case HttpURLConnection.HTTP_NOT_FOUND: return "Not Found";
        case HttpURLConnection.HTTP_BAD_METHOD: return "Method Not Allowed";
        case HttpURLConnection.HTTP_NOT_ACCEPTABLE: return "Not Acceptable";
        case HttpURLConnection.HTTP_PROXY_AUTH: return "Proxy Authentication Required";
        case HttpURLConnection.HTTP_CLIENT_TIMEOUT: return "Request Time-Out";
        case HttpURLConnection.HTTP_CONFLICT: return "Conflict";
        case HttpURLConnection.HTTP_GONE: return "Gone";
        case HttpURLConnection.HTTP_LENGTH_REQUIRED: return "Length Required";
        case HttpURLConnection.HTTP_PRECON_FAILED: return "Precondition Failed";
        case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: return "Request Entity Too Large";
        case HttpURLConnection.HTTP_REQ_TOO_LONG: return "Request-URI Too Large";
        case HttpURLConnection.HTTP_UNSUPPORTED_TYPE: return "Unsupported Media Type";

        // 5xx
        case HttpURLConnection.HTTP_INTERNAL_ERROR: return "Internal Server Error";
        case HttpURLConnection.HTTP_NOT_IMPLEMENTED: return "Not Implemented";
        case HttpURLConnection.HTTP_BAD_GATEWAY: return "Bad Gateway";
        case HttpURLConnection.HTTP_UNAVAILABLE: return "Service Unavailable";
        case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return "Gateway Timeout";
        case HttpURLConnection.HTTP_VERSION: return "Version Not Supported";

        default: return "unknown";
    }
}
 
Example 14
Source Project: sfs   File: Jobs.java    License: Apache License 2.0 4 votes vote down vote up
public JobAlreadyRunning() {
    super(HttpURLConnection.HTTP_CONFLICT);
}
 
Example 15
Source Project: hono   File: HonoConnectionImpl.java    License: Eclipse Public License 2.0 4 votes vote down vote up
private void reconnect(
        final Throwable connectionFailureCause,
        final Handler<AsyncResult<HonoConnection>> connectionHandler,
        final Handler<ProtonConnection> disconnectHandler) {

    if (shuttingDown.get()) {
        // no need to try to re-connect
        log.info("client is shutting down, giving up attempt to connect");
        final ClientErrorException ex = new ClientErrorException(
                HttpURLConnection.HTTP_CONFLICT, "client is already shut down");
        connectionHandler.handle(Future.failedFuture(ex));
        return;
    }
    final int reconnectAttempt = connectAttempts.getAndIncrement();
    if (clientConfigProperties.getReconnectAttempts() - reconnectAttempt == 0) {
        log.info("max number of attempts [{}] to re-connect to server [{}:{}, role: {}] have been made, giving up",
                clientConfigProperties.getReconnectAttempts(),
                connectionFactory.getHost(),
                connectionFactory.getPort(),
                connectionFactory.getServerRole());
        clearState();
        failConnectionAttempt(connectionFailureCause, connectionHandler);

    } else {
        deferredConnectionCheckHandler.setConnectionAttemptInProgress();
        if (connectionFailureCause != null) {
            logConnectionError(connectionFailureCause);
        }
        // apply exponential backoff with jitter
        final long reconnectMaxDelay = getReconnectMaxDelay(reconnectAttempt);
        // let the actual reconnect delay be a random between the minDelay and the current maxDelay
        final long reconnectDelay = reconnectMaxDelay > clientConfigProperties.getReconnectMinDelay()
                ? ThreadLocalRandom.current().nextLong(clientConfigProperties.getReconnectMinDelay(), reconnectMaxDelay)
                : clientConfigProperties.getReconnectMinDelay();
        if (reconnectDelay > 0) {
            log.trace("scheduling new connection attempt in {}ms ...", reconnectDelay);
            vertx.setTimer(reconnectDelay, tid -> {
                connect(clientOptions, connectionHandler, disconnectHandler);
            });
        } else {
            connect(clientOptions, connectionHandler, disconnectHandler);
        }
    }
}
 
Example 16
/**
 * List of errors which this method should handle:
 * <p/>
 * 400 Bad Request
 * 401 Unauthorized (user password has changed)
 * 403 Forbidden (access denied)
 * 404 Not found (object was already removed for example)
 * 405 Method not allowed (wrong HTTP request method)
 * 408 Request Time Out (too slow internet connection, long processing time, etc)
 * 409 Conflict (you are trying to treat some resource as another.
 * For example to create interpretation for map through chart URI)
 * 500 Internal server error (for example NullPointerException)
 * 501 Not implemented (no such method or resource)
 * 502 Bad Gateway (can be retried later)
 * 503 Service unavailable (can be temporary issue)
 * 504 Gateway Timeout (we need to retry request later)
 */
public static void handleApiException(APIException apiException, BaseModel model) throws APIException {
    switch (apiException.getKind()) {
        case HTTP: {
            switch (apiException.getResponse().getStatus()) {
                case HttpURLConnection.HTTP_BAD_REQUEST: {
                    // TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
                    break;
                }
                case HttpURLConnection.HTTP_UNAUTHORIZED: {
                    // if the user password has changed, none of other network
                    // requests won't pass. So we need to stop synchronization.
                    throw apiException;
                }
                case HttpURLConnection.HTTP_FORBIDDEN: {
                    // TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
                    // User does not has access to given resource anymore.
                    // We need to handle this in a special way
                    break;
                }
                case HttpURLConnection.HTTP_NOT_FOUND: {
                    // The given resource does not exist on the server anymore.
                    // Remove it locally.
                    if (model != null) {
                        model.delete();
                    }
                    break;
                }
                case HttpURLConnection.HTTP_CONFLICT: {
                    // TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
                    // Trying to access wrong resource.
                    break;
                }
                case HttpURLConnection.HTTP_INTERNAL_ERROR: {
                    // TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
                    break;
                }
                case HttpURLConnection.HTTP_NOT_IMPLEMENTED: {
                    // TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
                    break;
                }
            }

            break;
        }
        case NETWORK: {
            // Retry later.
            break;
        }
        case CONVERSION:
        case UNEXPECTED: {
            // TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
            // implement possibility to show error status. In most cases, this types of errors
            // won't be resolved automatically.

            // for now, just rethrow exception.
            throw apiException;
        }
    }
}
 
Example 17
Source Project: genie   File: GenieConflictException.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Constructor.
 *
 * @param msg human readable message
 */
public GenieConflictException(final String msg) {
    super(HttpURLConnection.HTTP_CONFLICT, msg);
}
 
Example 18
/**
 * Creates a new exception for a detail message.
 *
 * @param msg The detail message.
 */
public ResourceConflictException(final String msg) {
    super(HttpURLConnection.HTTP_CONFLICT, msg);
}
 
Example 19
/**
 * Creates a new exception for a root cause.
 *
 * @param cause The root cause.
 */
public ResourceConflictException(final Throwable cause) {
    super(HttpURLConnection.HTTP_CONFLICT, cause);
}
 
Example 20
/**
 * Creates a new exception for a detail message and a root cause.
 *
 * @param msg The detail message.
 * @param cause The root cause.
 */
public ResourceConflictException(final String msg, final Throwable cause) {
    super(HttpURLConnection.HTTP_CONFLICT, msg, cause);
}