Example usage for java.net HttpURLConnection HTTP_INTERNAL_ERROR

List of usage examples for java.net HttpURLConnection HTTP_INTERNAL_ERROR

Introduction

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

Prototype

int HTTP_INTERNAL_ERROR

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

Click Source Link

Document

HTTP Status-Code 500: Internal Server Error.

Usage

From source file:be.cytomine.client.HttpClient.java

public static BufferedImage readBufferedImageFromPOST(String url, String post) throws IOException {
    log.debug("readBufferedImageFromURL:" + url);
    URL URL = new URL(url);
    HttpHost targetHost = new HttpHost(URL.getHost(), URL.getPort());
    log.debug("targetHost:" + targetHost);
    DefaultHttpClient client = new DefaultHttpClient();

    log.debug("client:" + client);
    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    log.debug("localcontext:" + localcontext);

    BufferedImage img = null;/* ww w .j a  va 2s.  com*/
    HttpPost httpPost = new HttpPost(URL.toString());
    httpPost.setEntity(new StringEntity(post, "UTF-8"));
    HttpResponse response = client.execute(targetHost, httpPost, localcontext);

    int code = response.getStatusLine().getStatusCode();
    log.info("url=" + url + " is " + code + "(OK=" + HttpURLConnection.HTTP_OK + ",MOVED="
            + HttpURLConnection.HTTP_MOVED_TEMP + ")");

    boolean isOK = (code == HttpURLConnection.HTTP_OK);
    boolean isFound = (code == HttpURLConnection.HTTP_MOVED_TEMP);
    boolean isErrorServer = (code == HttpURLConnection.HTTP_INTERNAL_ERROR);

    if (!isOK && !isFound & !isErrorServer)
        throw new IOException(url + " cannot be read: " + code);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        img = ImageIO.read(entity.getContent());
    }
    return img;
}

From source file:rapture.kernel.BlobApiImpl.java

@Override
public BlobContainer getBlob(CallingContext context, String blobUri) {

    BlobContainer retVal = new BlobContainer();

    // TODO: Ben - push this up to the wrapper - the this class should
    // implement the Trusted API.
    RaptureURI interimUri = new RaptureURI(blobUri, BLOB);
    if (interimUri.hasAttribute()) {
        // TODO: Ben - This is messy, and shouldn't really be used, throw an
        // exception here?
        ContentEnvelope content = getContent(context, interimUri);
        try {/*from  w w  w.j  av  a2  s  .co  m*/
            retVal.setContent(content.getContent().toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                    apiMessageCatalog.getMessage("ErrorGettingBlob"), e);
        }
        return retVal;
    } else {
        BlobRepo blobRepo = getRepoFromCache(interimUri.getAuthority());
        if (blobRepo == null) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                    apiMessageCatalog.getMessage("NoSuchRepo", interimUri.toAuthString())); //$NON-NLS-1$
        }

        try (InputStream in = blobRepo.getBlob(context, interimUri)) {
            if (in != null) {
                retVal.setContent(IOUtils.toByteArray(in));
                Map<String, String> metaData = getBlobMetaData(context, blobUri);
                Map<String, String> headers = new HashMap<>();
                headers.put(ContentEnvelope.CONTENT_SIZE, metaData.get(ContentEnvelope.CONTENT_SIZE));
                headers.put(ContentEnvelope.CONTENT_TYPE_HEADER,
                        metaData.get(ContentEnvelope.CONTENT_TYPE_HEADER));
                retVal.setHeaders(headers);
                return retVal;
            } else {
                return null;
            }
        } catch (IOException e) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                    apiMessageCatalog.getMessage("ErrorGettingBlob"), e);
        }
    }

}

From source file:rapture.repo.VersionedRepo.java

@Override
public void drop() {
    if (cacheKeyStore != null) {
        cacheKeyStore.dropKeyStore();//from  ww  w .j a  v a2 s  .  c  o m
    }
    if (!store.dropKeyStore()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Could not drop keystore");
    }
}

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

/**
 * Add new tags to a given job./*  w w w .j av a 2s .  c om*/
 *
 * @param id   The id of the job to add the tags to. Not
 *             null/empty/blank.
 * @param tags The tags to add. Not null/empty/blank.
 * @return The active tags for this job.
 * @throws GenieException For any error
 */
@POST
@Path("/{id}/tags")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add new tags to a job", notes = "Add the supplied tags to the job with the supplied id.", response = String.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Job for id does not exist."),
        @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 Set<String> addTagsForJob(
        @ApiParam(value = "Id of the job to add configuration to.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The tags to add.", required = true) final Set<String> tags) throws GenieException {
    LOG.info("Called with id " + id + " and tags " + tags);
    return this.jobService.addTagsForJob(id, tags);
}

From source file:org.openhab.binding.digitalstrom.internal.lib.manager.impl.ConnectionManagerImpl.java

