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:org.languagetool.server.LanguageToolHttpHandler.java

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    long startTime = System.currentTimeMillis();
    String remoteAddress = null;//from  w ww.  j av a2  s. c  o m
    Map<String, String> parameters = new HashMap<>();
    int reqId = reqCounter.incrementRequestCount();
    ServerMetricsCollector.getInstance().logRequest();
    boolean incrementHandleCount = false;
    try {
        URI requestedUri = httpExchange.getRequestURI();
        if (requestedUri.getRawPath().startsWith("/v2/")) {
            // healthcheck should come before other limit checks (requests per time etc.), to be sure it works: 
            String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length());
            if (pathWithoutVersion.equals("healthcheck")) {
                if (workQueueFull(httpExchange, parameters,
                        "Healthcheck failed: There are currently too many parallel requests.")) {
                    ServerMetricsCollector.getInstance().logFailedHealthcheck();
                    return;
                } else {
                    String ok = "OK";
                    httpExchange.getResponseHeaders().set("Content-Type", "text/plain");
                    httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, ok.getBytes(ENCODING).length);
                    httpExchange.getResponseBody().write(ok.getBytes(ENCODING));
                    ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_OK);
                    return;
                }
            }
        }
        String referrer = httpExchange.getRequestHeaders().getFirst("Referer");
        String origin = httpExchange.getRequestHeaders().getFirst("Origin"); // Referer can be turned off with meta tags, so also check this
        for (String ref : config.getBlockedReferrers()) {
            String errorMessage = null;
            if (ref != null && !ref.isEmpty()) {
                if (referrer != null && siteMatches(referrer, ref)) {
                    errorMessage = "Error: Access with referrer " + referrer + " denied.";
                } else if (origin != null && siteMatches(origin, ref)) {
                    errorMessage = "Error: Access with origin " + origin + " denied.";
                }
            }
            if (errorMessage != null) {
                sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage);
                logError(errorMessage, HttpURLConnection.HTTP_FORBIDDEN, parameters, httpExchange);
                ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_FORBIDDEN);
                return;
            }
        }
        String origAddress = httpExchange.getRemoteAddress().getAddress().getHostAddress();
        String realAddressOrNull = getRealRemoteAddressOrNull(httpExchange);
        remoteAddress = realAddressOrNull != null ? realAddressOrNull : origAddress;
        reqCounter.incrementHandleCount(remoteAddress, reqId);
        incrementHandleCount = true;
        // According to the Javadoc, "Closing an exchange without consuming all of the request body is
        // not an error but may make the underlying TCP connection unusable for following exchanges.",
        // so we consume the request now, even before checking for request limits:
        parameters = getRequestQuery(httpExchange, requestedUri);
        if (requestLimiter != null) {
            try {
                requestLimiter.checkAccess(remoteAddress, parameters, httpExchange.getRequestHeaders());
            } catch (TooManyRequestsException e) {
                String errorMessage = "Error: Access from " + remoteAddress + " denied: " + e.getMessage();
                int code = HttpURLConnection.HTTP_FORBIDDEN;
                sendError(httpExchange, code, errorMessage);
                // already logged vai DatabaseAccessLimitLogEntry
                logError(errorMessage, code, parameters, httpExchange, false);
                return;
            }
        }
        if (errorRequestLimiter != null && !errorRequestLimiter.wouldAccessBeOkay(remoteAddress, parameters,
                httpExchange.getRequestHeaders())) {
            String textSizeMessage = getTextOrDataSizeMessage(parameters);
            String errorMessage = "Error: Access from " + remoteAddress + " denied - too many recent timeouts. "
                    + textSizeMessage + " Allowed maximum timeouts: " + errorRequestLimiter.getRequestLimit()
                    + " per " + errorRequestLimiter.getRequestLimitPeriodInSeconds() + " seconds";
            int code = HttpURLConnection.HTTP_FORBIDDEN;
            sendError(httpExchange, code, errorMessage);
            logError(errorMessage, code, parameters, httpExchange);
            return;
        }
        if (workQueueFull(httpExchange, parameters,
                "Error: There are currently too many parallel requests. Please try again later.")) {
            ServerMetricsCollector.getInstance()
                    .logRequestError(ServerMetricsCollector.RequestErrorType.QUEUE_FULL);
            return;
        }
        if (allowedIps == null || allowedIps.contains(origAddress)) {
            if (requestedUri.getRawPath().startsWith("/v2/")) {
                ApiV2 apiV2 = new ApiV2(textCheckerV2, config.getAllowOriginUrl());
                String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length());
                apiV2.handleRequest(pathWithoutVersion, httpExchange, parameters, errorRequestLimiter,
                        remoteAddress, config);
            } else if (requestedUri.getRawPath().endsWith("/Languages")) {
                throw new IllegalArgumentException(
                        "You're using an old version of our API that's not supported anymore. Please see https://languagetool.org/http-api/migration.php");
            } else if (requestedUri.getRawPath().equals("/")) {
                throw new IllegalArgumentException(
                        "Missing arguments for LanguageTool API. Please see " + API_DOC_URL);
            } else if (requestedUri.getRawPath().contains("/v2/")) {
                throw new IllegalArgumentException(
                        "You have '/v2/' in your path, but not at the root. Try an URL like 'http://server/v2/...' ");
            } else if (requestedUri.getRawPath().equals("/favicon.ico")) {
                sendError(httpExchange, HttpURLConnection.HTTP_NOT_FOUND, "Not found");
            } else {
                throw new IllegalArgumentException(
                        "This is the LanguageTool API. You have not specified any parameters. Please see "
                                + API_DOC_URL);
            }
        } else {
            String errorMessage = "Error: Access from " + StringTools.escapeXML(origAddress) + " denied";
            sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage);
            throw new RuntimeException(errorMessage);
        }
    } catch (Exception e) {
        String response;
        int errorCode;
        boolean textLoggingAllowed = false;
        boolean logStacktrace = true;
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (e instanceof TextTooLongException || rootCause instanceof TextTooLongException) {
            errorCode = HttpURLConnection.HTTP_ENTITY_TOO_LARGE;
            response = e.getMessage();
            logStacktrace = false;
        } else if (e instanceof ErrorRateTooHighException || rootCause instanceof ErrorRateTooHighException) {
            errorCode = HttpURLConnection.HTTP_BAD_REQUEST;
            response = ExceptionUtils.getRootCause(e).getMessage();
            logStacktrace = false;
        } else if (hasCause(e, AuthException.class)) {
            errorCode = HttpURLConnection.HTTP_FORBIDDEN;
            response = e.getMessage();
            logStacktrace = false;
        } else if (e instanceof IllegalArgumentException || rootCause instanceof IllegalArgumentException) {
            errorCode = HttpURLConnection.HTTP_BAD_REQUEST;
            response = e.getMessage();
        } else if (e instanceof PathNotFoundException || rootCause instanceof PathNotFoundException) {
            errorCode = HttpURLConnection.HTTP_NOT_FOUND;
            response = e.getMessage();
        } else if (e instanceof TimeoutException || rootCause instanceof TimeoutException) {
            errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
            response = "Checking took longer than " + config.getMaxCheckTimeMillis() / 1000.0f
                    + " seconds, which is this server's limit. "
                    + "Please make sure you have selected the proper language or consider submitting a shorter text.";
        } else {
            response = "Internal Error: " + e.getMessage();
            errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
            textLoggingAllowed = true;
        }
        long endTime = System.currentTimeMillis();
        logError(remoteAddress, e, errorCode, httpExchange, parameters, textLoggingAllowed, logStacktrace,
                endTime - startTime);
        sendError(httpExchange, errorCode, "Error: " + response);

    } finally {
        httpExchange.close();
        if (incrementHandleCount) {
            reqCounter.decrementHandleCount(reqId);
        }
    }
}

