Example usage for org.apache.commons.lang StringUtils substringAfter

List of usage examples for org.apache.commons.lang StringUtils substringAfter

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringAfter.

Prototype

public static String substringAfter(String str, String separator) 

Source Link

Document

Gets the substring after the first occurrence of a separator.

Usage

From source file:org.apache.sling.query.mock.ResourceMock.java

@Override
public Resource getChild(String relPath) {
    if (StringUtils.contains(relPath, '/')) {
        String firstPart = StringUtils.substringBefore(relPath, "/");
        String rest = StringUtils.substringAfter(relPath, "/");
        if (children.containsKey(firstPart)) {
            return children.get(firstPart).getChild(rest);
        }/*from   w w w.  j a va2 s  . c o  m*/
    } else if (children.containsKey(relPath)) {
        return children.get(relPath);
    }

    return null;
}

From source file:org.apache.sling.superimposing.impl.SuperimposingManagerImpl.java

/**
 * Find all existing superimposing registrations using all query defined in service configuration.
 * @param resolver Resource resolver/*from ww w .  j  a  v a  2 s.  c om*/
 * @return All superimposing registrations
 */
@SuppressWarnings("unchecked")
private List<Resource> findSuperimposings(ResourceResolver resolver) {
    List<Resource> allResources = new ArrayList<Resource>();
    for (String queryString : this.findAllQueries) {
        if (!StringUtils.contains(queryString, "|")) {
            throw new IllegalArgumentException(
                    "Query string does not contain query syntax seperated by '|': " + queryString);
        }
        String queryLanguage = StringUtils.substringBefore(queryString, "|");
        String query = StringUtils.substringAfter(queryString, "|");
        allResources.addAll(IteratorUtils.toList(resolver.findResources(query, queryLanguage)));
    }
    return allResources;
}

From source file:org.apache.usergrid.chop.webapp.elasticsearch.Util.java

/**
 * Converts a string to map. String should have this format: {2=b, 1=a}.
 */// www .j a v  a2 s.  c  om
public static Map<String, String> getMap(Map<String, Object> json, String key) {

    HashMap<String, String> map = new HashMap<String, String>();
    String str = getString(json, key);

    if (StringUtils.isEmpty(str) || !str.startsWith("{") || !str.endsWith("}") || str.equals("{}")) {
        return map;
    }
    String values[] = StringUtils.substringBetween(str, "{", "}").split(",");

    for (String s : values) {
        map.put(StringUtils.substringBefore(s, "=").trim(), StringUtils.substringAfter(s, "=").trim());
    }
    return map;
}

From source file:org.apdplat.platform.util.Struts2Utils.java

public static void render(final String contentType, final String content, final String... headers) {
    try {//from w  w  w. j av  a2 s  .c om
        //?headers?
        String encoding = ENCODING_DEFAULT;
        boolean noCache = NOCACHE_DEFAULT;
        for (String header : headers) {
            String headerName = StringUtils.substringBefore(header, ":");
            String headerValue = StringUtils.substringAfter(header, ":");

            if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) {
                encoding = headerValue;
            } else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) {
                noCache = Boolean.parseBoolean(headerValue);
            } else {
                throw new IllegalArgumentException(headerName + "??header");
            }
        }

        HttpServletResponse response = ServletActionContext.getResponse();

        //headers?
        String fullContentType = contentType + ";charset=" + encoding;
        response.setContentType(fullContentType);
        if (noCache) {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
        }

        response.getWriter().write(content);
        response.getWriter().flush();

    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:org.aselect.server.request.handler.openid.op.OpenID_RequestHandler.java

/**
 * Process incoming request <br>/*from ww  w  . j  a  va2  s  .co  m*/
 * .
 * 
 * @param request
 *            HttpServletRequest.
 * @param response
 *            HttpServletResponse.
 * @return the request state
 * @throws ASelectException
 *             If processing of  data request fails.
 */