@Override
public boolean checkConnection(int code) {
    switch (code) {
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_OK:
        if (!connectionEstablished) {
            connectionEstablished = true;
            onConnectionResumed();// w  ww .ja  v  a  2s .  c  o  m
        }
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        connectionEstablished = false;
        break;
    case HttpURLConnection.HTTP_FORBIDDEN:
        getNewSessionToken();
        if (sessionToken != null) {
            if (!connectionEstablished) {
                onConnectionResumed();
                connectionEstablished = true;
            }
        } else {
            if (this.genAppToken) {
                onNotAuthenticated();
            }
            connectionEstablished = false;
        }
        break;
    case ConnectionManager.MALFORMED_URL_EXCEPTION:
        onConnectionLost(ConnectionListener.INVALID_URL);
        connectionEstablished = false;
        break;
    case ConnectionManager.CONNECTION_EXCEPTION:
    case ConnectionManager.SOCKET_TIMEOUT_EXCEPTION:
        onConnectionLost(ConnectionListener.CONNECTON_TIMEOUT);
        connectionEstablished = false;
        break;
    case ConnectionManager.GENERAL_EXCEPTION:
        if (connListener != null) {
            connListener.onConnectionStateChange(ConnectionListener.CONNECTION_LOST);
        }
        break;
    case ConnectionManager.UNKNOWN_HOST_EXCEPTION:
        if (connListener != null) {
            onConnectionLost(ConnectionListener.UNKNOWN_HOST);
        }
        break;
    case ConnectionManager.AUTHENTIFICATION_PROBLEM:
        if (connListener != null) {
            if (config.getAppToken() != null) {
                connListener.onConnectionStateChange(ConnectionListener.NOT_AUTHENTICATED,
                        ConnectionListener.WRONG_APP_TOKEN);
            } else {
                connListener.onConnectionStateChange(ConnectionListener.NOT_AUTHENTICATED,
                        ConnectionListener.WRONG_USER_OR_PASSWORD);
            }
        }
        break;
    case HttpURLConnection.HTTP_NOT_FOUND:
        onConnectionLost(ConnectionListener.HOST_NOT_FOUND);
        connectionEstablished = false;
        break;
    }
    return connectionEstablished;
}

From source file:org.eclipse.hono.service.amqp.RequestResponseEndpoint.java

/**
 * Handles a client's request to establish a link for receiving responses
 * to service invocations.//from   w  ww.  j  a v a2  s .c  o  m
 * <p>
 * This method registers a consumer on the vert.x event bus for the given reply-to address.
 * Response messages received over the event bus are transformed into AMQP messages using
 * the {@link #getAmqpReply(EventBusMessage)} method and sent to the client over the established
 * link.
 *
 * @param con The AMQP connection that the link is part of.
 * @param sender The link to establish.
 * @param replyToAddress The reply-to address to create a consumer on the event bus for.
 */
@Override
public final void onLinkAttach(final ProtonConnection con, final ProtonSender sender,
        final ResourceIdentifier replyToAddress) {

    if (isValidReplyToAddress(replyToAddress)) {
        logger.debug("establishing sender link with client [{}]", sender.getName());
        final MessageConsumer<JsonObject> replyConsumer = vertx.eventBus().consumer(replyToAddress.toString(),
                message -> {
                    // TODO check for correct session here...?
                    if (logger.isTraceEnabled()) {
                        logger.trace("forwarding reply to client [{}]: {}", sender.getName(),
                                message.body().encodePrettily());
                    }
                    final EventBusMessage response = EventBusMessage.fromJson(message.body());
                    filterResponse(Constants.getClientPrincipal(con), response).recover(t -> {
                        final int status = Optional.of(t).map(cause -> {
                            if (cause instanceof ServiceInvocationException) {
                                return ((ServiceInvocationException) cause).getErrorCode();
                            } else {
                                return null;
                            }
                        }).orElse(HttpURLConnection.HTTP_INTERNAL_ERROR);
                        return Future.succeededFuture(response.getResponse(status));
                    }).map(filteredResponse -> {
                        final Message amqpReply = getAmqpReply(filteredResponse);
                        sender.send(amqpReply);
                        return null;
                    });
                });

        sender.setQoS(ProtonQoS.AT_LEAST_ONCE);
        sender.closeHandler(senderClosed -> {
            logger.debug("client [{}] closed sender link, removing associated event bus consumer [{}]",
                    sender.getName(), replyConsumer.address());
            replyConsumer.unregister();
            if (senderClosed.succeeded()) {
                senderClosed.result().close();
            }
        });
        sender.open();
    } else {
        logger.debug("client [{}] provided invalid reply-to address", sender.getName());
        sender.setCondition(ProtonHelper.condition(AmqpError.INVALID_FIELD, String.format(
                "reply-to address must have the following format %s/<tenant>/<reply-address>", getName())));
        sender.close();
    }
}

