Search in sources :

Example 6 with LatkeBeanManager

use of org.b3log.latke.ioc.LatkeBeanManager in project solo by b3log.

the class InitCheckFilter method doFilter.

/**
     * If Solo has not been initialized, so redirects to /init.
     *
     * @param request the specified request
     * @param response the specified response
     * @param chain filter chain
     * @throws IOException io exception
     * @throws ServletException servlet exception
     */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final String requestURI = httpServletRequest.getRequestURI();
    LOGGER.log(Level.TRACE, "Request[URI={0}]", requestURI);
    // If requests Latke Remote APIs, skips this filter 
    if (requestURI.startsWith(Latkes.getContextPath() + "/latke/remote")) {
        chain.doFilter(request, response);
        return;
    }
    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final InitService initService = beanManager.getReference(InitService.class);
    if (initService.isInited()) {
        chain.doFilter(request, response);
        return;
    }
    if ("POST".equalsIgnoreCase(httpServletRequest.getMethod()) && (Latkes.getContextPath() + "/init").equals(requestURI)) {
        // Do initailization
        chain.doFilter(request, response);
        return;
    }
    if (!initReported) {
        LOGGER.log(Level.DEBUG, "Solo has not been initialized, so redirects to /init");
        initReported = true;
    }
    final HTTPRequestContext context = new HTTPRequestContext();
    context.setRequest((HttpServletRequest) request);
    context.setResponse((HttpServletResponse) response);
    request.setAttribute(Keys.HttpRequest.REQUEST_URI, Latkes.getContextPath() + "/init");
    request.setAttribute(Keys.HttpRequest.REQUEST_METHOD, HTTPRequestMethod.GET.name());
    final HttpControl httpControl = new HttpControl(DispatcherServlet.SYS_HANDLER.iterator(), context);
    try {
        httpControl.nextHandler();
    } catch (final Exception e) {
        context.setRenderer(new HTTP500Renderer(e));
    }
    DispatcherServlet.result(context);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HTTPRequestContext(org.b3log.latke.servlet.HTTPRequestContext) HttpControl(org.b3log.latke.servlet.HttpControl) HTTP500Renderer(org.b3log.latke.servlet.renderer.HTTP500Renderer) InitService(org.b3log.solo.service.InitService) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) LatkeBeanManager(org.b3log.latke.ioc.LatkeBeanManager)

Example 7 with LatkeBeanManager

use of org.b3log.latke.ioc.LatkeBeanManager in project solo by b3log.

the class ProcessAuthAdvice method doAdvice.

@Override
public void doAdvice(final HTTPRequestContext context, final Map<String, Object> args) throws RequestProcessAdviceException {
    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class);
    if (!userQueryService.isLoggedIn(context.getRequest(), context.getResponse())) {
        try {
            context.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
        throw new RequestReturnAdviceException(null);
    }
}
Also used : RequestReturnAdviceException(org.b3log.latke.servlet.advice.RequestReturnAdviceException) UserQueryService(org.b3log.solo.service.UserQueryService) IOException(java.io.IOException) LatkeBeanManager(org.b3log.latke.ioc.LatkeBeanManager)

Example 8 with LatkeBeanManager

use of org.b3log.latke.ioc.LatkeBeanManager in project solo by b3log.

the class Skins method fillLangs.

/**
     * Fills the specified data model with the current skink's (WebRoot/skins/${skinName}/lang/lang_xx_XX.properties)
     * and core language (WebRoot/WEB-INF/classes/lang_xx_XX.properties) configurations.
     *
     * @param localeString the specified locale string
     * @param currentSkinDirName the specified current skin directory name
     * @param dataModel the specified data model
     * @throws ServiceException service exception
     */