public RequestState process(HttpServletRequest request, HttpServletResponse response) throws ASelectException {
    String sMethod = "process";
    //// maybe use "on the fly" endPointURL ?
    //         String handlerTarget = "/openidop_request";   // Don't forget to fill in the target
    //         String epu = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + handlerTarget;
    //         setOpEndpointUrl(epu);
    //         serverManager.setOPEndpointUrl(getOpEndpointUrl());
    /////

    ParameterList requestp = null;
    Message opResponse = null;
    String mode = null;

    Map reqParms = request.getParameterMap();
    if (reqParms.isEmpty()) {
        // assume discovery request...
        _systemLogger.log(Level.INFO, MODULE, sMethod, "Parameterlist is empty, assuming discovery request");

        try {
            String localID = request.getRequestURL().toString();
            localID = StringUtils.substringAfter(localID, getOpEndpointUrl());
            localID = localID.replaceFirst("^/", ""); // strip starting slash

            _systemLogger.log(Level.INFO, MODULE, sMethod, "localID:" + localID);
            Utils.sendDiscoveryResponse(request, response, createXrdsResponse(localID), _systemLogger);
        } catch (IOException e) {
            _systemLogger.log(Level.WARNING, MODULE, sMethod, "Problem sending XRDS response");
            throw new ASelectCommunicationException("Problem sending XRDS response", e);
        }
    } else {
        requestp = new ParameterList(request.getParameterMap());
        mode = reqParms.containsKey("openid.mode") ? requestp.getParameterValue("openid.mode") : null;
    }

    if ("associate".equals(mode)) {
        // --- process an association request ---
        _systemLogger.log(Level.INFO, MODULE, sMethod, "Process an association request");
        opResponse = serverManager.associationResponse(requestp);
        Utils.logRequestParameters(requestp, _systemLogger);
        Utils.sendPlainTextResponse(request, response, opResponse, _systemLogger);
    } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {
        _systemLogger.log(Level.INFO, MODULE, sMethod, "Process a checkid_setup or checkid_immediate request");
        Utils.logRequestParameters(requestp, _systemLogger);

        // RM_31_02, RM_31_03
        // authenticate to the aselect server
        String ridReqURL = aselectServerURL;
        String ridSharedSecret = sharedSecret;
        String ridAselectServer = _sMyServerID;
        String ridrequest = "authenticate";
        String ridAppURL = opEndpointUrl;

        //             String ridCheckSignature = verifySignature; 
        // maybe also forced_userid ?

        String claimedUID = requestp.getParameterValue("openid.claimed_id");
        String identity = requestp.getParameterValue("openid.identity");
        if (claimedUID == null && identity == null) {
            _systemLogger.log(Level.WARNING, MODULE, sMethod, "return error, extensions not supported (yet) ");
            Utils.logRequestParameters(requestp, _systemLogger);
            opResponse = DirectError.createDirectError("Extensions not supported (yet)");
            Utils.sendPlainTextResponse(request, response, opResponse, _systemLogger);
        }
        String uid = null;
        if ("http://specs.openid.net/auth/2.0/identifier_select".equals(identity)) {
            // RM_31_04
            // This should trigger a username input in  aselect
            // Either by presenting a choice or an input box
            // We let aselectserver handle this
            uid = defaultUID;
        } else {
            String localID = (identity == null) ? "" : identity;
            localID = StringUtils.substringAfter(localID, getOpEndpointUrl());
            localID = localID.replaceFirst("^/", ""); // strip starting slash
            uid = localID;
        }

        String ridResponse = "";
        // Send data 
        BufferedReader in = null;
        try {
            //Construct request data 
            String ridURL = ridReqURL + "?" + "shared_secret=" + URLEncoder.encode(ridSharedSecret, "UTF-8")
                    + "&a-select-server=" + URLEncoder.encode(ridAselectServer, "UTF-8") + "&request="
                    + URLEncoder.encode(ridrequest, "UTF-8") + "&uid=" + URLEncoder.encode(uid, "UTF-8") +
                    // RM_31_05
                    "&app_url=" + URLEncoder.encode(ridAppURL, "UTF-8") +
                    //                         "&check-signature=" + URLEncoder.encode(ridCheckSignature, "UTF-8") +
                    "&app_id=" + URLEncoder.encode(appID, "UTF-8");
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Requesting rid through: " + ridURL);

            URL url = new URL(ridURL);
            in = new BufferedReader(new InputStreamReader(url.openStream()));

            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                ridResponse += inputLine;
            }
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Requesting rid response: " + ridResponse);
        } catch (Exception e) {
            _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                    "Could not retrieve rid from aselectserver: " + ridAselectServer);
            throw new ASelectCommunicationException(Errors.ERROR_ASELECT_IO, e);
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    _systemLogger.log(Level.WARNING, MODULE, sMethod,
                            "Could not close stream to aselectserver : " + ridAselectServer);
                }
        }

        //out.println("<br/>ridResponse=" + ridResponse); 
        String extractedRid = ridResponse.replaceFirst(".*rid=([^&]*).*$", "$1");
        _systemLogger.log(Level.INFO, MODULE, sMethod, "rid retrieved: " + extractedRid);

        String sessionID = SESSIONID_PREFIX + extractedRid;
        _systemLogger.log(Level.INFO, MODULE, sMethod, "Storing requestparameters with id: " + sessionID);
        Utils.logRequestParameters(requestp, _systemLogger);

        HashMap<String, Object> htSessionContext = new HashMap<String, Object>();
        htSessionContext.put("openid_requestp", requestp);
        // 20120404, Bauke replaced: _oSessionManager.updateSession(sessionID, htSessionContext);
        _oSessionManager.createSession(sessionID, htSessionContext, true/*start paused*/); // new session with predefined RID

        String loginrequest = "login1";

        //Construct request data 
        String redirectURL = null;
        try {
            redirectURL = ridReqURL + "?" + "request=" + URLEncoder.encode(loginrequest, "UTF-8")
                    + "&a-select-server=" + URLEncoder.encode(ridAselectServer, "UTF-8") + "&rid="
                    + extractedRid;
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Requesting login through redirect with redirectURL: " + redirectURL);

            response.sendRedirect(redirectURL);
        } catch (UnsupportedEncodingException e1) {
            _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                    "Could not URLEncode to UTF-8, this should not happen!");
            throw new ASelectCommunicationException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e1);
        } catch (IOException e) {
            _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Could not redirect to: " + redirectURL);
            throw new ASelectCommunicationException(Errors.ERROR_ASELECT_IO, e);
        }

    } else if ("check_authentication".equals(mode)) {
        // --- processing a verification request ---
        _systemLogger.log(Level.INFO, MODULE, sMethod, "Process a check_authentication request");
        Utils.logRequestParameters(requestp, _systemLogger);
        opResponse = serverManager.verify(requestp);
        Utils.sendPlainTextResponse(request, response, opResponse, _systemLogger);
    } else {
        // This should be the aselectserver response
        if (request.getParameter("aselect_credentials") != null) {
            // handle the aselectserver response
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Handle the aselectserver response");

            // This could also be done by getting request parametermap
            String queryData = request.getQueryString();
            String extractedAselect_credentials = queryData.replaceFirst(".*aselect_credentials=([^&]*).*$",
                    "$1");
            String extractedRid = queryData.replaceFirst(".*rid=([^&]*).*$", "$1");
            String finalReqURL = aselectServerURL;
            String finalReqSharedSecret = sharedSecret;
            String finalReqAselectServer = _sMyServerID;
            String finalReqrequest = "verify_credentials";
            //                String ridCheckSignature = verifySignature; // this does not help for verify_credentials if <applications>
            // in aselect.xml has require_signing="true"

            //Construct request data
            // RM_31_06
            String finalRequestURL = null;
            try {
                finalRequestURL = finalReqURL + "?" + "shared_secret="
                        + URLEncoder.encode(finalReqSharedSecret, "UTF-8") + "&a-select-server="
                        + URLEncoder.encode(finalReqAselectServer, "UTF-8") + "&request="
                        + URLEncoder.encode(finalReqrequest, "UTF-8") + "&aselect_credentials="
                        + extractedAselect_credentials +
                        //                        "&check-signature=" + URLEncoder.encode(ridCheckSignature, "UTF-8") +
                        "&rid=" + extractedRid;

            } catch (UnsupportedEncodingException e3) {
                _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                        "Could not URLEncode to UTF-8, this should not happen!");
                throw new ASelectCommunicationException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e3);
            }
            String finalResult = "";

            //Send data
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Retrieving attributes through: " + finalRequestURL);

            BufferedReader in = null;
            try {
                URL url = new URL(finalRequestURL);

                in = new BufferedReader(new InputStreamReader(url.openStream()));

                String inputLine = null;
                while ((inputLine = in.readLine()) != null) {
                    finalResult += inputLine;
                }
                _systemLogger.log(Level.INFO, MODULE, sMethod, "Retrieved attributes in: " + finalResult);

            } catch (Exception e) {
                _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                        "Could not retrieve attributes from aselectserver: " + finalReqAselectServer);
                throw new ASelectCommunicationException(Errors.ERROR_ASELECT_IO, e);
            } finally {
                if (in != null)
                    try {
                        in.close();
                    } catch (IOException e) {
                        _systemLogger.log(Level.WARNING, MODULE, sMethod,
                                "Could not close stream to aselectserver : " + finalReqAselectServer);
                    }
            }

            String extractedAttributes = finalResult.replaceFirst(".*attributes=([^&]*).*$", "$1");
            String extractedResultCode = finalResult.replaceFirst(".*result_code=([^&]*).*$", "$1");

            String urlDecodedAttributes = null;
            ;
            String decodedAttributes = null;
            try {
                urlDecodedAttributes = URLDecoder.decode(extractedAttributes, "UTF-8");
                decodedAttributes = URLDecoder.decode(new String(
                        org.apache.commons.codec.binary.Base64.decodeBase64(urlDecodedAttributes.getBytes())),
                        "UTF-8");
                String attribs[] = decodedAttributes.split("&");
                for (int i = 0; i < attribs.length; i++) {
                    _systemLogger.log(Level.INFO, MODULE, sMethod,
                            "Retrieved attribute from aselectserver: " + attribs[i]);
                }

            } catch (UnsupportedEncodingException e2) {
                _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                        "Could not URLDecode from UTF-8, this should not happen!");
                throw new ASelectCommunicationException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e2);
            }

            String sessionID = SESSIONID_PREFIX + extractedRid;
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Retrieving requestparameters with sessionID: " + sessionID);

            HashMap<String, Object> htSessionContext = (HashMap<String, Object>) _oSessionManager
                    .get(sessionID);
            requestp = (ParameterList) htSessionContext.get("openid_requestp");

            Utils.logRequestParameters(requestp, _systemLogger);
            // RM_31_07
            //                _oSessionManager.killSession(sessionID);

            String userSelectedId = null;
            String userSelectedClaimedId = null;
            userSelectedId = getOpEndpointUrl() + "/" + finalResult.replaceFirst(".*uid=([^&]*).*$", "$1");
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Retrieved uid from aselect query string (userSelectedId): " + userSelectedId);
            userSelectedClaimedId = getOpEndpointUrl() + "/"
                    + decodedAttributes.replaceFirst(".*uid=([^&]*).*$", "$1");
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Retrieved uid from aselect attributes  (userSelectedClaimedId): " + userSelectedClaimedId);

            Boolean authenticatedAndApproved = false;
            try {
                authenticatedAndApproved = Boolean.valueOf(Integer.parseInt(extractedResultCode) == 0);
            } catch (NumberFormatException nfe) {
                _systemLogger.log(Level.WARNING, MODULE, sMethod,
                        "Resultcode from aselectserver was non-numeric: " + extractedResultCode);
            }

            // --- process an authentication request ---
            // RM_31_08
            opResponse = serverManager.authResponse(requestp, userSelectedId, userSelectedClaimedId,
                    authenticatedAndApproved.booleanValue());
            if (authenticatedAndApproved.booleanValue()) {
                try {
                    serverManager.sign((AuthSuccess) opResponse);
                    _systemLogger.log(Level.INFO, MODULE, sMethod, "Response signed");
                } catch (ServerException e1) {
                    _systemLogger.log(Level.WARNING, MODULE, sMethod,
                            "Unable to sign response, corresponding association cannot be found in store");
                } catch (AssociationException e1) {
                    _systemLogger.log(Level.WARNING, MODULE, sMethod,
                            "Unable to sign response, signature cannot be computed");
                }
            }

            // caller will need to decide which of the following to use:
            // - GET HTTP-redirect to the return_to URL
            // - HTML FORM Redirection

            String sRedirectUrl = opResponse.getDestinationUrl(true);
            // FOR GET-redirect
            _systemLogger.log(Level.INFO, MODULE, sMethod, "REDIR " + sRedirectUrl);
            try {
                response.sendRedirect(sRedirectUrl);
            } catch (IOException e) {
                StringBuffer sbWarning = new StringBuffer("Failed to redirect user to: ");
                sbWarning.append(sRedirectUrl);
                _systemLogger.log(Level.WARNING, MODULE, sMethod, sbWarning.toString());
                throw new ASelectCommunicationException(Errors.ERROR_ASELECT_IO, e);
            }

            // FOR FORM POST, set up form and...
            //      responseText = opResponse.wwwFormEncoding();
            //      String sRedirectUrl = opResponse.getDestinationUrl(false); 
            //      redirect(opResponse.getDestinationUrl(false));

        } else {
            // oops, it was not an aselectserver response
            // --- error response ---
            _systemLogger.log(Level.WARNING, MODULE, sMethod, "Unknown request: " + mode);
            Utils.logRequestParameters(requestp, _systemLogger);
            opResponse = DirectError.createDirectError("Unknown request");
            Utils.sendPlainTextResponse(request, response, opResponse, _systemLogger);
        }
    }
    return null;
}

