Example usage for java.net HttpURLConnection HTTP_BAD_REQUEST

List of usage examples for java.net HttpURLConnection HTTP_BAD_REQUEST

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_BAD_REQUEST.

Prototype

int HTTP_BAD_REQUEST

To view the source code for java.net HttpURLConnection HTTP_BAD_REQUEST.

Click Source Link

Document

HTTP Status-Code 400: Bad Request.

Usage

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

private Response getContentObjectByIdOrName(String contentObjectIdOrSystemName,
        String commaDelimitedProjectionPaths, Output output, String callback, boolean prettyPrint) {

    if (StringUtils.isBlank(contentObjectIdOrSystemName)) {
        logger.warn("No contentObjectId provided");
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }/*from  ww  w . j a  va 2 s  .  co m*/

    Date lastModified = null;
    String contentObjectXmlorJson = retrieveContentObjectXMLorJSONByIdOrSystemName(contentObjectIdOrSystemName,
            commaDelimitedProjectionPaths, output, lastModified, prettyPrint);

    if (StringUtils.isBlank(contentObjectXmlorJson)) {
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }

    try {

        StringBuilder resourceRepresentation = new StringBuilder();

        if (StringUtils.isBlank(callback)) {
            resourceRepresentation.append(contentObjectXmlorJson);
        } else {
            switch (output) {
            case XML: {
                ContentApiUtils.generateXMLP(resourceRepresentation, contentObjectXmlorJson, callback);
                break;
            }
            case JSON:
                ContentApiUtils.generateJSONP(resourceRepresentation, contentObjectXmlorJson, callback);
                break;
            }

        }

        return ContentApiUtils.createResponse(resourceRepresentation, output, callback, lastModified);

    } catch (Exception e) {
        logger.error("ContentObejct id/name " + contentObjectIdOrSystemName, e);
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }

}

From source file:rapture.kernel.DecisionApiImpl.java

@Override
public String getStepCategory(CallingContext context, String stepURI) {
    RaptureURI uri = new RaptureURI(stepURI, Scheme.WORKFLOW);
    Workflow workflow = getWorkflowNotNull(context, stepURI);
    if (uri.getElement() == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, String.format(
                "The Step URI passed in does not contain an 'element' indicating the step, but it requires one: '%s'",
                uri.toString()));//from  ww  w. j a va 2s  .  co m
    }
    Step step = getStep(workflow, uri.getElement());
    if (step == null) {
        throw RaptureExceptionFactory.create(String.format("Error! No step exists for URI %s", stepURI));
    } else if (step.getCategoryOverride() == null || "".equals(step.getCategoryOverride())) {
        return workflow.getCategory();
    } else {
        return step.getCategoryOverride();
    }
}

From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java

/**
 * Remove a member from the application/*from   ww  w.  j a v a  2  s.com*/
 * @param appId applicationId
 * @param memberId memberId
 * @return HttpResponse status if a member is removed
 */
