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:rapture.common.connection.ConnectionInfoConfigurer.java

protected void checkFieldPresent(String fieldName, String fieldValue) {
    if (StringUtils.isBlank(fieldValue)) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                fieldName + " can not be empty");
    }//w  w w .  j  a v a 2 s .co  m
}

From source file:rapture.repo.mongodb.MongoDbDataStore.java

@Override
public boolean delete(List<String> keys) {
    Document inClause = new Document($IN, keys);
    Document query = new Document(KEY, inClause);
    try {// w w  w  . j a v a 2  s  .co  m
        Document result = getCollection().findOneAndDelete(query);
        if ((result != null) && needsFolderHandling) {
            for (String key : keys) {
                dirRepo.dropFileEntry(key);
            }
        }
        return result != null;
    } catch (MongoException me) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, new ExceptionToString(me));
    }

}

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

/**
 * Get job status for give job id.//from  ww w . j a v a 2 s .com
 *
 * @param id id for job to look up
 * @return The status of the job
 * @throws GenieException For any error
 */
@GET
@Path("/{id}/status")
@ApiOperation(value = "Get the status of the job ", notes = "Get the status of job whose id is sent", response = String.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 ObjectNode getJobStatus(
        @ApiParam(value = "Id of the job.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called for job id:" + id);
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode node = mapper.createObjectNode();
    node.put("status", this.jobService.getJobStatus(id).toString());
    return node;
}

From source file:rapture.blob.file.FileBlobStore.java

@Override
public InputStream getBlob(CallingContext context, RaptureURI blobUri) {
    File f = FileRepoUtils.makeGenericFile(parentDir, blobUri.getDocPath() + Parser.COLON_CHAR);
    try {// ww  w.j  av a  2  s. c o  m
        if (f.exists()) {
            return new FileInputStream(f);
        } else {
            return null;
        }
    } catch (IOException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                "Error reading blob from file", e);
    }
}

From source file:i5.las2peer.services.servicePackage.TemplateService.java

/**
 * Example method that shows how to retrieve a user email address from a database 
 * and return an HTTP response including a JSON object.
 * //from w w w.j a v a  2  s  . c  o  m
 * WARNING: THIS METHOD IS ONLY FOR DEMONSTRATIONAL PURPOSES!!! 
 * IT WILL REQUIRE RESPECTIVE DATABASE TABLES IN THE BACKEND, WHICH DON'T EXIST IN THE TEMPLATE.
 * 
 */