From source file:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testServerErrorSetTTL() throws IOException {
    try {/*from   w ww .  j  av  a  2  s  . c o m*/
        streamClient.setTTL(StringUtils.EMPTY, STREAM_TTL);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getStatusCode());
    }
}

From source file:de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService.java

@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)/* w  ww . j  a  v a2s.c o m*/
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "This method allows to create an activity", notes = "Returns the created activity")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Activity created"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") })
public HttpResponse createActivity(
        @ApiParam(value = "Activity" + " entity as JSON", required = true) @ContentParam String activity) {
    Gson gson = new Gson();
    DALFacade dalFacade = null;
    Activity activityToCreate = gson.fromJson(activity, Activity.class);
    //TODO validate activity
    try {
        dalFacade = getDBConnection();
        Activity createdActivity = dalFacade.createActivity(activityToCreate);
        return new HttpResponse(gson.toJson(createdActivity), HttpURLConnection.HTTP_CREATED);
    } catch (Exception ex) {
        ActivityTrackerException atException = ExceptionHandler.getInstance().convert(ex,
                ExceptionLocation.ACTIVITIESERVICE, ErrorCode.UNKNOWN, "");
        return new HttpResponse(ExceptionHandler.getInstance().toJSON(atException),
                HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        closeDBConnection(dalFacade);
    }
}

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

/**
 * Kill job based on given job ID.//from w w  w. java 2  s. c  o m
 *
 * @param id id for job to kill
 * @return The job that was killed
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}")
@ApiOperation(value = "Delete a job", notes = "Delete the job with the id specified.", response = Job.class)
@ApiResponses(value = { @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 killJob(@ApiParam(value = "Id of the job.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called for job id: " + id);
    return this.executionService.killJob(id);
}

From source file:rapture.pipeline2.gcp.PubsubPipeline2Handler.java

@Override
public void publishTask(final String queue, final String task) {
    Topic topic = getTopic(queue);/*from  www.  java  2s.c om*/
    ByteString data = ByteString.copyFromUtf8(task);
    TopicName topicName = topic.getNameAsTopicName();

    try {
        PubsubMessage psmessage = PubsubMessage.newBuilder().setData(data).build();
        Publisher publisher = randomHouse.get(topicName);
        if (publisher == null) {
            logger.trace("No publisher found for " + topicName + " - creating");
            Builder builder = Publisher.defaultBuilder(topicName);
            // The default executor provider creates an insane number of threads.
            if (executor != null)
                builder.setExecutorProvider(executor);
            publisher = builder.build();
            randomHouse.put(topicName, publisher);
        } else {
            logger.trace("Existing publisher found for " + topicName);
        }

        ApiFuture<String> messageIdFuture = publisher.publish(psmessage);

        if (executor != null)
            messageIdFuture.addListener(listener, executor.getExecutor());

    } catch (IOException e) {
        String error = String.format("Cannot send message to topic %s:\n%s", topic.getName(),
                ExceptionToString.format(e));
        logger.error(error);
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, error, e);
    }
}

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