@DELETE
@Path("/data/{appId}/{memberId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "removeMemberFromApp", notes = "delete a member from an app")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Member is removed from app"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Error checking app ID exist"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "No member found"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database error") })
public HttpResponse removeMemberFromApp(
        @ApiParam(value = "Application ID", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Member ID", required = true) @PathParam("memberId") String memberId) {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "DELETE " + "gamification/applications/data/" + appId + "/" + memberId);

    JSONObject objResponse = new JSONObject();
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        if (!applicationAccess.isAppIdExist(conn, appId)) {
            objResponse.put("message", "Cannot remove member from Application. App not found");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        try {
            if (!applicationAccess.isMemberRegistered(conn, memberId)) {
                objResponse.put("message", "Cannot remove member from Application. No member found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            applicationAccess.removeMemberFromApp(conn, memberId, appId);
            objResponse.put("message", memberId + "is removed from " + appId);

            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_5, "" + memberId);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_6, "" + appId);
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

        } catch (SQLException e) {
            e.printStackTrace();
            objResponse.put("message",
                    "Cannot remove member from Application. Database error. " + 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 remove member from Application. Error checking app ID exist " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }

}

From source file:org.eclipse.orion.server.tests.servlets.xfer.TransferTest.java

@Test
public void testImportAndUnzipWithoutOverride() throws CoreException, IOException, SAXException {
    //create a directory to upload to
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    String filePath = "/org.eclipse.e4.webide/static/js/navigate-tree";
    createDirectory(directoryPath + filePath);
    //create a file that is not overwritten
    String fileContents = "This is the file contents";
    createFile(directoryPath + filePath + "/navigate-tree.js", fileContents);
    //start the import
    URL entry = ServerTestsActivator.getContext().getBundle().getEntry("testData/importTest/client.zip");
    File source = new File(FileLocator.toFileURL(entry).getPath());
    long length = source.length();
    InputStream in = new BufferedInputStream(new FileInputStream(source));
    PostMethodWebRequest request = new PostMethodWebRequest(getImportRequestPath(directoryPath), in,
            "application/zip");
    request.setHeaderField("Content-Length", "" + length);
    request.setHeaderField("Content-Type", "application/octet-stream");
    request.setHeaderField("Slug", "client.zip");
    request.setHeaderField("X-Xfer-Options", "no-overwrite");
    setAuthentication(request);/*from w  w w  .j av  a 2  s .c  o  m*/
    WebResponse postResponse = webConversation.getResponse(request);
    //assert the server rejects the override
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, postResponse.getResponseCode());
    //assert the unzip still occurred in the workspace
    assertTrue(checkFileExists(
            directoryPath + "/org.eclipse.e4.webide/static/images/unit_test/add-test-config.png"));
    //assert that imported file was not overwritten
    assertTrue(checkContentEquals(createTempFile("expectedFile", fileContents),
            directoryPath + filePath + "/navigate-tree.js"));
}

From source file:rapture.kernel.DocApiImpl.java

@Override
public DocWriteHandle putDocWithEventContext(CallingContext context, String docUri, String content,
        Map<String, String> extraEventContextMap) {
    boolean mustBeNew = false;

    RaptureURI internalUri = new RaptureURI(docUri, Scheme.DOCUMENT);
    DocumentRepoConfig config = getConfigFromCache(internalUri.getAuthority());

    if (config == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoSuchRepo", internalUri.toAuthString())); //$NON-NLS-1$
    }/*from   w  w w .  j a va 2  s .co  m*/

    DocWriteHandle handle;
    if (internalUri.hasAttribute()) {
        handle = addDocumentAttributeWithHandle(internalUri, content);
    } else {
        if (internalUri.getElement() != null && internalUri.getElement().equals(UserApiImpl.AUTOID)
                && config.getIdGenUri() != null && !config.getIdGenUri().isEmpty()) {
            // update display name with idgen
            String newId = Kernel.getIdGen().nextIds(context, config.getIdGenUri(), 1L);
            String oldPath = internalUri.getDocPath();
            String newPath = (oldPath == null || oldPath.isEmpty()) ? newId : oldPath + "/" + newId;
            log.debug("New path is " + newPath);

            // element will be still #id unless we clear it.
            internalUri = RaptureURI.builder(internalUri).docPath(newPath).element(null).build();
            mustBeNew = true;
            // Now we must replace any #UserApiImpl.AUTOID with this newly
            // generated idgen id
            content = content.replace("#" + UserApiImpl.AUTOID, newId);
        }

        Kernel.getStackContainer().pushStack(context, internalUri.toString());

        int versionNumber = -1;
        if (internalUri.hasVersion()) {
            try {
                versionNumber = Integer.parseInt(internalUri.getVersion());
            } catch (NumberFormatException e) {
                throw RaptureExceptionFactory.create(HttpStatus.SC_BAD_REQUEST,
                        String.format("Bad version specified in uri. version='%s', uri='%s'",
                                internalUri.getVersion(), internalUri));
            }
        }
        handle = saveDocument(context, internalUri, content, mustBeNew, config, versionNumber,
                extraEventContextMap);
        Kernel.getStackContainer().popStack(context);
    }

    return handle;
}

From source file:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java

/**
 * Delete an achievement data with specified ID
 * @param appId applicationId//from w w w  .  j  av a2  s. c  o  m
 * @param achievementId achievementId
 * @return HttpResponse returned as JSON object
 */
@DELETE
@Path("/{appId}/{achievementId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Achievement Delete Success"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Achievements not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"), })
@ApiOperation(value = "deleteAchievement", notes = "Delete an achievement")
public HttpResponse deleteAchievement(@PathParam("appId") String appId,
        @PathParam("achievementId") String achievementId) {

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

    Connection conn = null;
    JSONObject objResponse = new JSONObject();
    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_20, "" + randomLong);

        try {
            if (!achievementAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot delete 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 delete 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);
        }
        if (!achievementAccess.isAchievementIdExist(conn, appId, achievementId)) {
            objResponse.put("message", "Cannot delete achievement. Achievement not found");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        achievementAccess.deleteAchievement(conn, appId, achievementId);

        objResponse.put("message", "Cannot delete achievement. Achievement Deleted");
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_21, "" + randomLong);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_30, "" + name);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_31, "" + appId);
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {

        e.printStackTrace();
        objResponse.put("message", "Cannot delete achievement. Cannot delete Achievement. " + 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.gamificationQuestService.GamificationQuestService.java

/**
 * Delete a quest data with specified ID
 * @param appId applicationId/*w  w  w  . j  av a2 s  . com*/
 * @param questId questId
 * @return HttpResponse with the returnString
 */
@DELETE
@Path("/{appId}/{questId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "quest Delete Success"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "quest not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"), })
@ApiOperation(value = "deleteQuest", notes = "delete a quest")
public HttpResponse deleteQuest(@PathParam("appId") String appId, @PathParam("questId") String questId) {

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

    JSONObject objResponse = new JSONObject();
    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_20, "" + randomLong);

        try {
            if (!questAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot delete quest. 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 delete quest. 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);
        }
        if (!questAccess.isQuestIdExist(conn, appId, questId)) {
            objResponse.put("message",
                    "Cannot delete quest. Failed to delete the quest. Quest ID is not exist!");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        questAccess.deleteQuest(conn, appId, questId);

        objResponse.put("message", "quest Deleted");
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_21, "" + randomLong);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_30, "" + name);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_31, "" + appId);
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {

        e.printStackTrace();
        objResponse.put("message", "Cannot delete quest. Database error. " + 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.gamificationActionService.GamificationActionService.java

/**
 * Get a list of actions from database//from ww  w. java2s .  co m
 * @param appId applicationId
 * @param currentPage current cursor page
 * @param windowSize size of fetched data
 * @param searchPhrase search word
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a list of actions"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getActionList", notes = "Returns a list of actions", response = ActionModel.class, responseContainer = "List")
public HttpResponse getActionList(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Page number for retrieving data") @QueryParam("current") int currentPage,
        @ApiParam(value = "Number of data size") @QueryParam("rowCount") int windowSize,
        @ApiParam(value = "Search phrase parameter") @QueryParam("searchPhrase") String searchPhrase) {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/actions/" + appId);

    List<ActionModel> achs = null;
    Connection conn = null;

    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(this, Event.AGENT_GET_STARTED, "Get Actions");

        try {
            if (!actionAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get actions. 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 get actions. 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);
        }
        int offset = (currentPage - 1) * windowSize;
        int totalNum = actionAccess.getNumberOfActions(conn, appId);

        if (windowSize == -1) {
            offset = 0;
            windowSize = totalNum;
        }

        achs = actionAccess.getActionsWithOffsetAndSearchPhrase(conn, appId, offset, windowSize, searchPhrase);

        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        String actionString = objectMapper.writeValueAsString(achs);
        JSONArray actionArray = (JSONArray) JSONValue.parse(actionString);
        logger.info(actionArray.toJSONString());
        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", actionArray);
        objResponse.put("total", totalNum);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_10,
                "Actions fetched" + " : " + appId + " : " + userAgent);
        L2pLogger.logEvent(this, Event.AGENT_GET_SUCCESS,
                "Actions fetched" + " : " + appId + " : " + userAgent);
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        e.printStackTrace();

        // return HTTP Response on error
        objResponse.put("message", "Cannot get actions. Database error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get actions. JSON processing error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java

/**
 * Add a member to the application//  w  w  w  . j av a 2  s  . co  m
 * @param appId applicationId
 * @param memberId memberId
 * @return HttpResponse status if the member is added
 */
@POST
@Path("/data/{appId}/{memberId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Member is Added"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Error checking app ID exist"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database error") })
@ApiOperation(value = "addMemberToApp", notes = "add a member to an app")
public HttpResponse addMemberToApp(
        @ApiParam(value = "Application ID", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Member ID", required = true) @PathParam("memberId") String memberId) {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "POST " + "gamification/applications/data/" + appId + "/" + memberId);

    JSONObject objResponse = new JSONObject();
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        if (!applicationAccess.isAppIdExist(conn, appId)) {
            objResponse.put("message", "Cannot add member to Application. App not found");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        try {
            applicationAccess.addMemberToApp(conn, appId, memberId);
            objResponse.put("success", memberId + " is added to " + appId);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_3, "" + memberId);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_4, "" + appId);
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
        } catch (SQLException e) {

            e.printStackTrace();
            objResponse.put("message", "Cannot add member to Application. Database error. " + 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 add member to Application. Error checking app ID exist. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }

}

From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Get a badge data with specific ID from database
 * @param appId applicationId//www.  j ava  2s.  c  om
 * @param badgeId badge id
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}/{badgeId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a badges"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Find point for specific App ID and badge ID", notes = "Returns a badge", response = BadgeModel.class, responseContainer = "List", authorizations = @Authorization(value = "api_key"))
public HttpResponse getBadgeWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Badge ID") @PathParam("badgeId") String badgeId) {

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

    BadgeModel badge = null;
    Connection conn = null;

    JSONObject objResponse = new JSONObject();
    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_16, "" + randomLong);

        try {
            if (!badgeAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get badge. 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 get badge. 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);
        }
        badge = badgeAccess.getBadgeWithId(conn, appId, badgeId);
        if (badge == null) {
            objResponse.put("message", "Cannot get badge. Badge model is null.");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        String badgeString = objectMapper.writeValueAsString(badge);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_17, "" + randomLong);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_26, "" + name);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_27, "" + appId);
        return new HttpResponse(badgeString, HttpURLConnection.HTTP_OK);

    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get badge. Cannot process JSON." + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get badge. Database Error. " + 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);
        }
    }
}