@GET
@Path("/userEmail/{username}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "User Email"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "User not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Server Error") })
@ApiOperation(value = "Email Address Administration", notes = "Example method that retrieves a user email address from a database."
        + " WARNING: THIS METHOD IS ONLY FOR DEMONSTRATIONAL PURPOSES!!! "
        + "IT WILL REQUIRE RESPECTIVE DATABASE TABLES IN THE BACKEND, WHICH DON'T EXIST IN THE TEMPLATE.")
public HttpResponse getUserEmail(@PathParam("username") String username) {
    String result = "";
    Connection conn = null;
    PreparedStatement stmnt = null;
    ResultSet rs = null;
    try {

        // get connection from connection pool
        conn = dbm.getConnection();

        // prepare statement
        stmnt = conn.prepareStatement("SELECT email FROM users WHERE username = ?;");
        stmnt.setString(1, username);

        // retrieve result set
        rs = stmnt.executeQuery();

        // process result set
        if (rs.next()) {
            result = rs.getString(1);

            // setup resulting JSON Object
            JSONObject ro = new JSONObject();
            ro.put("email", result);

            // return HTTP Response on success
            return new HttpResponse(ro.toString(), HttpURLConnection.HTTP_OK);
        } else {
            result = "No result for username " + username;

            // return HTTP Response on error
            return new HttpResponse(result, HttpURLConnection.HTTP_NOT_FOUND);
        }
    } catch (Exception e) {
        // return HTTP Response on error
        return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        // free resources
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());

                // return HTTP Response on error
                return new HttpResponse("Internal error: " + e.getMessage(),
                        HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        }
        if (stmnt != null) {
            try {
                stmnt.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());

                // return HTTP Response on error
                return new HttpResponse("Internal error: " + e.getMessage(),
                        HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());

                // return HTTP Response on error
                return new HttpResponse("Internal error: " + e.getMessage(),
                        HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        }
    }
}

From source file:rapture.repo.file.FileDataStore.java

@Override
public void put(String k, String v) {
    // A key is a file name, the value is the contents
    if (createSymLink) {
        int index = k.indexOf("#");
        if (index > -1) {
            createSymLink(k.substring(0, index), k.substring(index + 1));
            return;
        }//  w w  w . j  a va2  s. c  o  m
    }

    File f = FileRepoUtils.makeGenericFile(parentDir, convertKeyToPathWithExtension(k));
    try {
        FileUtils.writeStringToFile(f, v);
    } catch (IOException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Error writing to file", e);
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitTagTest.java

@Test
public void testTagFailed() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project/folder metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());

        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitTagUri = gitSection.getString(GitConstants.KEY_TAG);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        // tag HEAD with 'tag'
        JSONObject tag = tag(gitTagUri, "tag", Constants.HEAD);
        assertEquals("tag", tag.getString(ProtocolConstants.KEY_NAME));
        new URI(tag.getString(ProtocolConstants.KEY_LOCATION));

        // tag HEAD with 'tag' again (TagHandler) - should fail
        request = getPostGitTagRequest(gitTagUri, "tag", Constants.HEAD);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, response.getResponseCode());

        // tag HEAD with 'tag' again (CommitHandler) - should fail
        request = getPutGitCommitRequest(gitHeadUri, "tag");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, response.getResponseCode());

        // modify
        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "test.txt change");

        // add//from  ww  w  .  ja  va  2s .c  om
        JSONObject folder1 = getChild(folder, "folder");
        JSONObject folderTxt = getChild(folder1, "folder.txt");
        addFile(folderTxt);

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // tag next commit with 'tag' again (TagHandler) - should fail
        request = getPostGitTagRequest(gitTagUri, "tag", Constants.HEAD);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, response.getResponseCode());
        JSONObject result = new JSONObject(response.getText());
        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, result.getInt("HttpCode"));
        assertEquals("Error", result.getString("Severity"));
        assertEquals("An error occured when tagging.", result.getString("Message"));
        assertTrue(result.toString(), result.getString("DetailedMessage").endsWith("already exists"));

        // tag HEAD with 'tag' again (CommitHandler) - should fail
        request = getPutGitCommitRequest(gitHeadUri, "tag");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, response.getResponseCode());
        result = new JSONObject(response.getText());
        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, result.getInt("HttpCode"));
        assertEquals("Error", result.getString("Severity"));
        assertEquals("An error occured when tagging.", result.getString("Message"));
        assertTrue(result.toString(), result.getString("DetailedMessage").endsWith("already exists"));
    }
}

From source file:org.betaconceptframework.astroboa.resourceapi.resource.SecurityResource.java

