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:i5.las2peer.services.gamificationLevelService.GamificationLevelService.java

/**
 * Get a list of levels from database/*from   w w  w .j  av a  2s  . c  o 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 levels"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getLevelList", notes = "Returns a list of levels", response = LevelModel.class, responseContainer = "List")
public HttpResponse getLevelList(@ApiParam(value = "Application ID to return") @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/levels/" + appId);

    List<LevelModel> model = 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 Levels");

        try {
            if (!levelAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get levels. 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 levels. 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;

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

        int totalNum = levelAccess.getNumberOfLevels(conn, appId);

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

        model = levelAccess.getLevelsWithOffsetAndSearchPhrase(conn, appId, offset, windowSize, searchPhrase);
        String modelString = objectMapper.writeValueAsString(model);
        JSONArray modelArray = (JSONArray) JSONValue.parse(modelString);
        logger.info(modelArray.toJSONString());
        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", modelArray);
        objResponse.put("total", totalNum);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_30, "Levels fetched : " + appId + " : " + userAgent);
        L2pLogger.logEvent(this, Event.AGENT_GET_SUCCESS, "Levels 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 levels. 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 levels. JSON processing 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:org.eclipse.orion.server.tests.servlets.git.GitCloneTest.java

@Test
public void testGetEmptyPath() throws Exception {
    // see bug 369909
    String requestURI = SERVER_LOCATION + GIT_SERVLET_LOCATION + Clone.RESOURCE + "/";
    WebRequest request = getGetRequest(requestURI);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode());
}

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

/**
 * Get a list of achievements from database
 * @param appId applicationId/*from w w  w  .j av  a 2 s.c  om*/
 * @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 achievements"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getAchievementList", notes = "Returns a list of achievements", response = AchievementModel.class, responseContainer = "List")
