Search in sources :

Example 66 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class UserMgmtService method changeRole.

/**
     * Swithches the user role between "defaultRole" and "visitorRole" by the specified user id.
     *
     * @param userId the specified user id
     * @throws ServiceException exception
     * @see User
     */
public void changeRole(final String userId) throws ServiceException {
    final Transaction transaction = userRepository.beginTransaction();
    try {
        final JSONObject oldUser = userRepository.get(userId);
        if (null == oldUser) {
            throw new ServiceException(langPropsService.get("updateFailLabel"));
        }
        final String role = oldUser.optString(User.USER_ROLE);
        if (Role.VISITOR_ROLE.equals(role)) {
            oldUser.put(User.USER_ROLE, Role.DEFAULT_ROLE);
        } else if (Role.DEFAULT_ROLE.equals(role)) {
            oldUser.put(User.USER_ROLE, Role.VISITOR_ROLE);
        }
        userRepository.update(userId, oldUser);
        transaction.commit();
    } catch (final RepositoryException e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        LOGGER.log(Level.ERROR, "Updates a user failed", e);
        throw new ServiceException(e);
    }
}
Also used : Transaction(org.b3log.latke.repository.Transaction) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) RepositoryException(org.b3log.latke.repository.RepositoryException)

Example 67 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class UserQueryService method getUsers.

/**
     * Gets users by the specified request json object.
     *
     * @param requestJSONObject the specified request json object, for example,
     * <pre>
     * {
     *     "paginationCurrentPageNum": 1,
     *     "paginationPageSize": 20,
     *     "paginationWindowSize": 10,
     * }, see {@link Pagination} for more details
     * </pre>
     * @return for example,
     * <pre>
     * {
     *     "pagination": {
     *         "paginationPageCount": 100,
     *         "paginationPageNums": [1, 2, 3, 4, 5]
     *     },
     *     "users": [{
     *         "oId": "",
     *         "userName": "",
     *         "userEmail": "",
     *         "userPassword": "",
     *         "roleName": ""
     *      }, ....]
     * }
     * </pre>
     * @throws ServiceException service exception
     * @see Pagination
     */
public JSONObject getUsers(final JSONObject requestJSONObject) throws ServiceException {
    final JSONObject ret = new JSONObject();
    final int currentPageNum = requestJSONObject.optInt(Pagination.PAGINATION_CURRENT_PAGE_NUM);
    final int pageSize = requestJSONObject.optInt(Pagination.PAGINATION_PAGE_SIZE);
    final int windowSize = requestJSONObject.optInt(Pagination.PAGINATION_WINDOW_SIZE);
    final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize);
    JSONObject result = null;
    try {
        result = userRepository.get(query);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Gets users failed", e);
        throw new ServiceException(e);
    }
    final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT);
    final JSONObject pagination = new JSONObject();
    ret.put(Pagination.PAGINATION, pagination);
    final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
    pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
    pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
    final JSONArray users = result.optJSONArray(Keys.RESULTS);
    ret.put(User.USERS, users);
    return ret;
}
Also used : JSONObject(org.json.JSONObject) Query(org.b3log.latke.repository.Query) ServiceException(org.b3log.latke.service.ServiceException) JSONArray(org.json.JSONArray) RepositoryException(org.b3log.latke.repository.RepositoryException)

Example 68 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class UserQueryService method getUser.

/**
     * Gets a user by the specified user id.
     *
     * @param userId the specified user id
     * @return for example,
     * <pre>
     * {
     *     "user": {
     *         "oId": "",
     *         "userName": "",
     *         "userEmail": "",
     *         "userPassword": ""
     *     }
     * }
     * </pre>, returns {@code null} if not found
     * @throws ServiceException service exception
     */
public JSONObject getUser(final String userId) throws ServiceException {
    final JSONObject ret = new JSONObject();
    JSONObject user = null;
    try {
        user = userRepository.get(userId);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Gets a user failed", e);
        throw new ServiceException(e);
    }
    if (null == user) {
        return null;
    }
    ret.put(User.USER, user);
    return ret;
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) RepositoryException(org.b3log.latke.repository.RepositoryException)

