Example usage for java.net HttpURLConnection HTTP_BAD_REQUEST

List of usage examples for java.net HttpURLConnection HTTP_BAD_REQUEST

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_BAD_REQUEST.

Prototype

int HTTP_BAD_REQUEST

To view the source code for java.net HttpURLConnection HTTP_BAD_REQUEST.

Click Source Link

Document

HTTP Status-Code 400: Bad Request.

Usage

From source file:rapture.kernel.ScriptApiImpl.java

@Override
public void removeScriptLink(CallingContext context, String fromScriptURI) {
    RaptureScript script = getScriptNoFollowLink(fromScriptURI);
    if (script.getPurpose() == RaptureScriptPurpose.LINK) {
        deleteScript(context, fromScriptURI);
    } else {//  w w w  .  j  a  v a2  s .c  o  m
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                String.format("Script %s is not a link", fromScriptURI));
    }
}

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Returns a BAD_REQUEST response with the specified message
 * @param message the message format//from  w w w .j av  a 2  s.  c  o  m
 * @param args the message parameters
 */
protected Response badRequest(String message, Object... args) {
    return status(HttpURLConnection.HTTP_BAD_REQUEST, message, args);
}

From source file:org.eclipse.hono.service.credentials.CredentialsHttpEndpoint.java

private void updateCredentials(final RoutingContext ctx) {

    final JsonObject payload = (JsonObject) ctx.get(KEY_REQUEST_BODY);
    final String deviceId = payload.getString(CredentialsConstants.FIELD_PAYLOAD_DEVICE_ID);
    final String authId = payload.getString(CredentialsConstants.FIELD_AUTH_ID);
    final String type = payload.getString(CredentialsConstants.FIELD_TYPE);
    final String tenantId = getTenantParam(ctx);
    final String authIdFromUri = getAuthIdParam(ctx);
    final String typeFromUri = getTypeParam(ctx);

    // auth-id and type from URI must match payload
    if (!authIdFromUri.equals(authId)) {
        ctx.response().setStatusMessage("Non-matching authentication identifier");
        ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
    } else if (!typeFromUri.equals(type)) {
        ctx.response().setStatusMessage("Non-matching credentials type");
        ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
    } else {/*from  w  w  w . j a va 2s  .com*/
        logger.debug("updating credentials [tenant: {}, device-id: {}, auth-id: {}, type: {}]", tenantId,
                deviceId, authId, type);

        final JsonObject requestMsg = EventBusMessage
                .forOperation(CredentialsConstants.CredentialsAction.update.toString()).setTenant(tenantId)
                .setDeviceId(deviceId).setJsonPayload(payload).toJson();

        sendAction(ctx, requestMsg, getDefaultResponseHandler(ctx));
    }
}

From source file:rapture.repo.google.IdGenGoogleDatastore.java

public void setValid(Boolean flag) {
    Key entityKey = datastore.newKeyFactory().setKind(kind).newKey(VALID);
    Entity entity = datastore.get(entityKey);
    try {//ww w . j  a v  a 2s . c o m
        Entity.Builder builder = Entity.newBuilder(entityKey);
        builder.set(kind, new BooleanValue(flag));
        entity = builder.build();
        datastore.put(entity);
    } catch (Exception e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                googleMsgCatalog.getMessage("CannotUpdate" + flag), e);
    }
}

From source file:org.ScripterRon.JavaBitcoin.RpcHandler.java

/**
 * Handle an HTTP request/*from   w ww.j a v a 2s .  c  o  m*/
 *
 * @param       exchange            HTTP exchange
 * @throws      IOException         Error detected while handling the request
 */
@Override
public void handle(HttpExchange exchange) throws IOException {
    try {
        int responseCode;
        String responseBody;
        //
        // Get the HTTP request
        //
        InetSocketAddress requestAddress = exchange.getRemoteAddress();
        String requestMethod = exchange.getRequestMethod();
        Headers requestHeaders = exchange.getRequestHeaders();
        String contentType = requestHeaders.getFirst("Content-Type");
        Headers responseHeaders = exchange.getResponseHeaders();
        log.debug(String.format("%s request received from %s", requestMethod, requestAddress.getAddress()));
        if (!rpcAllowIp.contains(requestAddress.getAddress())) {
            responseCode = HttpURLConnection.HTTP_UNAUTHORIZED;
            responseBody = "Your IP address is not authorized to access this server";
            responseHeaders.set("Content-Type", "text/plain");
        } else if (!exchange.getRequestMethod().equals("POST")) {
            responseCode = HttpURLConnection.HTTP_BAD_METHOD;
            responseBody = String.format("%s requests are not supported", exchange.getRequestMethod());
            responseHeaders.set("Content-Type", "text/plain");
        } else if (contentType == null || !contentType.equals("application/json-rpc")) {
            responseCode = HttpURLConnection.HTTP_BAD_REQUEST;
            responseBody = "Content type must be application/json-rpc";
            responseHeaders.set("Content-Type", "text/plain");
        } else {
            responseBody = processRequest(exchange);
            responseCode = HttpURLConnection.HTTP_OK;
            responseHeaders.set("Content-Type", "application/json-rpc");
        }
        //
        // Return the HTTP response
        //
        responseHeaders.set("Cache-Control", "no-cache, no-store, must-revalidate, private");
        responseHeaders.set("Server", "JavaBitcoin");
        byte[] responseBytes = responseBody.getBytes("UTF-8");
        exchange.sendResponseHeaders(responseCode, responseBytes.length);
        try (OutputStream out = exchange.getResponseBody()) {
            out.write(responseBytes);
        }
        log.debug(String.format("RPC request from %s completed", requestAddress.getAddress()));
    } catch (IOException exc) {
        log.error("Unable to process RPC request", exc);
        throw exc;
    }
}

