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:com.adaptris.http.RequestDispatcher.java

public void run() {
    RequestProcessor rp = null;//  www . j a v  a2  s.  c o  m
    HttpSession session = null;
    LinkedBlockingQueue queue = null;
    String oldName = Thread.currentThread().getName();
    Thread.currentThread().setName(threadName);
    do {
        try {
            if (logR.isTraceEnabled()) {
                logR.trace("Reading HTTP Request");
            }

            session = new ServerSession();
            session.setSocket(socket);
            //        String uri = session.getRequestLine().getURI();

            String file = session.getRequestLine().getFile();
            queue = (LinkedBlockingQueue) requestProcessors.get(file);

            if (queue == null) {
                // Get a default one, if any
                queue = (LinkedBlockingQueue) requestProcessors.get("*");
                if (queue == null) {
                    doResponse(session, HttpURLConnection.HTTP_NOT_FOUND);
                    break;
                }
            }
            rp = waitForRequestProcessor(queue);
            if (!parent.isAlive()) {
                doResponse(session, HttpURLConnection.HTTP_INTERNAL_ERROR);
                break;
            }
            rp.processRequest(session);
            session.commit();
        } catch (Exception e) {
            // if an exception occurs, then it's pretty much a fatal error for 
            // this session
            // we ignore any output that it might have setup, and use our own
            try {
                logR.error(e.getMessage(), e);
                if (session != null) {
                    doResponse(session, HttpURLConnection.HTTP_INTERNAL_ERROR);
                }
            } catch (Exception e2) {
                ;
            }
        }
    } while (false);
    try {
        if (rp != null && queue != null) {
            queue.put(rp);
            logR.trace(rp + " put back on to queue");
        }
    } catch (Exception e) {
        ;
    }
    session = null;
    queue = null;
    rp = null;
    Thread.currentThread().setName(oldName);
    return;
}

From source file:org.mskcc.cbio.portal.util.SessionServiceUtil.java

/**
 * Returns an ServletRequest parameter map for a given sessionId.  
 * Returns null if the session was not found.
 *
 * @param sessionId//  www .j  a  v  a  2s.co m
 * @return an ServletRequest parameter map
 * @throws HttpException if session service API returns with a response code that is not 404 or 200
 * @throws MalformedURLException
 * @throws IOException
 * @see ServletRequest#getParameterMap
 */
public static Map<String, String[]> getSession(String sessionId)
        throws HttpException, MalformedURLException, IOException {
    LOG.debug("SessionServiceUtil.getSession()");
    Map<String, String[]> parameterMap = null;
    HttpURLConnection conn = null;
    try {
        URL url = new URL(GlobalProperties.getSessionServiceUrl() + "main_session/" + sessionId);

        LOG.debug("SessionServiceUtil.getSession(): url = '" + url + "'");
        conn = (HttpURLConnection) url.openConnection();

        // Use basic authentication if provided (https://stackoverflow.com/questions/496651)
        if (isBasicAuthEnabled()) {
            conn.setRequestProperty("Authorization", getBasicAuthString());
        }

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            StringWriter stringWriter = new StringWriter();
            IOUtils.copy(conn.getInputStream(), stringWriter, Charset.forName("UTF-8"));
            String contentString = stringWriter.toString();
            LOG.debug("SessionServiceUtil.getSession(): response = '" + contentString + "'");
            JsonNode json = new ObjectMapper().readTree(contentString);
            LOG.debug(
                    "SessionServiceUtil.getSession(): response.data = '" + json.get("data").textValue() + "'");
            parameterMap = new ObjectMapper().readValue(json.get("data").toString(),
                    new TypeReference<Map<String, String[]>>() {
                    });
        } else {
            LOG.warn("SessionServiceUtil.getSession(): conn.getResponseCode() = '" + conn.getResponseCode()
                    + "'");
            if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
                return null;
            } else if (conn.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                throw new HttpException("Internal server error");
            } else {
                throw new HttpException("Unexpected error, response code '" + conn.getResponseCode() + "'");
            }
        }
    } catch (MalformedURLException mfue) {
        LOG.warn("SessionServiceUtil.getSession(): MalformedURLException = '" + mfue.getMessage() + "'");
        throw mfue;
    } catch (IOException ioe) {
        LOG.warn("SessionServiceUtil.getSession(): IOException = '" + ioe.getMessage() + "'");
        throw ioe;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return parameterMap;
}