private Response encryptInternal(String requestContent, Output output, String callback) {

    try {//from  w  w  w .  j  a va  2s.com

        if (StringUtils.isBlank(requestContent)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        checkUserIsAuthorizedToUseEncryptionUtility();

        Map<String, Object> userData = ContentApiUtils.parse(requestContent);

        String propertyPath = (String) userData.get("fullPropertyPath");

        if (StringUtils.isBlank(propertyPath)) {
            logger.error(
                    "No property path found. Request {} does not contain field {} or its value is blank. User info {}",
                    new Object[] { requestContent, "fullPropertyPath", astroboaClient.getInfo() });

            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        String password = (String) userData.get("password");

        if (StringUtils.isBlank(password)) {
            logger.error(
                    "No value for password found. Request {} does not contain field {} or its value is blank. User info {}",
                    new Object[] { requestContent, "password", astroboaClient.getInfo() });

            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        DefinitionService definitionService = astroboaClient.getDefinitionService();

        CmsDefinition definition = definitionService.getCmsDefinition(propertyPath,
                ResourceRepresentationType.DEFINITION_INSTANCE, false);

        if (definition == null) {
            logger.error("No definition found for property {}. Request {} - User info {}",
                    new Object[] { propertyPath, requestContent, astroboaClient.getInfo() });

            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        if (!(definition instanceof StringPropertyDefinition)
                || !((StringPropertyDefinition) definition).isPasswordType()) {
            logger.error("Property {}'s type  is not password type. Request {} - User info {}",
                    new Object[] { propertyPath, requestContent, astroboaClient.getInfo() });

            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        String encryptedPassword = StringEscapeUtils
                .escapeJava(((StringPropertyDefinition) definition).getPasswordEncryptor().encrypt(password));

        StringBuilder encryptedPasswordBuidler = new StringBuilder();

        switch (output) {
        case XML: {

            encryptedPassword = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><encryptedPassword>"
                    + encryptedPassword + "</encryptedPassword>";

            if (StringUtils.isBlank(callback)) {
                encryptedPasswordBuidler.append(encryptedPassword);
            } else {
                ContentApiUtils.generateXMLP(encryptedPasswordBuidler, encryptedPassword, callback);
            }
            break;
        }
        case JSON:

            encryptedPassword = "{\"encryptedPassword\" : \"" + encryptedPassword + "\"}";
            if (StringUtils.isBlank(callback)) {
                encryptedPasswordBuidler.append(encryptedPassword);
            } else {
                ContentApiUtils.generateJSONP(encryptedPasswordBuidler, encryptedPassword, callback);
            }
            break;
        }

        return ContentApiUtils.createResponse(encryptedPasswordBuidler, output, callback, null);

    } catch (WebApplicationException wae) {
        throw wae;
    } catch (Exception e) {
        logger.error(
                "Encrytpion failed. Request " + requestContent + " - User info " + astroboaClient.getInfo(), e);
        throw new WebApplicationException(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private double getAvail(int code) {
    // There are too many options to list everything that is
    // successful. So, instead we are going to call out the
    // things that should be considered failure, everything else
    // is OK./*w  ww.j av a 2s.co  m*/
    switch (code) {
    case HttpURLConnection.HTTP_BAD_REQUEST:
    case HttpURLConnection.HTTP_FORBIDDEN:
    case HttpURLConnection.HTTP_NOT_FOUND:
    case HttpURLConnection.HTTP_BAD_METHOD:
    case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
    case HttpURLConnection.HTTP_CONFLICT:
    case HttpURLConnection.HTTP_PRECON_FAILED:
    case HttpURLConnection.HTTP_ENTITY_TOO_LARGE:
    case HttpURLConnection.HTTP_REQ_TOO_LONG:
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
    case HttpURLConnection.HTTP_UNAVAILABLE:
    case HttpURLConnection.HTTP_VERSION:
    case HttpURLConnection.HTTP_BAD_GATEWAY:
    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
        return Metric.AVAIL_DOWN;
    default:
    }

    if (hasCredentials()) {
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            return Metric.AVAIL_DOWN;
        }
    }

    return Metric.AVAIL_UP;
}

From source file:rapture.repo.VersionedRepo.java

@Override
public DocumentWithMeta addDocument(String key, String value, String user, String comment, boolean mustBeNew) {
    String context = IDGenerator.getUUID();
    LockHandle lockHandle = lockHandler.acquireLock(context, DEFAULT_STAGE, 5, 5);
    if (lockHandle != null) {
        try {/*ww  w  .j a v a2  s  .  c  om*/
            // Create a new stage to be consistent
            createStage(DEFAULT_STAGE);
            addToStage(DEFAULT_STAGE, key, value, mustBeNew);
            commitStage(DEFAULT_STAGE, user, comment);

            cacheKeyStore.put(key, value);
        } finally {
            lockHandler.releaseLock(context, DEFAULT_STAGE, lockHandle);
        }
    } else {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                "Could not get lock for write");
    }
    return null; // Deprecated repository so don't do anything special here.
}