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.todolist.Todolist.java

/**
 * // ww w.  j a v  a2s. c o m
 * deleteData
 * 
 * 
 * @return HttpResponse
 * 
 */
@DELETE
@Path("/data/{id}")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "responseDeleteData") })
@ApiOperation(value = "deleteData", notes = "")
public HttpResponse deleteData(@PathParam("id") Integer id) {
    Connection conn = null;
    try {

        conn = dbm.getConnection();
        PreparedStatement stmt = conn.prepareStatement("DELETE FROM gamificationCAE.todolist WHERE id = ?");
        stmt.setInt(1, id);
        stmt.executeUpdate();
        stmt = conn.prepareStatement("ALTER TABLE todolist AUTO_INCREMENT = 1;");
        stmt.executeUpdate();
        return new HttpResponse("data number " + id + " is deleted!", 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:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java

/**
 * Post a new achievement/*from  w w w  .  j a  v  a2s  . c o m*/
 * @param appId applicationId
 * @param formData form data
 * @param contentType content type
 * @return HttpResponse returned as JSON object
 */
@POST
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Achievement upload success ( (achievementid) )\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (achievementid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the achievement. Achievement ID already exist!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Achievement ID cannot be null!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (achievementid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (achievementid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Achievement upload success ( (achievementid) )}") })
@ApiOperation(value = "createNewAchievement", notes = "A method to store a new achievement with details (achievement ID, achievement name, achievement description, achievement point value, achievement point id, achievement badge id")
public HttpResponse createNewAchievement(
        @ApiParam(value = "Application ID to store a new achievement", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ApiParam(value = "Achievement detail in multiple/form-data type", required = true) @ContentParam byte[] formData) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/achievements/" + appId);
    long randomLong = new Random().nextLong(); //To be able to match 

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();
    String achievementid = null;
    String achievementname = null;
    String achievementdesc = null;
    int achievementpointvalue = 0;
    String achievementbadgeid = null;

    boolean achievementnotifcheck = false;
    String achievementnotifmessage = null;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();

        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_14, "" + randomLong);

        try {
            if (!achievementAccess.isAppIdExist(conn, appId)) {
                logger.info("App not found >> ");
                objResponse.put("message", "Cannot create achievement. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));

                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            objResponse.put("message",
                    "Cannot create achievement. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType);
        FormDataPart partAchievementID = parts.get("achievementid");
        if (partAchievementID != null) {
            achievementid = partAchievementID.getContent();

            if (achievementAccess.isAchievementIdExist(conn, appId, achievementid)) {
                // Achievement id already exist
                objResponse.put("message",
                        "Cannot create achievement. Failed to add the achievement. achievement ID already exist!");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
            FormDataPart partAchievementName = parts.get("achievementname");
            if (partAchievementName != null) {
                achievementname = partAchievementName.getContent();
            }
            FormDataPart partAchievementDesc = parts.get("achievementdesc");
            if (partAchievementDesc != null) {
                // optional description text input form element
                achievementdesc = partAchievementDesc.getContent();
            }
            FormDataPart partAchievementPV = parts.get("achievementpointvalue");
            if (partAchievementPV != null) {
                // optional description text input form element
                achievementpointvalue = Integer.parseInt(partAchievementPV.getContent());
            }

            FormDataPart partAchievementBID = parts.get("achievementbadgeid");
            System.out.println("BADGE In Ach : " + partAchievementBID);
            System.out.println("BADGE In Ach : " + partAchievementBID.getContent());
            if (partAchievementBID != null) {
                // optional description text input form element
                achievementbadgeid = partAchievementBID.getContent();
            }
            if (achievementbadgeid.equals("")) {
                achievementbadgeid = null;
            }

            FormDataPart partNotificationCheck = parts.get("achievementnotificationcheck");
            if (partNotificationCheck != null) {
                // checkbox is checked
                achievementnotifcheck = true;

            } else {
                achievementnotifcheck = false;
            }

            FormDataPart partNotificationMsg = parts.get("achievementnotificationmessage");
            if (partNotificationMsg != null) {
                achievementnotifmessage = partNotificationMsg.getContent();
            } else {
                achievementnotifmessage = "";
            }
            AchievementModel achievement = new AchievementModel(achievementid, achievementname, achievementdesc,
                    achievementpointvalue, achievementbadgeid, achievementnotifcheck, achievementnotifmessage);

            try {
                achievementAccess.addNewAchievement(conn, appId, achievement);
                objResponse.put("message", "Achievement upload success (" + achievementid + ")");
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId);

                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED);

            } catch (SQLException e) {
                e.printStackTrace();
                objResponse.put("message",
                        "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            objResponse.put("message", "Cannot create achievement. Achievement ID cannot be null!");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }

    } catch (MalformedStreamException e) {
        // the stream failed to follow required syntax
        objResponse.put("message",
                "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    } catch (IOException e) {
        // a read or write error occurred
        objResponse.put("message",
                "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (NullPointerException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:nl.ru.cmbi.vase.web.rest.JobRestResource.java

@MethodMapping(value = "/status/{jobid}", httpMethod = HttpMethod.GET, produces = RestMimeTypes.TEXT_PLAIN)
public String status(String jobid) {

    if (Config.isXmlOnly() || !Config.hsspPdbCacheEnabled()) {

        log.warn("rest/status was requested, but not enabled");

        // hssp job submission is not allowed if hssp is turned off
        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_NOT_FOUND);
    }/*from ww w.ja v  a  2  s  .c  om*/

    try {
        URL url = new URL(hsspRestURL + "/status/pdb_file/hssp_stockholm/" + jobid + "/");

        StringWriter writer = new StringWriter();
        IOUtils.copy(url.openStream(), writer);
        writer.close();

        JSONObject output = new JSONObject(writer.toString());

        return output.getString("status");

    } catch (Exception e) {

        log.error(e.getMessage(), e);
        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:i5.las2peer.services.gamificationActionService.GamificationActionService.java

/**
 * Post a new action//from ww  w . j a v a 2  s  . c  o m
 * @param appId applicationId
 * @param formData form data
 * @param contentType content type
 * @return HttpResponse returned as JSON object
 */
@POST
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Action upload success ( (actionid) )\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (actionid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the action. Action ID already exist!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Action ID cannot be null!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (actionid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (actionid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Action upload success ( (actionid) )}") })
@ApiOperation(value = "createNewAction", notes = "A method to store a new action with details (action ID, action name, action description,action point value")
public HttpResponse createNewAction(
        @ApiParam(value = "Application ID to store a new action", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ApiParam(value = "Action detail in multiple/form-data type", required = true) @ContentParam byte[] formData) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/actions/" + appId);
    long randomLong = new Random().nextLong(); //To be able to match 

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();

    String actionid = null;
    String actionname = null;
    String actiondesc = null;
    int actionpointvalue = 0;

    boolean actionnotifcheck = false;
    String actionnotifmessage = null;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_14, "" + randomLong);

        try {
            if (!actionAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot create action. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            objResponse.put("message",
                    "Cannot create action. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType);
        FormDataPart partID = parts.get("actionid");
        if (partID != null) {
            actionid = partID.getContent();

            if (actionAccess.isActionIdExist(conn, appId, actionid)) {
                objResponse.put("message",
                        "Cannot create action. Failed to add the action. action ID already exist!");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
            FormDataPart partName = parts.get("actionname");
            if (partName != null) {
                actionname = partName.getContent();
            }
            FormDataPart partDesc = parts.get("actiondesc");
            if (partDesc != null) {
                // optional description text input form element
                actiondesc = partDesc.getContent();
            }
            FormDataPart partPV = parts.get("actionpointvalue");
            if (partPV != null) {
                // optional description text input form element
                actionpointvalue = Integer.parseInt(partPV.getContent());
            }
            FormDataPart partNotificationCheck = parts.get("actionnotificationcheck");
            if (partNotificationCheck != null) {
                // checkbox is checked
                actionnotifcheck = true;
            } else {
                actionnotifcheck = false;
            }
            FormDataPart partNotificationMsg = parts.get("actionnotificationmessage");
            if (partNotificationMsg != null) {
                actionnotifmessage = partNotificationMsg.getContent();
            } else {
                actionnotifmessage = "";
            }
            ActionModel action = new ActionModel(actionid, actionname, actiondesc, actionpointvalue,
                    actionnotifcheck, actionnotifmessage);

            try {
                actionAccess.addNewAction(conn, appId, action);
                objResponse.put("message", "Action upload success (" + actionid + ")");
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId);

                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED);

            } catch (SQLException e) {
                e.printStackTrace();
                objResponse.put("message",
                        "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            objResponse.put("message", "Cannot create action. Action ID cannot be null!");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

        }

    } catch (MalformedStreamException e) {
        // the stream failed to follow required syntax
        objResponse.put("message",
                "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    } catch (IOException e) {
        // a read or write error occurred
        objResponse.put("message",
                "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (NullPointerException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:i5.las2peer.services.gamificationGamifierService.GamificationGamifierService.java

/**
 * Get action data from database//  ww  w.j ava2 s  .c o  m
 * @param appId applicationId
 * @return HttpResponse Returned as JSON object
 */
@GET
@Path("/actions/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Fetch the actions"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
public HttpResponse getActions(@ApiParam(value = "Application ID") @PathParam("appId") String appId) {
    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    String memberId = name;
    //      try {      
    //            if(!initializeDBConnection()){
    //            logger.info("Cannot connect to database >> ");
    //            objResponse.put("message", "Cannot connect to database");
    //            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
    //            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    //         }

    // RMI call with parameters
    try {
        Object result = this.invokeServiceMethod(
                "i5.las2peer.services.gamificationActionService.GamificationActionService@0.1", "getActionsRMI",
                new Serializable[] { appId });
        if (result != null) {
            L2pLogger.logEvent(Event.RMI_SUCCESSFUL, "Get Actions RMI success");
            return new HttpResponse((String) result, HttpURLConnection.HTTP_OK);
        }
        L2pLogger.logEvent(Event.RMI_FAILED, "Get Actions RMI failed");
        objResponse.put("message", "Cannot find actions");
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (AgentNotKnownException | L2pServiceException | L2pSecurityException | InterruptedException
            | TimeoutException e) {
        e.printStackTrace();
        L2pLogger.logEvent(Event.RMI_FAILED, "Get Actions RMI failed. " + e.getMessage());
        objResponse.put("message", "Cannot find Actions. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    }

    //      } catch (SQLException e) {
    //         e.printStackTrace();
    //         objResponse.put("message", "DB Error. " + e.getMessage());
    //         L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
    //         return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    //
    //      }
}

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

@Test
public void testServerErrorGetTTL() throws IOException {
    try {/*from  w  w w  . j  a v a 2  s  . c om*/
        streamClient.getTTL(StringUtils.EMPTY);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getStatusCode());
    }
}

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Returns an INTERNAL_ERROR response
 */
protected Response internalError() {
    return status(HttpURLConnection.HTTP_INTERNAL_ERROR);
}

From source file:i5.las2peer.services.gamificationLevelService.GamificationLevelService.java

/**
 * Post a new level//from w w w .  j  a v a  2 s.co  m
 * @param appId applicationId
 * @param formData form data
 * @param contentType content type
 * @return HttpResponse with the returnString
 */
@POST
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Level upload success ( (levelnum) )\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (levelnum)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the level. levelnum already exist!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Level number cannot be null!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (levelnum)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (levelnum)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Level upload success ( (levelnum) )}") })
@ApiOperation(value = "createLevel", notes = "A method to store a new level with details (Level number, level name, level point value, level point id)")
public HttpResponse createLevel(
        @ApiParam(value = "Application ID to store a new level", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ApiParam(value = "Level detail in multiple/form-data type", required = true) @ContentParam byte[] formData) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/levels/" + appId);
    long randomLong = new Random().nextLong(); //To be able to match

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();
    int levelnum = 0;
    String levelname = null;
    int levelpointvalue = 0;

    boolean levelnotifcheck = false;
    String levelnotifmessage = null;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_14, "" + randomLong);

        try {
            if (!levelAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot create level. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            objResponse.put("message",
                    "Cannot create level. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType);
        FormDataPart partNum = parts.get("levelnum");
        if (partNum != null) {
            levelnum = Integer.parseInt(partNum.getContent());
            if (levelAccess.isLevelNumExist(conn, appId, levelnum)) {
                // level id already exist
                objResponse.put("message",
                        "Cannot create level. Failed to add the level. levelnum already exist!");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
            FormDataPart partName = parts.get("levelname");
            if (partName != null) {
                levelname = partName.getContent();
            }

            FormDataPart partPV = parts.get("levelpointvalue");
            if (partPV != null) {
                // optional description text input form element
                levelpointvalue = Integer.parseInt(partPV.getContent());
            }
            FormDataPart partNotificationCheck = parts.get("levelnotificationcheck");
            if (partNotificationCheck != null) {
                // checkbox is checked
                levelnotifcheck = true;

            } else {
                levelnotifcheck = false;
            }
            FormDataPart partNotificationMsg = parts.get("levelnotificationmessage");
            if (partNotificationMsg != null) {
                levelnotifmessage = partNotificationMsg.getContent();
            } else {
                levelnotifmessage = "";
            }
            LevelModel model = new LevelModel(levelnum, levelname, levelpointvalue, levelnotifcheck,
                    levelnotifmessage);

            try {
                levelAccess.addNewLevel(conn, appId, model);
                objResponse.put("message", "Level upload success (" + levelnum + ")");
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId);
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED);

            } catch (SQLException e) {
                e.printStackTrace();
                objResponse.put("message",
                        "Cannot create level. Failed to upload " + levelnum + ". " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            objResponse.put("message", "Cannot create level. Level number cannot be null!");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

        }

    } catch (MalformedStreamException e) {
        // the stream failed to follow required syntax
        objResponse.put("message", "Cannot create level. Failed to upload. " + levelnum + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    } catch (IOException e) {
        // a read or write error occurred
        objResponse.put("message", "Cannot create level. Failed to upload " + levelnum + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot create level. Failed to upload " + levelnum + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (NullPointerException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot create level. Failed to upload " + levelnum + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

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

/**
 * Get Applications based on user parameters.
 *
 * @param name       name for configuration (optional)
 * @param userName   The user who created the application (optional)
 * @param statuses   The statuses of the applications (optional)
 * @param tags       The set of tags you want the command for.
 * @param page       The page to start one (optional)
 * @param limit      the max number of results to return per page (optional)
 * @param descending Whether results returned in descending or ascending order (optional)
 * @param orderBys   The fields to order the results by (optional)
 * @return All applications matching the criteria
 * @throws GenieException For any error/*from  w ww . j  a  v a  2 s  .  com*/
 */
@GET
@ApiOperation(value = "Find applications", notes = "Find applications by the submitted criteria.", response = Application.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "If status is invalid."),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public List<Application> getApplications(
        @ApiParam(value = "Name of the application.") @QueryParam("name") final String name,
        @ApiParam(value = "User who created the application.") @QueryParam("userName") final String userName,
        @ApiParam(value = "The status of the applications to get.", allowableValues = "ACTIVE, DEPRECATED, INACTIVE") @QueryParam("status") final Set<String> statuses,
        @ApiParam(value = "Tags for the cluster.") @QueryParam("tag") final Set<String> tags,
        @ApiParam(value = "The page to start on.") @QueryParam("page") @DefaultValue("0") final int page,
        @ApiParam(value = "Max number of results per page.") @QueryParam("limit") @DefaultValue("1024") final int limit,
        @ApiParam(value = "Whether results should be sorted in descending or ascending order. Defaults to descending") @QueryParam("descending") @DefaultValue("true") final boolean descending,
        @ApiParam(value = "The fields to order the results by. Must not be collection fields. Default is updated.") @QueryParam("orderBy") final Set<String> orderBys)
        throws GenieException {
    LOG.info("Called [name | userName | status | tags | page | limit | descending | orderBys]");
    LOG.info(name + " | " + userName + " | " + statuses + " | " + tags + " | " + page + " | " + limit + " | "
            + descending + " | " + orderBys);
    Set<ApplicationStatus> enumStatuses = null;
    if (!statuses.isEmpty()) {
        enumStatuses = EnumSet.noneOf(ApplicationStatus.class);
        for (final String status : statuses) {
            if (StringUtils.isNotBlank(status)) {
                enumStatuses.add(ApplicationStatus.parse(status));
            }
        }
    }
    return this.applicationConfigService.getApplications(name, userName, enumStatuses, tags, page, limit,
            descending, orderBys);
}