public BufferedImage readBufferedImageFromURL(String url) 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);

    headersArray = null;//from ww  w . j a  v a  2  s  .c o m
    authorize("GET", URL.toString(), "", "application/json,*/*");

    BufferedImage img = null;
    HttpGet httpGet = new HttpGet(URL.toString());
    httpGet.setHeaders(headersArray);
    HttpResponse response = client.execute(targetHost, httpGet, 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:com.netflix.genie.server.resources.CommandConfigResource.java

/**
 * Add new configuration files to a given command.
 *
 * @param id      The id of the command to add the configuration file to. Not
 *                null/empty/blank./*from   w  ww  . j  a  v a2  s .c o m*/
 * @param configs The configuration files to add. Not null/empty/blank.
 * @return The active configurations for this command.
 * @throws GenieException For any error
 */
@POST
@Path("/{id}/configs")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add new configuration files to a command", notes = "Add the supplied configuration files to 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> addConfigsForCommand(
        @ApiParam(value = "Id of the command to add configuration to.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The configuration files to add.", required = true) final Set<String> configs)
        throws GenieException {
    LOG.info("Called with id " + id + " and config " + configs);
    return this.commandConfigService.addConfigsForCommand(id, configs);
}

From source file:org.cellprofiler.subimager.ImageWriterHandler.java

/**
 * Write the image plane to the given uri
 * /*from w  w  w  . j  a  va  2s.  co m*/
 * @param exchange the HttpExchange for the connection
 * @param ndimage the image to write
 * @param uri the file URI to write to (must be a file URI currently)
 * @param omeXML the OME-XML metadata for the plane
 * @param index the planar index of the plane being written to the file. Note that the indices must be written in order and that an index of 0 will truncate the file.
 * @param compression the compression method to be used
 * @throws IOException
 */
private void writeImage(HttpExchange exchange, NDImage ndimage, URI uri, String omeXML, int index,
        String compression) throws IOException {
    if (!uri.getScheme().equals("file")) {
        reportError(exchange, HttpURLConnection.HTTP_NOT_IMPLEMENTED,
                "<html><body>This server currently only supports the file: protocol, url=" + uri.toString()
                        + "</body></html>");
        return;
    }
    File outputFile = new File(uri);
    if ((index == 0) && outputFile.exists()) {
        outputFile.delete();
    }
    IMetadata metadata = null;
    try {
        ServiceFactory factory;
        factory = new ServiceFactory();
        OMEXMLService service = factory.getInstance(OMEXMLService.class);
        metadata = service.createOMEXMLMetadata(omeXML);
    } catch (DependencyException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>Configuration error: could not create OMEXML service - check for missing omexml libraries</body></html>");
        return;
    } catch (ServiceException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>Possible OME-XML parsing error: " + e.getMessage() + "</body></html>");
        return;
    }
    ImageWriter writer = new ImageWriter();
    writer.setMetadataRetrieve(metadata);
    try {
        writer.setId(outputFile.getAbsolutePath());
    } catch (IOException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>Failed to open output file " + outputFile.getAbsolutePath() + "</body></html>");
        return;
    } catch (FormatException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>Format exception when opening output file: " + e.getMessage() + "</body></html>");
        return;
    }
    PixelType pixelType = metadata.getPixelsType(0);
    if (SUPPORTED_PIXEL_TYPES.indexOf(pixelType) == -1) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>Unsupported pixel type: " + pixelType.getValue() + "</body></html>");
        return;
    }
    boolean toBigEndian = metadata.getPixelsBinDataBigEndian(0, 0);
    writer.setInterleaved(true);
    List<String> compressionTypes = Arrays.asList(writer.getCompressionTypes());
    try {
        if (compression == DEFAULT_COMPRESSION) {
            for (String possibleCompression : PREFERRED_COMPRESSION) {
                if (compressionTypes.indexOf(possibleCompression) != -1) {
                    //writer.setCompression(possibleCompression);
                    break;
                }
            }
        } else {
            if (compressionTypes.indexOf(compression) == -1) {
                reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                        "<html><body>Unsupported compression type: " + compression + "</body></html>");
                return;
            }
            writer.setCompression(compression);
        }
    } catch (FormatException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>Error when setting compression type: " + e.getMessage() + "</body></html>");
        return;
    }
    byte[] buffer = convertImage(ndimage, pixelType, toBigEndian);
    try {
        writer.saveBytes(index, buffer);
        writer.close();
    } catch (IOException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>An I/O error prevented the server from writing the image: " + e.getMessage()
                        + "</body></html>");
        return;
    } catch (FormatException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>The imaging library failed to write the image because of a format error: "
                        + e.getMessage() + "</body></html>");
        return;
    }
    String html = String.format("<html><body>%s successfully written</body></html>",
            StringEscapeUtils.escapeHtml(outputFile.getAbsolutePath()));
    reportError(exchange, HttpURLConnection.HTTP_OK, html);
}

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