Example 69 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class UserConsole method addUser.

/**
     * Adds a user with the specified request.
     *
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "oId": "", // Generated user id
     *     "msg": ""
     * }
     * </pre>
     * </p>
     *
     * @param request the specified http servlet request, for example,      <pre>
     * {
     *     "userName": "",
     *     "userEmail": "",
     *     "userPassword": "",
     *     "userURL": "", // optional, uses 'servePath' instead if not specified
     *     "userRole": "", // optional, uses {@value org.b3log.latke.model.Role#DEFAULT_ROLE} instead if not specified
     *     "userAvatar": "" // optional
     * }
     * </pre>
     *
     * @param response the specified http servlet response
     * @param context the specified http request context
     * @throws Exception exception
     */
@RequestProcessing(value = "/console/user/", method = HTTPRequestMethod.POST)
public void addUser(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception {
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = new JSONObject();
    renderer.setJSONObject(ret);
    try {
        final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
        if (userQueryService.isAdminLoggedIn(request)) {
            // if the administrator register a new user, treats the new user as a normal user
            // (defaultRole) who could post article
            requestJSONObject.put(User.USER_ROLE, Role.DEFAULT_ROLE);
        } else {
            final JSONObject preference = preferenceQueryService.getPreference();
            if (!preference.optBoolean(Option.ID_C_ALLOW_REGISTER)) {
                ret.put(Keys.STATUS_CODE, false);
                ret.put(Keys.MSG, langPropsService.get("notAllowRegisterLabel"));
                return;
            }
            // if a normal user or a visitor register a new user, treates the new user as a visitor 
            // (visitorRole) who couldn't post article
            requestJSONObject.put(User.USER_ROLE, Role.VISITOR_ROLE);
        }
        final String userId = userMgmtService.addUser(requestJSONObject);
        ret.put(Keys.OBJECT_ID, userId);
        ret.put(Keys.MSG, langPropsService.get("addSuccLabel"));
        ret.put(Keys.STATUS_CODE, true);
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, e.getMessage());
    }
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 70 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class UserConsole method getUser.

/**
     * Gets a user by the specified request.
     *
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "user": {
     *         "oId": "",
     *         "userName": "",
     *         "userEmail": "",
     *         "userPassword": "",
     *         "userAvatar": ""
     *     }
     * }
     * </pre>
     * </p>
     *
     * @param request the specified http servlet request
     * @param response the specified http servlet response
     * @param context the specified http request context
     * @throws Exception exception
     */
@RequestProcessing(value = "/console/user/*", method = HTTPRequestMethod.GET)
public void getUser(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception {
    if (!userQueryService.isAdminLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    try {
        final String requestURI = request.getRequestURI();
        final String userId = requestURI.substring((Latkes.getContextPath() + "/console/user/").length());
        final JSONObject result = userQueryService.getUser(userId);
        if (null == result) {
            renderer.setJSONObject(QueryResults.defaultResult());
            return;
        }
        renderer.setJSONObject(result);
        result.put(Keys.STATUS_CODE, true);
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, langPropsService.get("getFailLabel"));
    }
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Aggregations

ServiceException (org.b3log.latke.service.ServiceException)102 JSONObject (org.json.JSONObject)91 JSONException (org.json.JSONException)45 RepositoryException (org.b3log.latke.repository.RepositoryException)34 Transaction (org.b3log.latke.repository.Transaction)31 RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)23 JSONArray (org.json.JSONArray)17 JSONRenderer (org.b3log.latke.servlet.renderer.JSONRenderer)16 EventException (org.b3log.latke.event.EventException)14 IOException (java.io.IOException)11 ParseException (java.text.ParseException)10 ArrayList (java.util.ArrayList)8 Query (org.b3log.latke.repository.Query)8 Date (java.util.Date)7 AbstractFreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer)6 Template (freemarker.template.Template)3 FreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer)3 ArchiveDate (org.b3log.solo.model.ArchiveDate)3 URL (java.net.URL)2 HashMap (java.util.HashMap)2