Search in sources :

Example 61 with JSONRenderer

use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.

the class InitProcessor method initSolo.

/**
     * Initializes Solo.
     *
     * @param context the specified http request context
     * @param request the specified http servlet request, for example,      <pre>
     * {
     *     "userName": "",
     *     "userEmail": "",
     *     "userPassword": ""
     * }
     * </pre>
     *
     * @param response the specified http servlet response
     * @throws Exception exception
     */
@RequestProcessing(value = "/init", method = HTTPRequestMethod.POST)
public void initSolo(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    if (initService.isInited()) {
        response.sendRedirect("/");
        return;
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = QueryResults.defaultResult();
    renderer.setJSONObject(ret);
    try {
        final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
        final String userName = requestJSONObject.optString(User.USER_NAME);
        final String userEmail = requestJSONObject.optString(User.USER_EMAIL);
        final String userPassword = requestJSONObject.optString(User.USER_PASSWORD);
        if (Strings.isEmptyOrNull(userName) || Strings.isEmptyOrNull(userEmail) || Strings.isEmptyOrNull(userPassword) || !Strings.isEmail(userEmail)) {
            ret.put(Keys.MSG, "Init failed, please check your input");
            return;
        }
        if (invalidUserName(userName)) {
            ret.put(Keys.MSG, "Init failed, please check your username (length [1, 20], content {a-z, A-Z, 0-9}, do not contain 'admin' for security reason]");
            return;
        }
        final Locale locale = Locales.getLocale(request);
        requestJSONObject.put(Keys.LOCALE, locale.toString());
        initService.init(requestJSONObject);
        // If initialized, login the admin
        final JSONObject admin = new JSONObject();
        admin.put(User.USER_NAME, userName);
        admin.put(User.USER_EMAIL, userEmail);
        admin.put(User.USER_ROLE, Role.ADMIN_ROLE);
        admin.put(User.USER_PASSWORD, userPassword);
        admin.put(UserExt.USER_AVATAR, Thumbnails.getGravatarURL(userEmail, "128"));
        Sessions.login(request, response, admin);
        ret.put(Keys.STATUS_CODE, true);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        ret.put(Keys.MSG, e.getMessage());
    }
}
Also used : Locale(java.util.Locale) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 62 with JSONRenderer

use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.

the class ChanceProcessor method hasChance.

/**
     * Dose the client has a broadcast chance.
     * 
     * <p>
     * If the request come from a user not administrator, consider it is no broadcast chance.
     * </p>
     * 
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean, // if has a chance, the value will be true
     *     "broadcastChanceExpirationTime": long, // if has a chance, the value will larger then 0L
     * }
     * </pre>
     * </p>
     *
     * @param context the specified http request context
     * @param request the specified http servlet request
     * @param response the specified http servlet response
     * @throws Exception 
     */
@RequestProcessing(value = "/console/plugins/b3log-broadcast/chance", method = HTTPRequestMethod.GET)
public void hasChance(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    if (!userQueryService.isLoggedIn(request, response)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = new JSONObject();
    renderer.setJSONObject(ret);
    if (!userQueryService.isAdminLoggedIn(request)) {
        ret.put(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME, 0L);
        ret.put(Keys.STATUS_CODE, false);
        return;
    }
    try {
        final JSONObject option = optionQueryService.getOptionById(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME);
        if (null == option) {
            ret.put(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME, 0L);
            ret.put(Keys.STATUS_CODE, false);
            return;
        }
        ret.put(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME, option.getLong(Option.OPTION_VALUE));
        ret.put(Keys.STATUS_CODE, true);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Broadcast plugin exception", e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
    }
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) MalformedURLException(java.net.MalformedURLException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 63 with JSONRenderer

use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.

the class ChanceProcessor method submitBroadcast.

/**
     * Submits a broadcast.
     * 
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "msg": "" // optional
     * }
     * </pre>
     * </p>
     *
     * @param context the specified http request context
     * @param request the specified http servlet request, for example,
     * <pre>
     * {
     *     "broadcast": {
     *         "title": "",
     *         "content": "",
     *         "link": "" // optional
     *     }
     * }
     * </pre>
     * @param response the specified http servlet response
     * @throws Exception 
     */
@RequestProcessing(value = "/console/plugins/b3log-broadcast", method = HTTPRequestMethod.POST)
public void submitBroadcast(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    if (!userQueryService.isAdminLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = new JSONObject();
    renderer.setJSONObject(ret);
    try {
        final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
        final JSONObject broadcast = requestJSONObject.getJSONObject("broadcast");
        final JSONObject preference = preferenceQueryService.getPreference();
        final String b3logKey = preference.getString(Option.ID_C_KEY_OF_SOLO);
        final String email = preference.getString(Option.ID_C_ADMIN_EMAIL);
        final String clientName = "B3log Solo";
        final String clientVersion = SoloServletListener.VERSION;
        final String clientTitle = preference.getString(Option.ID_C_BLOG_TITLE);
        final String clientRuntimeEnv = Latkes.getRuntimeEnv().name();
        final JSONObject broadcastRequest = new JSONObject();
        broadcastRequest.put("b3logKey", b3logKey);
        broadcastRequest.put("email", email);
        broadcastRequest.put("broadcast", broadcast);
        broadcastRequest.put("clientRuntimeEnv", clientRuntimeEnv);
        broadcastRequest.put("clientTitle", clientTitle);
        broadcastRequest.put("clientVersion", clientVersion);
        broadcastRequest.put("clientName", clientName);
        broadcastRequest.put("clientHost", Latkes.getServePath());
        final HTTPRequest httpRequest = new HTTPRequest();
        httpRequest.setURL(ADD_BROADCAST_URL);
        httpRequest.setRequestMethod(HTTPRequestMethod.POST);
        httpRequest.setPayload(broadcastRequest.toString().getBytes("UTF-8"));
        @SuppressWarnings("unchecked") final Future<HTTPResponse> future = (Future<HTTPResponse>) urlFetchService.fetchAsync(httpRequest);
        final HTTPResponse result = future.get();
        if (HttpServletResponse.SC_OK == result.getResponseCode()) {
            ret.put(Keys.STATUS_CODE, true);
            optionMgmtService.removeOption(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME);
            LOGGER.info("Submits broadcast successfully");
            return;
        }
        ret.put(Keys.STATUS_CODE, false);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Submits broadcast failed", e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, e.getMessage());
    }
}
Also used : HTTPRequest(org.b3log.latke.urlfetch.HTTPRequest) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) HTTPResponse(org.b3log.latke.urlfetch.HTTPResponse) Future(java.util.concurrent.Future) MalformedURLException(java.net.MalformedURLException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 64 with JSONRenderer

use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.

the class ChanceProcessor method addChance.

/**
     * Adds a broadcast chance to option repository.
     * 
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "msg": "" // optional
     * }
     * </pre>
     * </p>
     *
     * @param context the specified http request context
     * @param request the specified http servlet request
     * @param response the specified http servlet response
     * @throws Exception 
     */
@RequestProcessing(value = "/console/plugins/b3log-broadcast/chance", method = HTTPRequestMethod.POST)
public void addChance(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = new JSONObject();
    renderer.setJSONObject(ret);
    try {
        // TODO: verify b3 key
        final String time = request.getParameter("time");
        if (Strings.isEmptyOrNull(time)) {
            ret.put(Keys.STATUS_CODE, false);
            return;
        }
        final long expirationTime = Long.valueOf(time);
        final JSONObject option = new JSONObject();
        option.put(Keys.OBJECT_ID, Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME);
        option.put(Option.OPTION_VALUE, expirationTime);
        option.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_BROADCAST);
        optionMgmtService.addOrUpdateOption(option);
        ret.put(Keys.STATUS_CODE, true);
    } catch (final Exception e) {
        final String msg = "Broadcast plugin exception";
        LOGGER.log(Level.ERROR, msg, e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, msg);
    }
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) MalformedURLException(java.net.MalformedURLException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 65 with JSONRenderer

use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.

the class ArticleProcessor method getArchivesArticlesByPage.

/**
     * Gets tag articles paged with the specified context.
     *
     * @param context the specified context
     * @param request the specified request
     */
@RequestProcessing(value = "/articles/archives/.+/\\d+", uriPatternsMode = URIPatternMode.REGEX, method = HTTPRequestMethod.GET)
public void getArchivesArticlesByPage(final HTTPRequestContext context, final HttpServletRequest request) {
    final JSONObject jsonObject = new JSONObject();
    final String archiveDateString = getArchivesArticlesPagedArchive(request.getRequestURI());
    final int currentPageNum = getArchivesArticlesPagedCurrentPageNum(request.getRequestURI());
    Stopwatchs.start("Get Archive-Articles Paged[archive=" + archiveDateString + ", pageNum=" + currentPageNum + ']');
    try {
        jsonObject.put(Keys.STATUS_CODE, true);
        final JSONObject preference = preferenceQueryService.getPreference();
        final int pageSize = preference.getInt(Option.ID_C_ARTICLE_LIST_DISPLAY_COUNT);
        final JSONObject archiveQueryResult = archiveDateQueryService.getByArchiveDateString(archiveDateString);
        if (null == archiveQueryResult) {
            throw new Exception("Can not found archive[archiveDate=" + archiveDateString + "]");
        }
        final JSONObject archiveDate = archiveQueryResult.getJSONObject(ArchiveDate.ARCHIVE_DATE);
        final String archiveDateId = archiveDate.getString(Keys.OBJECT_ID);
        final int articleCount = archiveDate.getInt(ArchiveDate.ARCHIVE_DATE_PUBLISHED_ARTICLE_COUNT);
        final int pageCount = (int) Math.ceil((double) articleCount / (double) pageSize);
        final List<JSONObject> articles = articleQueryService.getArticlesByArchiveDate(archiveDateId, currentPageNum, pageSize);
        final boolean hasMultipleUsers = userQueryService.hasMultipleUsers();
        if (hasMultipleUsers) {
            filler.setArticlesExProperties(request, articles, preference);
        } else if (!articles.isEmpty()) {
            final JSONObject author = articleQueryService.getAuthor(articles.get(0));
            filler.setArticlesExProperties(request, articles, author, preference);
        }
        Collections.sort(articles, Comparators.ARTICLE_CREATE_DATE_COMPARATOR);
        final JSONObject result = new JSONObject();
        final JSONObject pagination = new JSONObject();
        pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
        result.put(Pagination.PAGINATION, pagination);
        result.put(Article.ARTICLES, articles);
        jsonObject.put(Keys.RESULTS, result);
    } catch (final Exception e) {
        jsonObject.put(Keys.STATUS_CODE, false);
        LOGGER.log(Level.ERROR, "Gets article paged failed", e);
    } finally {
        Stopwatchs.end();
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    renderer.setJSONObject(jsonObject);
}
Also used : JSONObject(org.json.JSONObject) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) EventException(org.b3log.latke.event.EventException) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Aggregations

RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)67 JSONRenderer (org.b3log.latke.servlet.renderer.JSONRenderer)67 JSONObject (org.json.JSONObject)67 ServiceException (org.b3log.latke.service.ServiceException)38 IOException (java.io.IOException)12 JSONException (org.json.JSONException)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 MalformedURLException (java.net.MalformedURLException)4 EventException (org.b3log.latke.event.EventException)4 JSONArray (org.json.JSONArray)4 RepositoryException (org.b3log.latke.repository.RepositoryException)3 Template (freemarker.template.Template)2 StringWriter (java.io.StringWriter)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 ServletException (javax.servlet.ServletException)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HttpSession (javax.servlet.http.HttpSession)2 HTTPRequest (org.b3log.latke.urlfetch.HTTPRequest)2