public static void fillLangs(final String localeString, final String currentSkinDirName, final Map<String, Object> dataModel) throws ServiceException {
    Stopwatchs.start("Fill Skin Langs");
    try {
        final String langName = currentSkinDirName + "." + localeString;
        Map<String, String> langs = LANG_MAP.get(langName);
        if (null == langs) {
            // Collect unused skin languages
            LANG_MAP.clear();
            LOGGER.log(Level.DEBUG, "Loading skin [dirName={0}, locale={1}]", new Object[] { currentSkinDirName, localeString });
            langs = new HashMap<String, String>();
            final String language = Locales.getLanguage(localeString);
            final String country = Locales.getCountry(localeString);
            final ServletContext servletContext = SoloServletListener.getServletContext();
            final InputStream inputStream = servletContext.getResourceAsStream("/skins/" + currentSkinDirName + "/lang/lang_" + language + '_' + country + ".properties");
            final Properties props = new Properties();
            props.load(inputStream);
            final Set<Object> keys = props.keySet();
            for (final Object key : keys) {
                langs.put((String) key, props.getProperty((String) key));
            }
            LANG_MAP.put(langName, langs);
            LOGGER.log(Level.DEBUG, "Loaded skin[dirName={0}, locale={1}, keyCount={2}]", new Object[] { currentSkinDirName, localeString, langs.size() });
        }
        // Fills the current skin's language configurations
        dataModel.putAll(langs);
        // Fills the core language configurations
        final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
        final LangPropsService langPropsService = beanManager.getReference(LangPropsServiceImpl.class);
        dataModel.putAll(langPropsService.getAll(Latkes.getLocale()));
    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "Fills skin langs failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}
Also used : ServiceException(org.b3log.latke.service.ServiceException) InputStream(java.io.InputStream) ServletContext(javax.servlet.ServletContext) IOException(java.io.IOException) Properties(java.util.Properties) LatkeBeanManager(org.b3log.latke.ioc.LatkeBeanManager) LangPropsService(org.b3log.latke.service.LangPropsService)

Example 9 with LatkeBeanManager

use of org.b3log.latke.ioc.LatkeBeanManager in project solo by b3log.

the class PageCommentReplyNotifier method action.

@Override
public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject eventData = event.getData();
    final JSONObject comment = eventData.optJSONObject(Comment.COMMENT);
    final JSONObject page = eventData.optJSONObject(Page.PAGE);
    LOGGER.log(Level.DEBUG, "Processing an event[type={0}, data={1}] in listener[className={2}]", new Object[] { event.getType(), eventData, PageCommentReplyNotifier.class.getName() });
    final String originalCommentId = comment.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID);
    if (Strings.isEmptyOrNull(originalCommentId)) {
        LOGGER.log(Level.DEBUG, "This comment[id={0}] is not a reply", comment.optString(Keys.OBJECT_ID));
        return;
    }
    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final PreferenceQueryService preferenceQueryService = beanManager.getReference(PreferenceQueryService.class);
    final CommentRepository commentRepository = beanManager.getReference(CommentRepositoryImpl.class);
    try {
        final String commentEmail = comment.getString(Comment.COMMENT_EMAIL);
        final JSONObject originalComment = commentRepository.get(originalCommentId);
        final String originalCommentEmail = originalComment.getString(Comment.COMMENT_EMAIL);
        if (originalCommentEmail.equalsIgnoreCase(commentEmail)) {
            return;
        }
        final JSONObject preference = preferenceQueryService.getPreference();
        if (null == preference) {
            throw new EventException("Not found preference");
        }
        final String blogTitle = preference.getString(Option.ID_C_BLOG_TITLE);
        final String adminEmail = preference.getString(Option.ID_C_ADMIN_EMAIL);
        final String commentContent = comment.getString(Comment.COMMENT_CONTENT);
        final String commentSharpURL = comment.getString(Comment.COMMENT_SHARP_URL);
        final Message message = new Message();
        message.setFrom(adminEmail);
        message.addRecipient(originalCommentEmail);
        final JSONObject replyNotificationTemplate = preferenceQueryService.getReplyNotificationTemplate();
        final String mailSubject = replyNotificationTemplate.getString("subject").replace("${blogTitle}", blogTitle);
        message.setSubject(mailSubject);
        final String pageTitle = page.getString(Page.PAGE_TITLE);
        final String pageLink = Latkes.getServePath() + page.getString(Page.PAGE_PERMALINK);
        final String commentName = comment.getString(Comment.COMMENT_NAME);
        final String commentURL = comment.getString(Comment.COMMENT_URL);
        String commenter;
        if (!"http://".equals(commentURL)) {
            commenter = "<a target=\"_blank\" " + "href=\"" + commentURL + "\">" + commentName + "</a>";
        } else {
            commenter = commentName;
        }
        final String mailBody = replyNotificationTemplate.getString("body").replace("${postLink}", pageLink).replace("${postTitle}", pageTitle).replace("${replier}", commenter).replace("${replyURL}", Latkes.getServePath() + commentSharpURL).replace("${replyContent}", commentContent);
        message.setHtmlBody(mailBody);
        LOGGER.log(Level.DEBUG, "Sending a mail[mailSubject={0}, mailBody=[{1}] to [{2}]", new Object[] { mailSubject, mailBody, originalCommentEmail });
        mailService.send(message);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        throw new EventException("Reply notifier error!");
    }
}
Also used : PreferenceQueryService(org.b3log.solo.service.PreferenceQueryService) JSONObject(org.json.JSONObject) Message(org.b3log.latke.mail.MailService.Message) EventException(org.b3log.latke.event.EventException) CommentRepository(org.b3log.solo.repository.CommentRepository) EventException(org.b3log.latke.event.EventException) LatkeBeanManager(org.b3log.latke.ioc.LatkeBeanManager)

