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:i5.las2peer.services.userManagement.UserManagement.java

/**
 * /*w w w.java2s . c o  m*/
 * getUser
 * 
 * 
 * @return HttpResponse
 * 
 */
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "userFound"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internal"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "userNotFound") })
@ApiOperation(value = "getUser", notes = "")
public HttpResponse getUser() {
    // userFound
    boolean userFound_condition = true;
    if (userFound_condition) {
        JSONObject user = new JSONObject();
        HttpResponse userFound = new HttpResponse(user.toJSONString(), HttpURLConnection.HTTP_OK);
        return userFound;
    }
    // internal
    boolean internal_condition = true;
    if (internal_condition) {
        String error = "Some String";
        HttpResponse internal = new HttpResponse(error, HttpURLConnection.HTTP_INTERNAL_ERROR);
        return internal;
    }
    // userNotFound
    boolean userNotFound_condition = true;
    if (userNotFound_condition) {
        String error = "Some String";
        HttpResponse userNotFound = new HttpResponse(error, HttpURLConnection.HTTP_NOT_FOUND);
        return userNotFound;
    }
    return null;
}

From source file:com.stackmob.example.Stripe.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    int responseCode = 0;
    String responseBody = "";

    LoggerService logger = serviceProvider.getLoggerService(Stripe.class);

    // AMOUNT should be a whole integer - ie 100 is 1 US dollar
    String amount = request.getParams().get("amount");

    //  CURRENCY - should be one of the supported currencies, please check STRIPE documentation.
    String currency = "usd";

    //  TOKEN - is returned when you submit the credit card information to stripe using
    // the Stripe JavaScript library.
    String token = request.getParams().get("token");

    // DESCRIPTION - the description of the transaction
    String description = request.getParams().get("description");

    if (token == null || token.isEmpty()) {
        logger.error("Token is missing");
    }//w w  w . ja  va2 s  .co m

    if (amount == null || amount.isEmpty()) {
        logger.error("Amount is missing");
    }

    StringBuilder body = new StringBuilder();

    body.append("amount=");
    body.append(amount);
    body.append("&currency=");
    body.append(currency);
    body.append("&card=");
    body.append(token);
    body.append("&description=");
    body.append(description);

    String url = "https://api.stripe.com/v1/charges";
    String pair = secretKey;

    //Base 64 Encode the secretKey
    String encodedString = new String("utf-8");
    try {
        byte[] b = Base64.encodeBase64(pair.getBytes("utf-8"));
        encodedString = new String(b);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        HashMap<String, String> errParams = new HashMap<String, String>();
        errParams.put("error", "the auth header threw an exception: " + e.getMessage());
        return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request
    }

    Header accept = new Header("Accept-Charset", "utf-8");
    Header auth = new Header("Authorization", "Basic " + encodedString);
    Header content = new Header("Content-Type", "application/x-www-form-urlencoded");

    Set<Header> set = new HashSet();
    set.add(accept);
    set.add(content);
    set.add(auth);

    try {
        HttpService http = serviceProvider.getHttpService();
        PostRequest req = new PostRequest(url, set, body.toString());

        HttpResponse resp = http.post(req);
        responseCode = resp.getCode();
        responseBody = resp.getBody();
    } catch (TimeoutException e) {
        logger.error(e.getMessage(), e);
        responseCode = HttpURLConnection.HTTP_BAD_GATEWAY;
        responseBody = e.getMessage();
    } catch (AccessDeniedException e) {
        logger.error(e.getMessage(), e);
        responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
        responseBody = e.getMessage();
    } catch (MalformedURLException e) {
        logger.error(e.getMessage(), e);
        responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
        responseBody = e.getMessage();
    } catch (ServiceNotActivatedException e) {
        logger.error(e.getMessage(), e);
        responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
        responseBody = e.getMessage();
    }

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("response_body", responseBody);

    return new ResponseToProcess(responseCode, map);
}

From source file:rapture.ftp.common.SFTPConnection.java

