Java Code Examples for java.net.HttpURLConnection#HTTP_BAD_REQUEST

The following examples show how to use java.net.HttpURLConnection#HTTP_BAD_REQUEST . 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
Source Project: grpc-nebula-java   File: GrpcUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static Status.Code httpStatusToGrpcCode(int httpStatusCode) {
  if (httpStatusCode >= 100 && httpStatusCode < 200) {
    // 1xx. These headers should have been ignored.
    return Status.Code.INTERNAL;
  }
  switch (httpStatusCode) {
    case HttpURLConnection.HTTP_BAD_REQUEST:  // 400
    case 431: // Request Header Fields Too Large
      // TODO(carl-mastrangelo): this should be added to the http-grpc-status-mapping.md doc.
      return Status.Code.INTERNAL;
    case HttpURLConnection.HTTP_UNAUTHORIZED:  // 401
      return Status.Code.UNAUTHENTICATED;
    case HttpURLConnection.HTTP_FORBIDDEN:  // 403
      return Status.Code.PERMISSION_DENIED;
    case HttpURLConnection.HTTP_NOT_FOUND:  // 404
      return Status.Code.UNIMPLEMENTED;
    case 429:  // Too Many Requests
    case HttpURLConnection.HTTP_BAD_GATEWAY:  // 502
    case HttpURLConnection.HTTP_UNAVAILABLE:  // 503
    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:  // 504
      return Status.Code.UNAVAILABLE;
    default:
      return Status.Code.UNKNOWN;
  }
}
 
