Search in sources :

Example 96 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.

the class IndexProcessor method showKillBrowser.

/**
     * Shows kill browser page with the specified context.
     *
     * @param context the specified context
     * @param request the specified HTTP servlet request
     * @param response the specified HTTP servlet response
     */
@RequestProcessing(value = "/kill-browser", method = HTTPRequestMethod.GET)
public void showKillBrowser(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) {
    final AbstractFreeMarkerRenderer renderer = new KillBrowserRenderer();
    context.setRenderer(renderer);
    final Map<String, Object> dataModel = renderer.getDataModel();
    try {
        final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request));
        dataModel.putAll(langs);
        final JSONObject preference = preferenceQueryService.getPreference();
        filler.fillBlogHeader(request, response, dataModel, preference);
        filler.fillBlogFooter(request, dataModel, preference);
        Keys.fillServer(dataModel);
        Keys.fillRuntime(dataModel);
        filler.fillMinified(dataModel);
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (final IOException ex) {
            LOGGER.error(ex.getMessage());
        }
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONObject(org.json.JSONObject) IOException(java.io.IOException) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 97 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.

the class IndexProcessor method showIndex.

/**
     * Shows index with the specified context.
     *
     * @param context the specified context
     * @param request the specified HTTP servlet request
     * @param response the specified HTTP servlet response
     */
@RequestProcessing(value = { "/\\d*", "" }, uriPatternsMode = URIPatternMode.REGEX, method = HTTPRequestMethod.GET)
public void showIndex(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) {
    final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("index.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    final String requestURI = request.getRequestURI();
    try {
        final int currentPageNum = getCurrentPageNum(requestURI);
        final JSONObject preference = preferenceQueryService.getPreference();
        // https://github.com/b3log/solo/issues/12060
        String specifiedSkin = Skins.getSkinDirName(request);
        if (null != specifiedSkin) {
            if ("default".equals(specifiedSkin)) {
                specifiedSkin = preference.optString(Option.ID_C_SKIN_DIR_NAME);
            }
        } else {
            specifiedSkin = preference.optString(Option.ID_C_SKIN_DIR_NAME);
        }
        Templates.MAIN_CFG.setServletContextForTemplateLoading(SoloServletListener.getServletContext(), "/skins/" + specifiedSkin);
        request.setAttribute(Keys.TEMAPLTE_DIR_NAME, specifiedSkin);
        Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);
        filler.fillIndexArticles(request, dataModel, currentPageNum, preference);
        filler.fillSide(request, dataModel, preference);
        filler.fillBlogHeader(request, response, dataModel, preference);
        filler.fillBlogFooter(request, dataModel, preference);
        dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, currentPageNum);
        final int previousPageNum = currentPageNum > 1 ? currentPageNum - 1 : 0;
        dataModel.put(Pagination.PAGINATION_PREVIOUS_PAGE_NUM, previousPageNum);
        final Integer pageCount = (Integer) dataModel.get(Pagination.PAGINATION_PAGE_COUNT);
        final int nextPageNum = currentPageNum + 1 > pageCount ? pageCount : currentPageNum + 1;
        dataModel.put(Pagination.PAGINATION_NEXT_PAGE_NUM, nextPageNum);
        dataModel.put(Common.PATH, "");
        statisticMgmtService.incBlogViewCount(request, response);
        // https://github.com/b3log/solo/issues/12060
        final Cookie cookie = new Cookie(Skin.SKIN, specifiedSkin);
        cookie.setPath("/");
        response.addCookie(cookie);
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (final IOException ex) {
            LOGGER.error(ex.getMessage());
        }
    }
}
Also used : Cookie(javax.servlet.http.Cookie) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONObject(org.json.JSONObject) FreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) IOException(java.io.IOException) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 98 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing 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 99 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing 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 100 with RequestProcessing

use of org.b3log.latke.servlet.annotation.RequestProcessing 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)

Aggregations

RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)104 JSONObject (org.json.JSONObject)94 JSONRenderer (org.b3log.latke.servlet.renderer.JSONRenderer)67 ServiceException (org.b3log.latke.service.ServiceException)51 IOException (java.io.IOException)35 AbstractFreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 JSONException (org.json.JSONException)12 JSONArray (org.json.JSONArray)11 HttpServletResponse (javax.servlet.http.HttpServletResponse)9 EventException (org.b3log.latke.event.EventException)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 TextHTMLRenderer (org.b3log.latke.servlet.renderer.TextHTMLRenderer)7 FreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer)7 ConsoleRenderer (org.b3log.solo.processor.renderer.ConsoleRenderer)7 Date (java.util.Date)6 ExecutionException (java.util.concurrent.ExecutionException)6 ArrayList (java.util.ArrayList)5 MalformedURLException (java.net.MalformedURLException)4 HttpSession (javax.servlet.http.HttpSession)4