public HttpResponse getAchievementList(
        @ApiParam(value = "Application ID to return") @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/achievements/" + appId);

    List<AchievementModel> 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();

        try {
            if (!achievementAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get achievements. 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 achievements. 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 = achievementAccess.getNumberOfAchievements(conn, appId);

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

        achs = achievementAccess.getAchievementsWithOffsetAndSearchPhrase(conn, appId, offset, windowSize,
                searchPhrase);

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

        String achievementString = objectMapper.writeValueAsString(achs);
        JSONArray achievementArray = (JSONArray) JSONValue.parse(achievementString);
        logger.info(achievementArray.toJSONString());
        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", achievementArray);
        objResponse.put("total", totalNum);
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get achievements. Database error. " + e.getMessage());
        // return HTTP Response on error
        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 achievements. 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.gamificationBadgeService.GamificationBadgeService.java

/**
 * Delete a badge data with specified ID
 * @param appId application id/*from  www  . ja v  a2  s .c o  m*/
 * @param badgeId badge id
 * @return HttpResponse returned as JSON object
 */
@DELETE
@Path("/{appId}/{badgeId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Badge Delete Success"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Badges not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"), })
@ApiOperation(value = "", notes = "delete a badge")
public HttpResponse deleteBadge(@PathParam("appId") String appId, @PathParam("badgeId") String badgeId) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "DELETE " + "gamification/badges/" + appId + "/" + badgeId);
    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 (!badgeAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot delete 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 delete 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);
        }
        if (!badgeAccess.isBadgeIdExist(conn, appId, badgeId)) {
            logger.info("Badge not found >> ");
            objResponse.put("message", "Cannot delete badge. Badge not found");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        badgeAccess.deleteBadge(conn, appId, badgeId);
        if (!LocalFileManager.deleteFile(LocalFileManager.getBasedir() + "/" + appId + "/" + badgeId)) {

            logger.info("Delete File Failed >> ");
            objResponse.put("message", "Cannot delete badge. Delete File Failed");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

        }
        objResponse.put("message", "File 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 badge. Cannot delete file. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
    }

}

From source file:i5.las2peer.services.gamificationQuestService.GamificationQuestService.java

/**
 * Get a list of quests from database//w  w  w  .j a  v a 2s  .c om
 * @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 quests"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getQuestList", notes = "Returns a list of quests", response = QuestModel.class, responseContainer = "List")
public HttpResponse getQuestList(@ApiParam(value = "Application ID to return") @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/quests/" + appId);

    List<QuestModel> qs = 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 Levels");

        try {
            if (!questAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get quests. 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 quests. 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 = questAccess.getNumberOfQuests(conn, appId);

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

        qs = questAccess.getQuestsWithOffsetAndSearchPhrase(conn, appId, offset, windowSize, searchPhrase);

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

        String questString = objectMapper.writeValueAsString(qs);
        JSONArray questArray = (JSONArray) JSONValue.parse(questString);
        //logger.info(questArray.toJSONString());

        for (int i = 0; i < qs.size(); i++) {
            JSONArray actionArray = listPairtoJSONArray(qs.get(i).getActionIds());

            JSONObject questObject = (JSONObject) questArray.get(i);

            questObject.replace("actionIds", actionArray);

            questArray.set(i, questObject);
        }

        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", questArray);
        objResponse.put("total", totalNum);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_37,
                "Quests fetched" + " : " + appId + " : " + userAgent);
        L2pLogger.logEvent(this, Event.AGENT_GET_SUCCESS, "Quests 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 quests. 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 quests. JSON process error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (IOException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get quests. IO Exception. " + 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.gamificationApplicationService.GamificationApplicationService.java

/**
 * Validate member and add to the database as the new member if he/she is not registered yet
 * @return HttpResponse status if validation success
 *//*from   w ww . j  a  v a 2  s. com*/
@POST
@Path("/validation")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "memberLoginValidation", notes = "Simple function to validate a member login.")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Member is registered"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "User data error to be retrieved"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "User data error to be retrieved. Not JSON object") })
public HttpResponse memberLoginValidation() {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/applications/validation");

    JSONObject objResponse = new JSONObject();

    MemberModel member;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    // take username as default name
    String name = userAgent.getLoginName();
    System.out.println("User name : " + name);
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    // try to fetch firstname/lastname from user data received from OpenID
    Serializable userData = userAgent.getUserData();

    if (userData != null) {
        Object jsonUserData = JSONValue.parse(userData.toString());
        if (jsonUserData instanceof JSONObject) {
            JSONObject obj = (JSONObject) jsonUserData;
            Object firstnameObj = obj.get("given_name");
            Object lastnameObj = obj.get("family_name");
            Object emailObj = obj.get("email");
            String firstname, lastname, email;
            if (firstnameObj != null) {
                firstname = ((String) firstnameObj);
            } else {
                firstname = "";
            }

            if (lastnameObj != null) {
                lastname = ((String) lastnameObj);
            } else {
                lastname = "";
            }

            if (emailObj != null) {
                email = ((String) emailObj);
            } else {
                email = "";
            }

            member = new MemberModel(name, firstname, lastname, email);
            //logger.info(member.getId()+" "+member.getFullName()+" "+member.getEmail());
            try {
                conn = dbm.getConnection();
                if (!applicationAccess.isMemberRegistered(conn, member.getId())) {
                    applicationAccess.registerMember(conn, member);
                    objResponse.put("message", "Welcome " + member.getId() + "!");
                    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_7, "" + member.getId());

                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
                }
            } catch (SQLException e) {
                e.printStackTrace();
                objResponse.put("message", "Cannot validate member login. 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);
                }
            }
        } else {
            //logger.warning("Parsing user data failed! Got '" + jsonUserData.getClass().getName() + " instead of "+ JSONObject.class.getName() + " expected!");
            objResponse.put("message",
                    "Cannot validate member login. User data error to be retrieved. Not JSON object.");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        objResponse.put("message", "Member already registered");
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_8, "" + member.getId());

        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
    } else {
        objResponse.put("message", "Cannot validate member login. User data error to be retrieved.");
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    }

}

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