Example 2
Source Project: openlauncher   File: NetworkUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static String performCall(final URL url, final String method, final String data, final HttpURLConnection existingConnection) {
    try {
        final HttpURLConnection connection = existingConnection != null
                ? existingConnection : (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setDoInput(true);

        if (data != null && !data.isEmpty()) {
            connection.setDoOutput(true);
            final OutputStream output = connection.getOutputStream();
            output.write(data.getBytes(Charset.forName(UTF8)));
            output.flush();
            output.close();
        }

        InputStream input = connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST
                ? connection.getInputStream() : connection.getErrorStream();

        return FileUtils.readCloseTextStream(connection.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 3
Source Project: takes   File: RqLive.java    License: MIT License 6 votes vote down vote up
/**
 * Returns a legal character based n the read character.
 * @param data Character read
 * @param baos Byte stream containing read header
 * @param position Header line number
 * @return A legal character
 * @throws IOException if character is illegal
 */
private static Integer legalCharacter(final Opt<Integer> data,
    final ByteArrayOutputStream baos, final Integer position)
    throws IOException {
    // @checkstyle MagicNumber (1 line)
    if ((data.get() > 0x7f || data.get() < 0x20)
        && data.get() != '\t') {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            String.format(
                "illegal character 0x%02X in HTTP header line #%d: \"%s\"",
                data.get(),
                position,
                new TextOf(baos.toByteArray()).asString()
            )
        );
    }
    return data.get();
}
 
Example 4
/**
 * Creates an AMQP error condition for an throwable.
 * <p>
 * Non {@link ServiceInvocationException} instances are mapped to {@link AmqpError#PRECONDITION_FAILED}.
 *
 * @param t The throwable to map to an error condition.
 * @return The error condition.
 */
protected final ErrorCondition getErrorCondition(final Throwable t) {
    if (ServiceInvocationException.class.isInstance(t)) {
        final ServiceInvocationException error = (ServiceInvocationException) t;
        switch (error.getErrorCode()) {
        case HttpURLConnection.HTTP_BAD_REQUEST:
            return ProtonHelper.condition(Constants.AMQP_BAD_REQUEST, error.getMessage());
        case HttpURLConnection.HTTP_FORBIDDEN:
            return ProtonHelper.condition(AmqpError.UNAUTHORIZED_ACCESS, error.getMessage());
        case HttpUtils.HTTP_TOO_MANY_REQUESTS:
            return ProtonHelper.condition(AmqpError.RESOURCE_LIMIT_EXCEEDED, error.getMessage());
        default:
            return ProtonHelper.condition(AmqpError.PRECONDITION_FAILED, error.getMessage());
        }
    } else {
        return ProtonHelper.condition(AmqpError.PRECONDITION_FAILED, t.getMessage());
    }
}
 
Example 5
private SaslOutcome getSaslOutcomeForErrorStatus(final int status) {
    final SaslOutcome saslOutcome;
    switch (status) {
        case HttpURLConnection.HTTP_BAD_REQUEST:
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            // failed due to an authentication error
            saslOutcome = SaslOutcome.PN_SASL_AUTH;
            break;
        case HttpURLConnection.HTTP_INTERNAL_ERROR:
            // failed due to a system error
            saslOutcome = SaslOutcome.PN_SASL_SYS;
            break;
        case HttpURLConnection.HTTP_UNAVAILABLE:
            // failed due to a transient error
            saslOutcome = SaslOutcome.PN_SASL_TEMP;
            break;
        default:
            if (status >= 400 && status < 500) {
                // client error
                saslOutcome = SaslOutcome.PN_SASL_PERM;
            } else {
                saslOutcome = SaslOutcome.PN_SASL_TEMP;
            }
    }
    return saslOutcome;
}
 
Example 6
private static String performCall(final URL url, final String method, final String data, final HttpURLConnection existingConnection) {
    try {
        final HttpURLConnection connection = existingConnection != null
                ? existingConnection : (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setDoInput(true);

        if (data != null && !data.isEmpty()) {
            connection.setDoOutput(true);
            final OutputStream output = connection.getOutputStream();
            output.write(data.getBytes(Charset.forName(UTF8)));
            output.flush();
            output.close();
        }

        InputStream input = connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST
                ? connection.getInputStream() : connection.getErrorStream();

        return FileUtils.readCloseTextStream(connection.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 7
Source Project: takes   File: PsGoogle.java    License: MIT License 6 votes vote down vote up
/**
 * Get user name from Google, with the token provided.
 * @param token Google access token
 * @return The user found in Google
 * @throws IOException If fails
 */
private Identity fetch(final String token) throws IOException {
    // @checkstyle LineLength (1 line)
    final String uri = new Href(this.gapi).path("plus").path("v1")
        .path("people")
        .path("me")
        .with(PsGoogle.ACCESS_TOKEN, token)
        .toString();
    final JsonObject json = new JdkRequest(uri).fetch()
        .as(JsonResponse.class).json()
        .readObject();
    if (json.containsKey(PsGoogle.ERROR)) {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            String.format(
                "could not retrieve id from Google, possible cause: %s.",
                json.getJsonObject(PsGoogle.ERROR).get("message")
            )
        );
    }
    return PsGoogle.parse(json);
}
 
Example 8
Source Project: takes   File: PsGithub.java    License: MIT License 5 votes vote down vote up
@Override
public Opt<Identity> enter(final Request request)
    throws IOException {
    final Href href = new RqHref.Base(request).href();
    final Iterator<String> code = href.param(PsGithub.CODE).iterator();
    if (!code.hasNext()) {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            "code is not provided by Github"
        );
    }
    return new Opt.Single<>(
        this.fetch(this.token(href.toString(), code.next()))
    );
}
 
Example 9
/**
 * Constructs a response object from a servlet response.
 * @param frame the target frame on which the response will be displayed
 * @param url the url from which the response was received
 * @param response the response populated by the servlet
 **/
ServletUnitWebResponse( ServletUnitClient client, FrameSelector frame, URL url, HttpServletResponse response, boolean throwExceptionOnError ) throws IOException {
    super( client, frame, url );
    _response = (ServletUnitHttpResponse) response;
    /** make sure that any IO exception for HTML received page happens here, not later. **/
    if (getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST || !throwExceptionOnError) {
        defineRawInputStream( new ByteArrayInputStream( _response.getContents() ) );
        if (getContentType().startsWith( "text" )) loadResponseText();
    }
}
 
Example 10
Source Project: takes   File: PsLinkedin.java    License: MIT License 5 votes vote down vote up
@Override
public Opt<Identity> enter(final Request request)
    throws IOException {
    final Href href = new RqHref.Base(request).href();
    final Iterator<String> code = href.param(PsLinkedin.CODE).iterator();
    if (!code.hasNext()) {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            "code is not provided by LinkedIn"
        );
    }
    return new Opt.Single<>(
        this.fetch(this.token(href.toString(), code.next()))
    );
}
 
Example 11
/**
 * Constructs a response object from an input stream.
 * @param frame the target window or frame to which the request should be directed
 * @param url the url from which the response was received
 * @param connection the URL connection from which the response can be read
 **/
HttpWebResponse( WebConversation client, FrameSelector frame, URL url, URLConnection connection, boolean throwExceptionOnError ) throws IOException {
    super( client, frame, url );
    if (HttpUnitOptions.isLoggingHttpHeaders()) System.out.println( "\nReceived from " + url );
    readHeaders( connection );

    /** make sure that any IO exception for HTML received page happens here, not later. **/
    if (_responseCode < HttpURLConnection.HTTP_BAD_REQUEST || !throwExceptionOnError) {
        defineRawInputStream( new BufferedInputStream( getInputStream( connection ) ) );
        if (getContentType().startsWith( "text" )) loadResponseText();
    }
}
 
Example 12
Source Project: takes   File: RqFormSmart.java    License: MIT License 5 votes vote down vote up
/**
 * Get single param or throw HTTP exception.
 * @param name Name of query param
 * @return Value of it
 * @throws IOException If fails
 */
public String single(final CharSequence name) throws IOException {
    final Iterator<String> params = this.param(name).iterator();
    if (!params.hasNext()) {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            String.format(
                "form param \"%s\" is mandatory", name
            )
        );
    }
    return params.next();
}
 
Example 13
private void checkStatusCode(HttpURLConnection conn) throws IOException {
    switch (conn.getResponseCode()) {
        case HttpURLConnection.HTTP_BAD_REQUEST:
            throw new TrelloBadRequestException(IOUtils.toString(conn.getErrorStream()));
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            throw new NotAuthorizedException();
        case HttpURLConnection.HTTP_NOT_FOUND:
            throw new NotFoundException("Resource not found: " + conn.getURL());
    }
}
 
Example 14
Source Project: hono   File: HonoConnectionImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void failConnectionAttempt(final Throwable connectionFailureCause, final Handler<AsyncResult<HonoConnection>> connectionHandler) {

        log.info("stopping connection attempt to server [{}:{}, role: {}] due to terminal error",
                connectionFactory.getHost(),
                connectionFactory.getPort(),
                connectionFactory.getServerRole(),
                connectionFailureCause);

        final ServiceInvocationException serviceInvocationException;
        if (connectionFailureCause == null) {
            serviceInvocationException = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE,
                    "failed to connect");
        } else if (connectionFailureCause instanceof AuthenticationException) {
            // wrong credentials?
            serviceInvocationException = new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED,
                    "failed to authenticate with server");
        } else if (connectionFailureCause instanceof MechanismMismatchException) {
            serviceInvocationException = new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED,
                    "no suitable SASL mechanism found for authentication with server");
        } else if (connectionFailureCause instanceof SSLException) {
            serviceInvocationException = new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                    "TLS handshake with server failed: " + connectionFailureCause.getMessage(), connectionFailureCause);
        } else {
            serviceInvocationException = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE,
                    "failed to connect", connectionFailureCause);
        }
        connectionHandler.handle(Future.failedFuture(serviceInvocationException));
    }
 
