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:io.joynr.messaging.http.HttpMessageSender.java

public void sendMessage(final MessageContainer messageContainer, final FailureAction failureAction) {
    logger.trace("SEND messageId: {} channelId: {}", messageContainer.getMessageId(),
            messageContainer.getChannelId());

    HttpContext context = new BasicHttpContext();

    String channelId = messageContainer.getChannelId();
    String messageId = messageContainer.getMessageId();

    if (messageContainer.isExpired()) {
        logger.error("SEND executionQueue.run channelId: {}, messageId: {} TTL expired: ", messageId,
                messageContainer.getExpiryDate());
        failureAction.execute(new JoynrTimeoutException(messageContainer.getExpiryDate()));
        return;/*from  w w w  .  java 2  s.com*/
    }

    // execute http command to send
    CloseableHttpResponse response = null;
    String sendUrl = null;
    try {

        String serializedMessage = messageContainer.getSerializedMessage();
        sendUrl = urlResolver.getSendUrl(messageContainer.getChannelId());
        logger.debug("SENDING message channelId: {}, messageId: {} toUrl: {}",
                new String[] { channelId, messageId, sendUrl });
        if (sendUrl == null) {
            logger.error("SEND executionQueue.run channelId: {}, messageId: {} No channelId found", messageId,
                    messageContainer.getExpiryDate());
            failureAction.execute(new JoynrMessageNotSentException("no channelId found"));
            return;
        }

        HttpPost httpPost = httpRequestFactory.createHttpPost(URI.create(sendUrl));
        httpPost.addHeader(new BasicHeader(httpConstants.getHEADER_CONTENT_TYPE(),
                httpConstants.getAPPLICATION_JSON() + ";charset=UTF-8"));
        httpPost.setEntity(new StringEntity(serializedMessage, "UTF-8"));

        // Clone the default config
        Builder requestConfigBuilder = RequestConfig.copy(defaultRequestConfig);
        requestConfigBuilder.setConnectionRequestTimeout(httpConstants.getSEND_MESSAGE_REQUEST_TIMEOUT());
        httpPost.setConfig(requestConfigBuilder.build());

        response = httpclient.execute(httpPost, context);

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        String statusText = statusLine.getReasonPhrase();

        switch (statusCode) {
        case HttpURLConnection.HTTP_OK:
        case HttpURLConnection.HTTP_CREATED:
            logger.debug("SEND to ChannelId: {} messageId: {} completed successfully", channelId, messageId);
            break;
        case HttpURLConnection.HTTP_BAD_REQUEST:
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                logger.error(
                        "SEND to ChannelId: {} messageId: {} completed in error. No further reason found in message body",
                        channelId, messageId);
                return;
            }
            String body = EntityUtils.toString(entity, "UTF-8");

            JoynrMessagingError error = objectMapper.readValue(body, JoynrMessagingError.class);
            JoynrMessagingErrorCode joynrMessagingErrorCode = JoynrMessagingErrorCode
                    .getJoynrMessagingErrorCode(error.getCode());
            logger.error(error.toString());
            switch (joynrMessagingErrorCode) {
            case JOYNRMESSAGINGERROR_CHANNELNOTFOUND:
                failureAction.execute(new JoynrChannelMissingException("Channel does not exist. Status: "
                        + statusCode + " error: " + error.getCode() + "reason:" + error.getReason()));
                break;
            default:
                logger.error("SEND error channelId: {}, messageId: {} url: {} error: {} code: {} reason: {} ",
                        new Object[] { channelId, messageId, sendUrl, statusText, error.getCode(),
                                error.getReason() });
                failureAction.execute(new JoynrCommunicationException("Http Error while communicating: "
                        + statusText + body + " error: " + error.getCode() + "reason:" + error.getReason()));
                break;
            }
            break;
        default:
            logger.error("SEND to ChannelId: {} messageId: {} - unexpected response code: {} reason: {}",
                    new Object[] { channelId, messageId, statusCode, statusText });
            break;
        }
    } catch (Exception e) {
        // An exception occured - this could still be a communication error (e.g Connection refused)
        logger.error("SEND error channelId: {}, messageId: {} url: {} error: {}",
                new Object[] { channelId, messageId, sendUrl, e.getMessage() });

        failureAction.execute(new JoynrCommunicationException(
                e.getClass().getName() + "Exception while communicating. error: " + e.getMessage()));
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
    }
}

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

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

    final String tenantId = request.getTenant();
    final String deviceId = request.getDeviceId();

    if (tenantId == null || deviceId == null) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    } else {/*from  w w  w  .  j av  a  2  s .co m*/
        log.debug("retrieving device [{}] of tenant [{}]", deviceId, tenantId);
        final Future<RegistrationResult> result = Future.future();
        getDevice(tenantId, deviceId, result.completer());
        return result.map(res -> {
            return request.getResponse(res.getStatus()).setDeviceId(deviceId).setJsonPayload(res.getPayload())
                    .setCacheDirective(res.getCacheDirective());
        });
    }
}