From source file:org.b3log.latke.servlet.handler.RouteHandler.java

@Override
public void handle(final RequestContext context) {
    final HttpServletRequest request = context.getRequest();

    final long startTimeMillis = System.currentTimeMillis();
    request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis);
    String requestURI = getRequestURI(request);
    requestURI = StringUtils.substringAfter(requestURI, Latkes.getContextPath()); // remove servlet container context path
    final String httpMethod = getHttpMethod(request);
    LOGGER.log(Level.DEBUG, "Request [requestURI={0}, method={1}]", requestURI, httpMethod);

    final MatchResult result = doMatch(requestURI, httpMethod);
    if (result != null) {
        context.pathVars(result.getPathVars());
        context.attr(MATCH_RESULT, result);
        context.handle();//from  ww  w.  j  a  va2  s.  com
    }

    context.abort();
}

From source file:org.b3log.latke.util.StaticResources.java

/**
 * Initializes the static resource path patterns.
 *///from  ww  w  . j av  a  2s  . c  o  m
private static synchronized void init() {
    LOGGER.trace("Reads static resources definition from [static-resources.xml]");

    final File staticResources = Latkes.getWebFile("/WEB-INF/static-resources.xml");
    if (null == staticResources || !staticResources.exists()) {
        throw new IllegalStateException("Not found static resources definition from [static-resources.xml]");
    }

    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

    try {
        final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        final Document document = documentBuilder.parse(staticResources);
        final Element root = document.getDocumentElement();

        root.normalize();

        final StringBuilder logBuilder = new StringBuilder("Reading static files: [")
                .append(Strings.LINE_SEPARATOR);
        final NodeList includes = root.getElementsByTagName("include");
        for (int i = 0; i < includes.getLength(); i++) {
            final Element include = (Element) includes.item(i);
            String path = include.getAttribute("path");
            final URI uri = new URI("http", "b3log.org", path, null);
            final String s = uri.toASCIIString();
            path = StringUtils.substringAfter(s, "b3log.org");

            STATIC_RESOURCE_PATHS.add(path);

            logBuilder.append("    ").append("path pattern [").append(path).append("]");
            if (i < includes.getLength() - 1) {
                logBuilder.append(",");
            }
            logBuilder.append(Strings.LINE_SEPARATOR);
        }

        logBuilder.append("]");

        if (LOGGER.isTraceEnabled()) {
            LOGGER.debug(logBuilder.toString());
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Reads [" + staticResources.getName() + "] failed", e);
        throw new RuntimeException(e);
    }

    final StringBuilder logBuilder = new StringBuilder("Static files: [").append(Strings.LINE_SEPARATOR);
    final Iterator<String> iterator = STATIC_RESOURCE_PATHS.iterator();
    while (iterator.hasNext()) {
        final String pattern = iterator.next();

        logBuilder.append("    ").append(pattern);
        if (iterator.hasNext()) {
            logBuilder.append(',');
        }
        logBuilder.append(Strings.LINE_SEPARATOR);
    }
    logBuilder.append("], ").append('[').append(STATIC_RESOURCE_PATHS.size()).append("] path patterns");

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(logBuilder.toString());
    }

    inited = true;
}