From source file:com.utest.webservice.interceptors.UtestRestFaultOutInterceptor.java

public String buildResponse(final Message message) {
    final StringBuffer sb = new StringBuffer();
    final Fault fault = (Fault) message.getContent(Exception.class);
    final String accept = (String) message.getExchange().getInMessage().get(Message.ACCEPT_CONTENT_TYPE);
    int type = TYPE_TEXT;
    int responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
    if (accept.contains(MediaType.APPLICATION_XML)) {
        type = TYPE_XML;/*w  w w . j ava2 s. c om*/
        message.put(Message.CONTENT_TYPE, MediaType.APPLICATION_XML);
    } else if (accept.contains(MediaType.APPLICATION_JSON)) {
        type = TYPE_JSON;
        message.put(Message.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    } else {
        message.put(Message.CONTENT_TYPE, MediaType.TEXT_PLAIN);
    }
    sb.append(getStart(type));
    if (fault.getCause() instanceof ValidationException) {
        final ValidationException ve = (ValidationException) fault.getCause();
        for (final String errmsg : ve.getMessageKeys()) {
            sb.append(createError(type, fault.getCause(), errmsg));
        }
    } else {
        sb.append(createError(type, fault.getCause(), fault.getCause().getMessage()));
    }

    if ((fault.getCause() instanceof org.apache.cxf.interceptor.security.AccessDeniedException)
            || (fault.getCause() instanceof org.springframework.security.access.AccessDeniedException)) {
        responseCode = HttpURLConnection.HTTP_FORBIDDEN;// Access deny
    } else if (fault.getCause() instanceof NotFoundException) {
        responseCode = HttpURLConnection.HTTP_NOT_FOUND;// Not found
    } else if ((fault.getCause() instanceof StaleObjectStateException)
            || (fault.getCause() instanceof StaleStateException)) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof EmailInUseException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof ScreenNameInUseException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof InvalidParentChildEnvironmentException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof DuplicateTestCaseStepException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof DuplicateNameException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof DeletingActivatedEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof DeletingUsedEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof ActivatingIncompleteEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof UnsupportedEnvironmentSelectionException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof ApprovingIncompleteEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof ActivatingNotApprovedEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof ChangingActivatedEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof IncludingMultileVersionsOfSameEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// not allowed
    } else if (fault.getCause() instanceof AssigningMultileVersionsOfSameEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof IncludingNotActivatedEntityException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// Not allowed
    } else if (fault.getCause() instanceof TestCaseExecutionBlockedException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// Not allowed
    } else if (fault.getCause() instanceof TestCaseExecutionWithoutRestartException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// Not allowed
    } else if (fault.getCause() instanceof InvalidParentChildEnvironmentException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof UnsupportedTeamSelectionException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof NoTeamDefinitionException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof InvalidTeamMemberException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    } else if (fault.getCause() instanceof TestCycleClosedException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    }
    // this is here to catch all business exceptions if this interceptor
    // wasn't updated properly
    else if (fault.getCause() instanceof DomainException) {
        responseCode = HttpURLConnection.HTTP_CONFLICT;// conflict
    }

    message.put(Message.RESPONSE_CODE, responseCode);
    sb.append(getEnd(type));
    return sb.toString();
}

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

/**
 * Create an Application./*  www.  j a  va  2 s  .co m*/
 *
 * @param app The application to create
 * @return The created application configuration
 * @throws GenieException For any error
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create an application", notes = "Create an application from the supplied information.", response = Application.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Application created successfully.", response = Application.class),
        @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "An application with the supplied id already exists"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "A precondition failed"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Response createApplication(
        @ApiParam(value = "The application to create.", required = true) final Application app)
        throws GenieException {
    LOG.info("Called to create new application");
    final Application createdApp = this.applicationConfigService.createApplication(app);
    return Response.created(this.uriInfo.getAbsolutePathBuilder().path(createdApp.getId()).build())
            .entity(createdApp).build();
}