Example 10 with LatkeBeanManager

use of org.b3log.latke.ioc.LatkeBeanManager in project solo by b3log.

the class UpdateArticleGoogleBlogSearchPinger method action.

@Override
public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject eventData = event.getData();
    String articleTitle = null;
    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final PreferenceQueryService preferenceQueryService = beanManager.getReference(PreferenceQueryService.class);
    try {
        final JSONObject article = eventData.getJSONObject(Article.ARTICLE);
        articleTitle = article.getString(Article.ARTICLE_TITLE);
        final JSONObject preference = preferenceQueryService.getPreference();
        final String blogTitle = preference.getString(Option.ID_C_BLOG_TITLE);
        if (Latkes.getServePath().contains("localhost")) {
            LOGGER.log(Level.TRACE, "Solo runs on local server, so should not ping " + "Google Blog Search Service for the article[title={0}]", new Object[] { article.getString(Article.ARTICLE_TITLE) });
            return;
        }
        final String articlePermalink = Latkes.getServePath() + article.getString(Article.ARTICLE_PERMALINK);
        final String spec = "http://blogsearch.google.com/ping?name=" + URLEncoder.encode(blogTitle, "UTF-8") + "&url=" + URLEncoder.encode(Latkes.getServePath(), "UTF-8") + "&changesURL=" + URLEncoder.encode(articlePermalink, "UTF-8");
        LOGGER.log(Level.DEBUG, "Request Google Blog Search Service API[{0}] while updateing " + "an article[title=" + articleTitle + "]", spec);
        final HTTPRequest request = new HTTPRequest();
        request.setURL(new URL(spec));
        URL_FETCH_SERVICE.fetchAsync(request);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Ping Google Blog Search Service fail while updating an " + "article[title=" + articleTitle + "]", e);
    }
}
Also used : PreferenceQueryService(org.b3log.solo.service.PreferenceQueryService) HTTPRequest(org.b3log.latke.urlfetch.HTTPRequest) JSONObject(org.json.JSONObject) URL(java.net.URL) EventException(org.b3log.latke.event.EventException) LatkeBeanManager(org.b3log.latke.ioc.LatkeBeanManager)

Aggregations

LatkeBeanManager (org.b3log.latke.ioc.LatkeBeanManager)14 JSONObject (org.json.JSONObject)10 EventException (org.b3log.latke.event.EventException)8 PreferenceQueryService (org.b3log.solo.service.PreferenceQueryService)7 IOException (java.io.IOException)5 HTTPRequest (org.b3log.latke.urlfetch.HTTPRequest)5 MalformedURLException (java.net.MalformedURLException)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 URL (java.net.URL)2 ServletException (javax.servlet.ServletException)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 Message (org.b3log.latke.mail.MailService.Message)2 RepositoryException (org.b3log.latke.repository.RepositoryException)2 ServiceException (org.b3log.latke.service.ServiceException)2 CommentRepository (org.b3log.solo.repository.CommentRepository)2 UserQueryService (org.b3log.solo.service.UserQueryService)2 InputStream (java.io.InputStream)1 Properties (java.util.Properties)1 ServletContext (javax.servlet.ServletContext)1 Cookie (javax.servlet.http.Cookie)1