From source file:com.netflix.genie.server.resources.JobResource.java

/**
 * Get job information for given job id.
 *
 * @param id id for job to look up// www .j ava 2s .  c  om
 * @return the Job
 * @throws GenieException For any error
 */
@GET
@Path("/{id}")
@ApiOperation(value = "Find a job by id", notes = "Get the job by id if it exists", response = Job.class)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Job not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid id supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Job getJob(@ApiParam(value = "Id of the job to get.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("called for job with id: " + id);
    return this.jobService.getJob(id);
}

From source file:rapture.series.children.ChildrenRepo.java

public boolean dropFileEntry(String filePath) {
    String parent = SeriesPathParser.getParent(filePath);
    String child = ChildKeyUtil.createColumnFile(SeriesPathParser.getChild(filePath));
    boolean ret = false;
    try {//from   w w  w  .j a  v a2  s.co  m
        ret = dropPoints(ChildKeyUtil.createRowKey(parent), ImmutableList.of(child));
        if (ret) {
            // If we call dropFolderEntry here it will cause an endless loop for Cassandra
            FolderCleanupService.getInstance().addForReview(getUniqueId(), parent);
        }
    } catch (Exception e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "Error communicating with the database", e);
    }
    return ret;
}

From source file:rapture.kernel.SearchApiImpl.java

@Override
public SearchRepoConfig getSearchRepoConfig(CallingContext context, String searchRepoUri) {
    RaptureURI uri = new RaptureURI(searchRepoUri, Scheme.SEARCH);
    if (uri.hasDocPath()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoDocPath", searchRepoUri)); //$NON-NLS-1$
    }/*  w  w w  . j a  v  a2 s.  c  o m*/
    return SearchRepoConfigStorage.readByAddress(uri);
}

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

/**
 * Returns a BAD_REQUEST response
 */
protected Response badRequest() {
    return status(HttpURLConnection.HTTP_BAD_REQUEST);
}

From source file:rapture.kernel.StructuredApiImpl.java

private StructuredRepo getRepoOrFail(String authority) {
    StructuredRepo repo = getRepoFromCache(authority);
    if (repo == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoSuchRepo", Scheme.STRUCTURED + "://" + authority)); //$NON-NLS-1$
    } else {/*from   w  ww  .  j a v a 2s. com*/
        return repo;
    }
}

From source file:com.mobicage.rogerthat.CallbackApiServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json-rpc; charset=utf-8");

    // Validate incomming request
    final String contentType = req.getHeader("Content-type");
    if (contentType == null || !contentType.startsWith("application/json-rpc")) {
        resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
        return;/* www  . java 2 s  .  c  o  m*/
    }
    final String sikKey = req.getHeader("X-Nuntiuz-Service-Key");
    if (!validateSIK(sikKey)) {
        resp.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
        return;
    }

    // Parse
    final InputStream is = req.getInputStream();
    final JSONObject request;
    try {
        request = (JSONObject) JSONValue.parse(new BufferedReader(new InputStreamReader(is, "UTF-8")));
    } finally {
        is.close();
    }

    if (logTraffic)
        log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sikKey,
                request.toJSONString()));

    final String id = (String) request.get("id");

    if (callbackDedup != null) {
        byte[] response = callbackDedup.getResponse(id);
        if (response != null) {
            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.write(response);
            outputStream.flush();
            return;
        }
    }

    final JSONObject result = new JSONObject();
    final RequestContext requestContext = new RequestContext(id, sikKey);
    try {
        processor.process(request, result, requestContext);
    } finally {
        String jsonString = result.toJSONString();
        if (logTraffic)
            log.info("Returning result:\n" + jsonString);

        byte[] response = jsonString.getBytes("UTF-8");
        if (callbackDedup != null) {
            callbackDedup.storeResponse(id, response);
        }

        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(response);
        outputStream.flush();
    }
}

From source file:rapture.kernel.SeriesApiImpl.java

@Override
public SeriesRepoConfig getSeriesRepoConfig(CallingContext context, String seriesURI) {
    RaptureURI internalURI = new RaptureURI(seriesURI, Scheme.SERIES);

    if (internalURI.hasDocPath()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoDocPath", seriesURI)); //$NON-NLS-1$
    }//from   w w  w.  j a  v a 2 s  . c o  m

    return SeriesRepoConfigStorage.readByAddress(internalURI);
}

From source file:rapture.mongodb.MongoDBFactory.java

private DB _getDB(String instanceName) {
    if (mongoDBs.containsKey(instanceName)) {
        return mongoDBs.get(instanceName);
    } else {/*from w w w . jav a 2 s. c  o m*/
        getMongoForInstance(instanceName);
        if (mongoDBs.containsKey(instanceName)) {
            return mongoDBs.get(instanceName);
        } else {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                    mongoMsgCatalog.getMessage("NotInitialized"));
        }
    }
}