From source file:i5.las2peer.services.todolist.Todolist.java

/**
 * //from  w ww.ja  v  a  2s . c  o  m
 * getData
 * 
 * 
 * @return HttpResponse
 * 
 */
@GET
@Path("/data")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "responseGetData") })
@ApiOperation(value = "getData", notes = "")
public HttpResponse getData() {
    JSONObject dataJson = new JSONObject();
    Connection conn = null;
    try {

        conn = dbm.getConnection();
        PreparedStatement stmt = conn
                .prepareStatement("SELECT * FROM gamificationCAE.todolist ORDER BY id ASC");
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            dataJson.put(rs.getInt("id"), rs.getString("name"));

        }

        if (!dataJson.isEmpty()) {
            return new HttpResponse(dataJson.toJSONString(), HttpURLConnection.HTTP_OK);
        }
        return new HttpResponse("No data Found", HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

        return new HttpResponse("Database connection error", HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.jboss.as.test.integration.web.customerrors.CustomErrorsUnitTestCase.java

/**
 * Test that the custom 500 error page is seen
 *
 * @throws Exception/*from w  w w .  j a  v  a  2 s  . c  o m*/
 */
@Test
@OperateOnDeployment("error-producer.war")
public void test500Error(@ArquillianResource(ErrorGeneratorServlet.class) URL baseURL) throws Exception {
    int errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
    URL url = new URL(baseURL + "/ErrorGeneratorServlet?errorCode=" + errorCode);
    testURL(url, errorCode, "500.jsp", null);
}

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

/**
 * Submit a new job.//from   w  ww .  java 2s .  co m
 *
 * @param job request object containing job info element for new job
 * @return The submitted job
 * @throws GenieException For any error
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Submit a job", notes = "Submit a new job to run to genie", response = Job.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Created", response = Job.class),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"),
        @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "Job with ID already exists."),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Precondition Failed"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Response submitJob(@ApiParam(value = "Job object to run.", required = true) final Job job)
        throws GenieException {
    if (job == null) {
        throw new GenieException(HttpURLConnection.HTTP_PRECON_FAILED, "No job entered. Unable to submit.");
    }
    LOG.info("Called to submit job: " + job);

    // get client's host from the context
    String clientHost = this.httpServletRequest.getHeader(FORWARDED_FOR_HEADER);
    if (clientHost != null) {
        clientHost = clientHost.split(",")[0];
    } else {
        clientHost = this.httpServletRequest.getRemoteAddr();
    }

    // set the clientHost, if it is not overridden already
    if (StringUtils.isNotBlank(clientHost)) {
        LOG.debug("called from: " + clientHost);
        job.setClientHost(clientHost);
    }

    final Job createdJob = this.executionService.submitJob(job);
    return Response.created(this.uriInfo.getAbsolutePathBuilder().path(createdJob.getId()).build())
            .entity(createdJob).build();
}

From source file:rapture.util.StringUtil.java

/**
 * Compress the passed in string and base64 encode it
 * @param content/*from ww  w.  j  av a  2s  .  c  o  m*/
 * @return
 */
public static String base64Compress(String content) {
    if (content == null || content.isEmpty()) {
        return content;
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip;
    try {
        gzip = new GZIPOutputStream(out);
        gzip.write(content.getBytes("UTF-8"));
        gzip.close();
    } catch (IOException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Error compressing content",
                e);
    }

    // Now with out, base64
    byte[] encoding = Base64.encodeBase64(out.toByteArray());
    return new String(encoding);
}

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

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)//from w w w .java2  s .  c o m
@ApiOperation(value = "This method returns a list of activities", notes = "Default the latest ten activities will be returned")
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of activities"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") })
//TODO add filter
public HttpResponse getActivities(
        @ApiParam(value = "Before cursor pagination", required = false) @DefaultValue("-1") @QueryParam("before") int before,
        @ApiParam(value = "After cursor pagination", required = false) @DefaultValue("-1") @QueryParam("after") int after,
        @ApiParam(value = "Limit of elements of components", required = false) @DefaultValue("10") @QueryParam("limit") int limit,
        @ApiParam(value = "User authorization token", required = false) @DefaultValue("") @HeaderParam("authorization") String authorizationToken) {

    DALFacade dalFacade = null;
    try {
        if (before != -1 && after != -1) {
            ExceptionHandler.getInstance().throwException(ExceptionLocation.ACTIVITIESERVICE,
                    ErrorCode.WRONG_PARAMETER, "both: before and after parameter not possible");
        }
        int cursor = before != -1 ? before : after;
        Pageable.SortDirection sortDirection = after != -1 ? Pageable.SortDirection.ASC
                : Pageable.SortDirection.DESC;

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(20);
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();

        dalFacade = getDBConnection();
        Gson gson = new Gson();
        ExecutorService executor = Executors.newCachedThreadPool();

        int getObjectCount = 0;
        PaginationResult<Activity> activities;
        List<ActivityEx> activitiesEx = new ArrayList<>();
        Pageable pageInfo = new PageInfo(cursor, limit, "", sortDirection);
        while (activitiesEx.size() < limit && getObjectCount < 5) {
            pageInfo = new PageInfo(cursor, limit, "", sortDirection);
            activities = dalFacade.findActivities(pageInfo);
            getObjectCount++;
            cursor = sortDirection == Pageable.SortDirection.ASC ? cursor + limit : cursor - limit;
            if (cursor < 0) {
                cursor = 0;
            }
            activitiesEx.addAll(
                    getObjectBodies(httpclient, executor, authorizationToken, activities.getElements()));
        }

        executor.shutdown();
        if (activitiesEx.size() > limit) {
            activitiesEx = activitiesEx.subList(0, limit);
        }
        PaginationResult<ActivityEx> activitiesExResult = new PaginationResult<>(pageInfo, activitiesEx);

        HttpResponse response = new HttpResponse(gson.toJson(activitiesExResult.getElements()),
                HttpURLConnection.HTTP_OK);
        Map<String, String> parameter = new HashMap<>();
        parameter.put("limit", String.valueOf(limit));
        response = this.addPaginationToHtppResponse(activitiesExResult, "", parameter, response);

        return response;

    } catch (ActivityTrackerException atException) {
        return new HttpResponse(ExceptionHandler.getInstance().toJSON(atException),
                HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (Exception ex) {
        ActivityTrackerException atException = ExceptionHandler.getInstance().convert(ex,
                ExceptionLocation.ACTIVITIESERVICE, ErrorCode.UNKNOWN, ex.getMessage());
        return new HttpResponse(ExceptionHandler.getInstance().toJSON(atException),
                HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        closeDBConnection(dalFacade);
    }
}

From source file:org.apache.hama.manager.LogView.java

/**
 * download log file./* w  w  w .j a v  a2s .co m*/
 * 
 * @param filPath log file path.
 * @throws Exception
 */
public static void downloadFile(HttpServletResponse response, String filePath)
        throws ServletException, IOException {

    File file = new File(filePath);

    if (!file.exists()) {
        throw new ServletException("File doesn't exists.");
    }

    String headerKey = "Content-Disposition";
    String headerValue = "attachment; filename=\"" + file.getName() + "\"";

    BufferedInputStream in = null;
    BufferedOutputStream out = null;

    try {

        response.setContentType("application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader(headerKey, headerValue);

        in = new BufferedInputStream(new FileInputStream(file));
        out = new BufferedOutputStream(response.getOutputStream());

        byte[] buffer = new byte[4 * 1024];
        int read = -1;

        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }

    } catch (SocketException e) {
        // download cancel..
    } catch (Exception e) {
        response.reset();
        response.sendError(HttpURLConnection.HTTP_INTERNAL_ERROR, e.toString());
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}