From source file:com.netflix.genie.server.services.impl.GenieExecutionServiceImpl.java

/** {@inheritDoc} */
@Override//w w  w.  j a  v  a  2 s  . c  o  m
public JobInfoResponse getJobs(String jobID, String jobName, String userName, String jobType, String status,
        String clusterName, String clusterId, Integer limit, Integer page) {
    logger.info("called");

    JobInfoResponse response;
    String table = JobInfoElement.class.getSimpleName();

    ClauseBuilder criteria = null;
    try {
        criteria = new ClauseBuilder(ClauseBuilder.AND);
        if ((jobID != null) && (!jobID.isEmpty())) {
            String query = "jobID like '" + jobID + "'";
            criteria.append(query);
        }
        if ((jobName != null) && (!jobName.isEmpty())) {
            String query = "jobName like '" + jobName + "'";
            criteria.append(query);
        }
        if ((userName != null) && (!userName.isEmpty())) {
            String query = "userName='" + userName + "'";
            criteria.append(query);
        }
        if ((jobType != null) && (!jobType.isEmpty())) {
            if (Types.JobType.parse(jobType) == null) {
                throw new CloudServiceException(HttpURLConnection.HTTP_BAD_REQUEST,
                        "Job type: " + jobType + " can only be HADOOP, HIVE or PIG");
            }
            String query = "jobType='" + jobType.toUpperCase() + "'";
            criteria.append(query);
        }
        if ((status != null) && (!status.isEmpty())) {
            if (Types.JobStatus.parse(status) == null) {
                throw new CloudServiceException(HttpURLConnection.HTTP_BAD_REQUEST,
                        "Unknown job status: " + status);
            }
            String query = "status='" + status.toUpperCase() + "'";
            criteria.append(query);
        }
        if ((clusterName != null) && (!clusterName.isEmpty())) {
            String query = "clusterName='" + clusterName + "'";
            criteria.append(query);
        }
        if ((clusterId != null) && (!clusterId.isEmpty())) {
            String query = "clusterId='" + clusterId + "'";
            criteria.append(query);
        }
    } catch (CloudServiceException e) {
        logger.error(e.getMessage(), e);
        response = new JobInfoResponse(e);
        return response;
    }

    Object[] results;
    try {
        QueryBuilder builder = new QueryBuilder().table(table).clause(criteria.toString()).limit(limit)
                .page(page);
        results = pm.query(builder);

    } catch (Exception e) {
        logger.error("Failed to get job results from database: ", e);
        response = new JobInfoResponse(
                new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage()));
        return response;
    }

    if (results.length != 0) {
        JobInfoElement[] jobInfos = new JobInfoElement[results.length];
        for (int i = 0; i < results.length; i++) {
            jobInfos[i] = (JobInfoElement) results[i];
        }

        response = new JobInfoResponse();
        response.setJobs(jobInfos);
        response.setMessage("Returning job information for specified criteria");
        return response;
    } else {
        response = new JobInfoResponse(new CloudServiceException(HttpURLConnection.HTTP_NOT_FOUND,
                "No jobs found for specified criteria"));
        return response;
    }
}

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

/**
 * Get all the configuration files for a given command.
 *
 * @param id The id of the command to get the configuration files for. Not
 *           NULL/empty/blank.//from ww  w .j  a  v a2  s .  c o  m
 * @return The active set of configuration files.
 * @throws GenieException For any error
 */
@GET
@Path("/{id}/configs")
@ApiOperation(value = "Get the configuration files for a command", notes = "Get the configuration files for the command with the supplied id.", response = String.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Command not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Set<String> getConfigsForCommand(
        @ApiParam(value = "Id of the command to get configurations for.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called with id " + id);
    return this.commandConfigService.getConfigsForCommand(id);
}

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

@Override
public RaptureQueryResult runNativeQuery(String repoType, List<String> queryParams) {
    if (repoType.toUpperCase().equals("GCP_DATASTORE")) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Not yet implemented");
    } else {//from  www.  ja  v  a  2  s .  co  m
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "RepoType mismatch. Repo is of type GCP_DATASTORE, asked for " + repoType);
    }
}

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

/**
 * Get all the configuration files for a given application.
 *
 * @param id The id of the application to get the configuration files for.
 *           Not NULL/empty/blank./* w  w w  .j av  a2  s  . c  o  m*/
 * @return The active set of configuration files.
 * @throws GenieException For any error
 */
@GET
@Path("/{id}/configs")
@ApiOperation(value = "Get the configuration files for an application", notes = "Get the configuration files for the application with the supplied id.", response = String.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Application 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 Set<String> getConfigsForApplication(
        @ApiParam(value = "Id of the application to get configurations for.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called with id " + id);
    return this.applicationConfigService.getConfigsForApplication(id);
}