@PUT
@Path("/{contentObjectIdOrName: " + CmsConstants.UUID_OR_SYSTEM_NAME_REG_EXP_FOR_RESTEASY + "}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response putContentObjectByIdOrName(@PathParam("contentObjectIdOrName") String contentObjectIdOrName,
        @QueryParam("updateLastModificationTime") String updateLastModificationTime, String requestContent) {

    if (StringUtils.isBlank(contentObjectIdOrName)) {
        logger.warn("Use HTTP PUT to save object {} but no id or system name was provided ", requestContent);
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }//from  w  w  w  .j ava2 s  . c  o m

    long start = System.currentTimeMillis();

    Response response = saveContentObjectByIdOrName(contentObjectIdOrName, requestContent, HttpMethod.PUT,
            ContentApiUtils.shouldUpdateLastModificationTime(updateLastModificationTime));

    logger.debug(" PUT ContentObject {} in {}", contentObjectIdOrName,
            DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start));

    return response;

}

From source file:rapture.kernel.DocApiImpl.java

private DocWriteHandle addDocumentAttributeWithHandle(RaptureURI docUri, String value) {
    Repository repository = getRepoFromCache(docUri.getAuthority());

    if (!docUri.hasAttribute() || docUri.getAttributeKey() == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Invalid arguments supplied");
    }/*from  w ww .ja v a2 s.  c  om*/

    DocumentAttribute attribute = DocumentAttributeFactory.create(docUri.getAttributeName());
    attribute.setKey(docUri.toString());
    attribute.setValue(value);

    if (repository == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoSuchRepo", docUri.toAuthString())); //$NON-NLS-1$
    }
    repository.setDocAttribute(docUri, attribute);

    DocWriteHandle handle = new DocWriteHandle();
    handle.setDocumentURI(docUri.toString());
    handle.setIsSuccess(true);
    return handle;
}

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

@DELETE
@Path("/{contentObjectIdOrName: " + CmsConstants.UUID_OR_SYSTEM_NAME_REG_EXP_FOR_RESTEASY + "}")
public Response deleteContentObjectByIdOrName(
        @PathParam("contentObjectIdOrName") String contentObjectIdOrName) {

    if (StringUtils.isBlank(contentObjectIdOrName)) {
        logger.warn("No id or system name was provided. Delete request cannot proceed");
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }//from   w w  w  . j av  a 2 s . co  m

    try {
        boolean objectDeleted = astroboaClient.getContentService().deleteContentObject(contentObjectIdOrName);

        return ContentApiUtils.createResponseForHTTPDelete(objectDeleted, contentObjectIdOrName);
    } catch (CmsUnauthorizedAccessException e) {
        throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED);
    } catch (Exception e) {
        logger.error("", e);
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }
}

From source file:rapture.kernel.DocApiImpl.java

@Override
public Map<String, Boolean> setDocAttributes(CallingContext context, String attributeUri, List<String> keys,
        List<String> values) {
    if (keys.size() != values.size()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "Cannot bulk add multiple attributes since the size of the list of keys is not equal to the size of the list of values");
    }// w w  w.  j  a  v  a  2s .  c  om
    Map<String, Boolean> ret = new HashMap<String, Boolean>();
    for (int i = 0; i < keys.size(); i++) {
        String key = keys.get(i);
        String interimUri = attributeUri + "/" + key;
        try {
            String value = values.get(i);
            // go back out to wrapper in ordere to verify entitlement
            // See RAP-3715
            Boolean success = Kernel.getDoc().setDocAttribute(context, interimUri, value);
            ret.put(key, success);
        } catch (RaptureException e) {
            log.error("setDocAttributes failed with error: " + e.getMessage());
            ret.put(key, false);
        }
    }
    return ret;
}