Example 15
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 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
private static String getUserFriendlyReason(int reason) {
    String failedReason = "";
    switch (reason) {
        case DownloadManager.ERROR_CANNOT_RESUME:
            failedReason = "ERROR_CANNOT_RESUME";
            break;
        case DownloadManager.ERROR_DEVICE_NOT_FOUND:
            failedReason = "ERROR_DEVICE_NOT_FOUND";
            break;
        case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
            failedReason = "ERROR_FILE_ALREADY_EXISTS";
            break;
        case DownloadManager.ERROR_FILE_ERROR:
            failedReason = "ERROR_FILE_ERROR";
            break;
        case DownloadManager.ERROR_HTTP_DATA_ERROR:
            failedReason = "ERROR_HTTP_DATA_ERROR";
            break;
        case DownloadManager.ERROR_INSUFFICIENT_SPACE:
            failedReason = "ERROR_INSUFFICIENT_SPACE";
            break;
        case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
            failedReason = "ERROR_TOO_MANY_REDIRECTS";
            break;
        case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
            failedReason = "ERROR_UNHANDLED_HTTP_CODE";
            break;
        case DownloadManager.ERROR_UNKNOWN:
            failedReason = "ERROR_UNKNOWN";
            break;
        case HttpURLConnection.HTTP_BAD_REQUEST:
            failedReason = "BAD_REQUEST";
            break;
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            failedReason = "UNAUTHORIZED";
            break;
        case HttpURLConnection.HTTP_FORBIDDEN:
            failedReason = "FORBIDDEN";
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            failedReason = "NOT_FOUND";
            break;
        case HttpURLConnection.HTTP_INTERNAL_ERROR:
            failedReason = "INTERNAL_SERVER_ERROR";
            break;
        case ERROR_CANCELED:
            failedReason = "CANCELED";
            break;
    }

    return failedReason;
}
 