@Override
public boolean connectAndLogin() {
    if (isLocal()) {
        log.info("In test mode - not connecting");
        return true;
    }/*  w  w w . java  2s .  com*/

    if (!config.isUseSFTP()) {
        return super.connectAndLogin();
    } else {
        if (!isConnected()) {
            return FTPService.runWithRetry(
                    "Could not login to " + config.getAddress() + " as " + config.getLoginId(), this, false,
                    new FTPAction<Boolean>() {
                        @SuppressWarnings("synthetic-access")
                        @Override
                        public Boolean run(int attemptNum) throws IOException {
                            try {
                                java.util.Properties properties = new java.util.Properties();
                                session = jsch.getSession(config.getLoginId(), config.getAddress(),
                                        config.getPort());
                                properties.put("StrictHostKeyChecking", "no");
                                properties.put("kex",
                                        "diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256");
                                session.setConfig(properties);
                                if (!StringUtils.isEmpty(config.getPassword())) {
                                    session.setPassword(config.getPassword());
                                } else {
                                    jsch.addIdentity(config.getAddress(), config.getPrivateKey().getBytes(),
                                            null, null);
                                }
                                session.connect();
                                channel = (ChannelSftp) session.openChannel("sftp");
                                channel.setInputStream(System.in);
                                channel.setOutputStream(System.out);
                                channel.connect();
                                return true;
                            } catch (Exception e) {
                                if (e.getCause() instanceof UnknownHostException) {
                                    throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                            "Unknown host " + config.getAddress());
                                }
                                log.error("Unable to establish secure FTP connection " + config.getLoginId()
                                        + "@" + config.getAddress() + ":" + config.getPort());
                                throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                        "Unable to establish secure FTP connection to " + config.getAddress(),
                                        e);
                            }
                        }
                    });
        }
    }
    return false;
}

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

/**
 * Get cluster configuration from unique id.
 *
 * @param id id for the cluster//from  w  w  w .j  a  va  2  s. co  m
 * @return the cluster
 * @throws GenieException For any error
 */
@GET
@Path("/{id}")
@ApiOperation(value = "Find a cluster by id", notes = "Get the cluster by id if it exists", response = Cluster.class)
@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 Cluster getCluster(
        @ApiParam(value = "Id of the cluster to get.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called with id: " + id);
    return this.clusterConfigService.getCluster(id);
}

From source file:rapture.common.client.BaseHttpApi.java

public BaseHttpApi(String url, String keyholePart) {
    this.keyholeUrl = keyholePart;
    this.stateManager = new URLStateManager(url);
    currentUrl = stateManager.getURL();/*  w  ww.ja  va 2  s .c  om*/
    if (currentUrl == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                "No available Rapture end points");
    }
    setup();
}

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

/**
 * Get Command configuration for given id.
 *
 * @param id unique id for command configuration
 * @return The command configuration/* w ww . j  a v a  2 s. c om*/
 * @throws GenieException For any error
 */
@GET
@Path("/{id}")
@ApiOperation(value = "Find a command by id", notes = "Get the command by id if it exists", response = Command.class)
@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 Command getCommand(
        @ApiParam(value = "Id of the command to get.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called to get command with id " + id);
    return this.commandConfigService.getCommand(id);
}

From source file:rapture.util.StringUtil.java

public static String base64Decompress(String content) {
    byte[] decodedBytes = Base64.decodeBase64(content.getBytes());
    ByteArrayInputStream is = new ByteArrayInputStream(decodedBytes);
    try {/*from w  w w  . jav a2s  .c o m*/
        GZIPInputStream gzip = new GZIPInputStream(is);
        BufferedReader bf = new BufferedReader(new InputStreamReader(gzip, "UTF-8"));
        StringBuilder ret = new StringBuilder();
        String line;
        while ((line = bf.readLine()) != null) {
            ret.append(line);
            ret.append("\n");
        }
        return ret.toString().substring(0, ret.length() - 1);
    } catch (IOException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                "Error decompressing content", e);
    }
}