From source file:org.b3log.rhythm.processor.ArticleProcessor.java

/**
 * Gets articles by tags./*from  w w  w.j  av  a  2 s .  co  m*/
 *
 * @param context the specified context
 * @throws IOException io exception
 */
@RequestProcessing(value = "/get-articles-by-tags.do", method = HTTPRequestMethod.GET)
public void getArticlesByTags(final HTTPRequestContext context) throws IOException {
    final HttpServletRequest request = context.getRequest();
    final String tagParam = request.getParameter(Tag.TAGS);
    if (Strings.isEmptyOrNull(tagParam)) {
        context.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    final String tagString = tagParam.toLowerCase();
    String soloHost = request.getParameter(Blog.BLOG_HOST);
    if (Strings.isEmptyOrNull(soloHost)) {
        context.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (soloHost.contains("://")) {
        soloHost = StringUtils.substringAfter(soloHost, "://");
    }

    soloHost = soloHost.split(":")[0];

    final int pageSize = Integer.valueOf(request.getParameter(Pagination.PAGINATION_PAGE_SIZE));
    String callbackFuncName = request.getParameter("callback");
    if (Strings.isEmptyOrNull(callbackFuncName)) {
        callbackFuncName = "callback";
    }

    final JSONObject jsonObject = new JSONObject();

    final JSONRenderer renderer = new JSONRenderer();
    renderer.setCallback(callbackFuncName); // Sets JSONP
    context.setRenderer(renderer);
    renderer.setJSONObject(jsonObject);

    jsonObject.put(Keys.STATUS_CODE, StatusCodes.GET_ARTICLES_SUCC);

    final List<JSONObject> articles = new ArrayList<JSONObject>();

    LOGGER.log(Level.DEBUG, "Getting articles by tags[{0}]....", tagString);
    try {
        final String[] tags = tagString.split(",");

        for (int i = 0; i < tags.length; i++) {
            final String tagTitle = tags[i];
            final JSONObject tag = tagRepository.getByTitle(tagTitle);

            if (null != tag) {
                LOGGER.log(Level.DEBUG, "Tag Title[{0}]", tag.getString(Tag.TAG_TITLE_LOWER_CASE));

                final String tagId = tag.getString(Keys.OBJECT_ID);
                final JSONObject result = tagArticleRepository.getByTagId(tagId, 1, pageSize);
                final JSONArray tagArticleRelations = result.getJSONArray(Keys.RESULTS);
                final int relationSize = pageSize < tagArticleRelations.length() ? pageSize
                        : tagArticleRelations.length();
                LOGGER.log(Level.TRACE, "Relation size[{0}]", relationSize);

                for (int j = 0; j < relationSize; j++) {
                    final JSONObject tagArticleRelation = tagArticleRelations.getJSONObject(j);
                    LOGGER.log(Level.TRACE, "Relation[{0}]", tagArticleRelation.toString());
                    final String relatedArticleId = tagArticleRelation
                            .getString(Article.ARTICLE + "_" + Keys.OBJECT_ID);
                    final JSONObject article = articleRepository.get(relatedArticleId);

                    String articleHost = article.getString(Blog.BLOG_HOST);
                    if (articleHost.contains("://")) {
                        articleHost = StringUtils.substringAfter(articleHost, "://");
                    }

                    articleHost = articleHost.split(":")[0];

                    if (articleHost.equalsIgnoreCase(soloHost)) {
                        continue; // Excludes articles from requested host
                    }

                    boolean existed = false;
                    for (final JSONObject relevantArticle : articles) {
                        if (relevantArticle.getString(Keys.OBJECT_ID)
                                .equals(article.getString(Keys.OBJECT_ID))) {
                            existed = true;
                        }
                    }

                    if (!existed) {
                        articles.add(article);
                    }

                    if (articles.size() == pageSize) {
                        break; // Got enough
                    }
                }
            }

            if (articles.size() == pageSize) {
                break; // Got enough
            }
        }

        removeUnusedProperties(articles);

        jsonObject.put(Article.ARTICLES, articles);

        jsonObject.put(Keys.STATUS_CODE, StatusCodes.GET_ARTICLES_SUCC);

        LOGGER.log(Level.DEBUG, "Got articles[{0}] by tag[{1}]", new Object[] { articles, tagString });
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Can not get articles", e);

        try {
            context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (final IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:org.b3log.rhythm.processor.VersionProcessor.java

/**
 * Gets the latest version of the B3log Solo.
 *
 * @param context the specified context//from   w ww .j a va2 s  .co m
 * @throws Exception exception
 */
@RequestProcessing(value = { "/version/solo/latest/*", "/version/solo/latest" }, method = HTTPRequestMethod.GET)
public void getLatestSoloVersion(final HTTPRequestContext context) throws Exception {
    final HttpServletRequest request = context.getRequest();
    String callbackFuncName = request.getParameter("callback");
    if (Strings.isEmptyOrNull(callbackFuncName)) {
        callbackFuncName = "callback";
    }

    final JSONObject jsonObject = new JSONObject();

    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);

    renderer.setCallback(callbackFuncName); // Sets JSONP
    renderer.setJSONObject(jsonObject);

    String currentVersion = request.getRequestURI();
    currentVersion = StringUtils.substringAfter(currentVersion, "/version/solo/latest");
    if (currentVersion.startsWith("/")) {
        currentVersion = currentVersion.substring(1);
    }

    final String latestVersion = Rhythms.getLatestSoloVersion(currentVersion);

    LOGGER.log(Level.DEBUG, "Version[client={0}, latest={1}]", new Object[] { currentVersion, latestVersion });

    jsonObject.put(Solo.SOLO_VERSION, latestVersion);

    jsonObject.put(Solo.SOLO_DOWNLOAD, Rhythms.LATEST_SOLO_DL_URL);
}

From source file:org.b3log.rhythm.processor.VersionProcessor.java

/**
 * Gets the latest version of the B3log Wide.
 *
 * @param context the specified context/* w  ww  .  j a  v  a 2s.c  o  m*/
 * @throws Exception exception
 */
@RequestProcessing(value = { "/version/wide/latest/*", "/version/wide/latest" }, method = HTTPRequestMethod.GET)
public void getLatestWideVersion(final HTTPRequestContext context) throws Exception {
    final HttpServletRequest request = context.getRequest();
    String callbackFuncName = request.getParameter("callback");
    if (Strings.isEmptyOrNull(callbackFuncName)) {
        callbackFuncName = "callback";
    }

    final JSONObject jsonObject = new JSONObject();

    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);

    renderer.setCallback(callbackFuncName); // Sets JSONP
    renderer.setJSONObject(jsonObject);

    String currentVersion = request.getRequestURI();
    currentVersion = StringUtils.substringAfter(currentVersion, "/version/wide/latest");
    if (currentVersion.startsWith("/")) {
        currentVersion = currentVersion.substring(1);
    }

    final String latestVersion = Rhythms.getLatestWideVersion(currentVersion);

    LOGGER.log(Level.DEBUG, "Version[client={0}, latest={1}]", new Object[] { currentVersion, latestVersion });

    jsonObject.put("wideVersion", latestVersion);
    jsonObject.put("wideDownload", Rhythms.LATEST_WIDE_DL_URL);
}