From source file:org.eclipse.mylyn.internal.bugzilla.rest.core.BugzillaRestPostNewTask.java

@Override
protected void doValidate(CommonHttpResponse response, IOperationMonitor monitor)
        throws IOException, BugzillaRestException {
    int statusCode = response.getStatusCode();
    if (statusCode != HttpURLConnection.HTTP_BAD_REQUEST && statusCode != HttpURLConnection.HTTP_OK) {
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            throw new BugzillaRestResourceNotFoundException(
                    NLS.bind("Requested resource ''{0}'' does not exist", response.getRequestPath()));
        }//from   w ww.  j a  va 2 s  .  c  o  m
        throw new BugzillaRestException(
                NLS.bind("Unexpected response from Bugzilla REST server for ''{0}'': {1}",
                        response.getRequestPath(), HttpUtil.getStatusText(statusCode)));
    }

}

From source file:rapture.common.client.BaseHttpApi.java

protected <T> T doRequest(BasePayload payload, String requestCode, TypeReference<T> reference) {
    int numTries = 0;
    while (numTries < MAX_RETRIES - 1) {
        numTries++;// w ww.jav  a 2s  .c  om
        try {
            return innerDoRequest(payload, requestCode, reference);
        } catch (Exception e) {
            log.error(String.format("%s -- exception during API call, attempt %s/%s. Will retry", e, numTries,
                    MAX_RETRIES));
        }
    }
    // if we got here, it means that we never returned above
    String errorMessage;
    Throwable exception;
    try {
        return innerDoRequest(payload, requestCode, reference);
    } catch (ClientProtocolException e) {
        exception = e;
        errorMessage = "Error connecting to server after 3 retries";
    } catch (IOException e) {
        exception = e;
        errorMessage = "Error connecting to server after 3 retries";
    }

    RaptureException raptException = RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
            errorMessage, exception);
    log.error(String.format("%s -- exception during API call, attempt %s/%s. Stack trace: ", exception,
            MAX_RETRIES, MAX_RETRIES));
    log.error(RaptureExceptionFormatter.getExceptionMessage(raptException, exception));
    throw raptException;
}

From source file:i5.las2peer.services.userManagement.UserManagement.java

/**
 * //ww  w  .j ava  2s.co  m
 * updateUser
 * 
 * 
 * @return HttpResponse
 * 
 */
@PUT
@Path("/update")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "userNotFound"),
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "updated"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "malformedUpdate") })
@ApiOperation(value = "updateUser", notes = "")
public HttpResponse updateUser() {
    // userNotFound
    boolean userNotFound_condition = true;
    if (userNotFound_condition) {
        String error = "Some String";
        HttpResponse userNotFound = new HttpResponse(error, HttpURLConnection.HTTP_NOT_FOUND);
        return userNotFound;
    }
    // updated
    boolean updated_condition = true;
    if (updated_condition) {
        JSONObject updatedUser = new JSONObject();
        HttpResponse updated = new HttpResponse(updatedUser.toJSONString(), HttpURLConnection.HTTP_OK);
        return updated;
    }
    // malformedUpdate
    boolean malformedUpdate_condition = true;
    if (malformedUpdate_condition) {
        String error = "Some String";
        HttpResponse malformedUpdate = new HttpResponse(error, HttpURLConnection.HTTP_BAD_REQUEST);
        return malformedUpdate;
    }
    return null;
}

From source file:rapture.kernel.SeriesApiImpl.java

@Override
public void deleteSeriesRepo(CallingContext context, String seriesURI) {
    // Need to drop the data, then drop the type definition

    RaptureURI internalURI = new RaptureURI(seriesURI, Scheme.SERIES);

    if (internalURI.hasDocPath()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoDocPath", seriesURI)); //$NON-NLS-1$
    }/*www .  j a va  2  s  .  co m*/

    SeriesRepo repo = getRepoFromCache(internalURI.getAuthority());
    if (repo != null) {
        repo.drop();
    }
    SearchPublisher.publishDropMessage(context, internalURI.toString());
    SeriesRepoConfigStorage.deleteByAddress(internalURI, context.getUser(),
            Messages.getString("Admin.RemoveType")); //$NON-NLS-1$ //$NON-NLS-2$
    removeRepoFromCache(internalURI.getAuthority());
}

From source file:org.eclipse.hono.service.registration.BaseRegistrationService.java

private Future<EventBusMessage> processUpdateRequest(final EventBusMessage request) {

    final String tenantId = request.getTenant();
    final String deviceId = request.getDeviceId();
    final JsonObject payload = getRequestPayload(request.getJsonPayload());

    if (tenantId == null || deviceId == null) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    } else {/*from w  w  w . j  av a2 s .c o  m*/
        log.debug("updating registration information for device [{}] of tenant [{}]", deviceId, tenantId);
        final Future<RegistrationResult> result = Future.future();
        updateDevice(tenantId, deviceId, payload, result.completer());
        return result.map(res -> {
            return request.getResponse(res.getStatus()).setDeviceId(deviceId)
                    .setCacheDirective(res.getCacheDirective());
        });
    }
}