From source file:com.leafhut.open_source.VerifyReceipt.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {

    // Set up logger
    LoggerService logger = serviceProvider.getLoggerService(VerifyReceipt.class);

    String startMessage = "Processing receipt...";
    logger.info(startMessage);/*from   w  w w . ja v  a 2  s. c  o  m*/

    HttpService http;
    try {
        http = serviceProvider.getHttpService();
    } catch (ServiceNotActivatedException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        logger.error(exceptionLogMessage);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    if (http == null) {

        String failureReason = "HTTP Service is null.";
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    // Fetch parameters sent via POST
    String encodedReceipt = null;
    try {

        JSONObject jsonObj = new JSONObject(request.getBody());

        if (!jsonObj.isNull(kReceiptParameter)) {

            encodedReceipt = jsonObj.getString(kReceiptParameter);
        }

    } catch (JSONException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "Invalid or missing parameter.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    // Create JSON representation of receipt
    JSONObject validationBodyJSON = new JSONObject();
    try {
        validationBodyJSON.put(kReceiptValidationKey, encodedReceipt);
    } catch (JSONException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "Could not create JSON for receipt validation server.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }
    String validationBodyString = validationBodyJSON.toString();

    // create the HTTP request
    PostRequest req;
    try {
        req = new PostRequest(validationServerURL, validationBodyString);
    } catch (MalformedURLException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "Invalid URL for receipt validation server.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailingURLStringKey, validationServerURL);
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    // Send the request. This method call will not return until the server returns.
    // note that this method may throw AccessDeniedException if the URL is whitelisted or rate limited,
    // or TimeoutException if the server took too long to return
    HttpResponse response;
    try {
        response = http.post(req);
    } catch (AccessDeniedException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "HTTP request refused by StackMob custom code environment.";
        String suggestionMessage = "Check rate limiting, whitelisting, and blacklisting in the StackMob custom code environment.";
        logger.error(exceptionLogMessage);
        logger.error(failureReason);
        logger.debug(suggestionMessage);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_FORBIDDEN);
        errorMap.put(kErrorDescriptionKey, kErrorCode403Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);
        errorMap.put(kRecoverySuggestionKey, suggestionMessage);

        return new ResponseToProcess(HttpURLConnection.HTTP_FORBIDDEN, errorMap);

    } catch (TimeoutException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "HTTP request to receipt validation server timed out.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_GATEWAY_TIMEOUT);
        errorMap.put(kErrorDescriptionKey, kErrorCode504Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_GATEWAY_TIMEOUT, errorMap);
    }

    if (response == null) {

        String failureReason = "Response from receipt validation server is null.";
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    // Parse the response from the server
    JSONObject serverResponseJSON;

    try {
        serverResponseJSON = new JSONObject(response.getBody());
    } catch (JSONException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "Could not parse JSON response from receipt validation server.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    int validationStatus = -1;
    try {
        if (!serverResponseJSON.isNull(kValidationResponseStatusKey)) {

            validationStatus = serverResponseJSON.getInt(kValidationResponseStatusKey);
        }
    } catch (JSONException e) {

        String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage();
        String failureReason = "Missing or invalid status code from receipt validation server.";

        logger.error(exceptionLogMessage);
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR);
        errorMap.put(kErrorDescriptionKey, kErrorCode500Description);
        errorMap.put(kExceptionNameKey, e.getClass().getName());
        errorMap.put(kExceptionMessageKey, e.getMessage());
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap);
    }

    // Take action based on receipt validation
    if (validationStatus == 0) {

        //
        // Receipt is valid
        //
        // This is where you could take any server-side actions that were required to fulfill the purchase.
        // See the StackMob custom code documentation for more details:
        // https://developer.preview.stackmob.com/tutorials/custom%20code
        //

    } else {

        //
        // Receipt is invalid
        //

        String failureReason = "Invalid receipt.";
        logger.error(failureReason);

        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_PAYMENT_REQUIRED);
        errorMap.put(kErrorDescriptionKey, kErrorCode402Description);
        errorMap.put(kFailureReasonKey, failureReason);

        return new ResponseToProcess(HttpURLConnection.HTTP_PAYMENT_REQUIRED, errorMap);
    }

    // Send human-readable server response to calling client
    // Note: The parsing below is brittle (depends on there never being more than two layers of JSON).
    //       This probably should be generalized using recursion.
    Map<String, Object> returnMap = new HashMap<String, Object>();

    Iterator<?> keys = serverResponseJSON.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        try {
            if (serverResponseJSON.get(key) instanceof JSONObject) {

                JSONObject nestedJSON = (JSONObject) serverResponseJSON.get(key);

                Iterator<?> nestedKeys = nestedJSON.keys();
                while (nestedKeys.hasNext()) {

                    String nestedKey = (String) nestedKeys.next();
                    Object nestedValue = nestedJSON.get(nestedKey);
                    returnMap.put(nestedKey, nestedValue.toString());

                }
            } else {

                Object value = serverResponseJSON.get(key);
                returnMap.put(key, value.toString());
            }

        } catch (JSONException e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }
    }

    String finishMessage = "Receipt is valid.";
    logger.info(finishMessage);
    return new ResponseToProcess(HttpURLConnection.HTTP_OK, returnMap);
}

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

/**
 * //from ww w. ja  v a 2 s. c o m
 * createData
 * 
 * 
 * @return HttpResponse
 * 
 */
@POST
@Path("/data/{name}")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "responseCreateData") })
@ApiOperation(value = "createData", notes = "")
public HttpResponse createData(@PathParam("name") String name) {
    Connection conn = null;
    try {

        conn = dbm.getConnection();
        PreparedStatement stmt = conn
                .prepareStatement("INSERT INTO gamificationCAE.todolist (name) VALUES (?)");
        stmt.setString(1, name);

        stmt.executeUpdate();

        return new HttpResponse(name + " is added!", 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:com.netflix.genie.server.resources.ApplicationConfigResource.java

/**
 * Get Application for given id./*from   w w  w.  j  ava 2  s  .  c o m*/
 *
 * @param id unique id for application configuration
 * @return The application configuration
 * @throws GenieException For any error
 */
@GET
@Path("/{id}")
@ApiOperation(value = "Find an application by id", notes = "Get the application by id if it exists", response = Application.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK", response = Application.class),
        @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 Application getApplication(
        @ApiParam(value = "Id of the application to get.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called to get Application for id " + id);
    return this.applicationConfigService.getApplication(id);
}