Example 18
Source Project: java-binance-api   File: BinanceRequest.java    License: MIT License 4 votes vote down vote up
/**
 * Saving response into local string variable
 * @return this request object
 * @throws BinanceApiException in case of any error
 */
public BinanceRequest read() throws BinanceApiException {
    if (conn == null) {
        connect();
    }
    try {

        // posting payload it we do not have it yet
        if (!Strings.isNullOrEmpty(getRequestBody())) {
            log.debug("Payload: {}", getRequestBody());
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            writer.write(getRequestBody());
            writer.close();
        }

        InputStream is;
        if (conn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
            is = conn.getInputStream();
        } else {
            /* error from server */
            is = conn.getErrorStream();
        }

        BufferedReader br = new BufferedReader( new InputStreamReader(is));
        lastResponse = IOUtils.toString(br);
        log.debug("Response: {}", lastResponse);

        if (conn.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST) {
            // Try to parse JSON
            JsonObject obj = (JsonObject)jsonParser.parse(lastResponse);
            if (obj.has("code") && obj.has("msg")) {
                throw new BinanceApiException("ERROR: " +
                        obj.get("code").getAsString() + ", " + obj.get("msg").getAsString() );
            }
        }
    } catch (IOException e) {
        throw new BinanceApiException("Error in reading response " + e.getMessage());
    }
    return this;
}
 
Example 19
Source Project: metacat   File: PartitionController.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Delete partitions for the given view.
 *
 * @param catalogName  catalog name
 * @param databaseName database name
 * @param tableName    table name
 * @param viewName     metacat view name
 * @param partitionIds list of partition names
 */
@RequestMapping(
    method = RequestMethod.DELETE,
    path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}",
    consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
    value = "Delete partitions for the given view",
    notes = "Delete partitions for the given view"
)
@ApiResponses(
    {
        @ApiResponse(
            code = HttpURLConnection.HTTP_OK,
            message = "The partitions were deleted successfully"
        ),
        @ApiResponse(
            code = HttpURLConnection.HTTP_NOT_FOUND,
            message = "The requested catalog or database or metacat view cannot be located"
        ),
        @ApiResponse(
            code = HttpURLConnection.HTTP_BAD_REQUEST,
            message = "The list of partitionNames is not present"
        )
    }
)
public void deletePartitions(
    @ApiParam(value = "The name of the catalog", required = true)
    @PathVariable("catalog-name") final String catalogName,
    @ApiParam(value = "The name of the database", required = true)
    @PathVariable("database-name") final String databaseName,
    @ApiParam(value = "The name of the table", required = true)
    @PathVariable("table-name") final String tableName,
    @ApiParam(value = "The name of the metacat view", required = true)
    @PathVariable("view-name") final String viewName,
    @ApiParam(value = "partitionId of the partitions to be deleted from this table", required = true)
    @RequestBody final List<String> partitionIds
) {
    final QualifiedName name = this.requestWrapper.qualifyName(
        () -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
    );
    this.requestWrapper.processRequest(
        name,
        "deleteMViewPartition",
        () -> {
            if (partitionIds.isEmpty()) {
                throw new IllegalArgumentException("partitionIds are required");
            }
            this.mViewService.deletePartitions(name, partitionIds);
            return null;
        }
    );
}
 
Example 20
Source Project: genie   File: GenieBadRequestException.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Constructor.
 *
 * @param msg human readable message
 */
public GenieBadRequestException(final String msg) {
    super(HttpURLConnection.HTTP_BAD_REQUEST, msg);
}