/**
 * Add new configuration files to a given application.
 *
 * @param id      The id of the application to add the configuration file to. Not
 *                null/empty/blank.//from   w w w .  ja v  a2 s  .  c  om
 * @param configs The configuration files to add. Not null/empty/blank.
 * @return The active configurations for this application.
 * @throws GenieException For any error
 */
@POST
@Path("/{id}/configs")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add new configuration files to an application", notes = "Add the supplied configuration files to 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> addConfigsToApplication(
        @ApiParam(value = "Id of the application to add configuration to.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The configuration files to add.", required = true) final Set<String> configs)
        throws GenieException {
    LOG.info("Called with id " + id + " and config " + configs);
    return this.applicationConfigService.addConfigsToApplication(id, configs);
}

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

/**
 * Add new configuration files to a given cluster.
 *
 * @param id      The id of the cluster to add the configuration file to. Not
 *                null/empty/blank./*from   www  .j  a  va  2 s. c o m*/
 * @param configs The configuration files to add. Not null/empty/blank.
 * @return The active configurations for this cluster.
 * @throws GenieException For any error
 */
@POST
@Path("/{id}/configs")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add new configuration files to a cluster", notes = "Add the supplied configuration files to the cluster with the supplied id.", response = String.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Cluster 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> addConfigsForCluster(
        @ApiParam(value = "Id of the cluster to add configuration to.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The configuration files to add.", required = true) final Set<String> configs)
        throws GenieException {
    LOG.info("Called with id " + id + " and config " + configs);
    return this.clusterConfigService.addConfigsForCluster(id, configs);
}