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

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

Introduction

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

Prototype

public static String substringBetween(String str, String open, String close) 

Source Link

Document

Gets the String that is nested in between two Strings.

Usage

From source file:org.apache.http.examples.me.ClientMultiThreadedExecution.java

public static void callback(String _body, int id) throws JSONException {
    if (StringUtils.isBlank(_body))
        return;//from  w w  w .  j a  v  a  2s  . c  om
    String body = StringUtils.substringBetween(_body, "(", ")");
    System.out.println("body[" + body + "]");
    JSONObject jsonObject = new JSONObject(body);
    if (jsonObject.getBoolean("login")) {
        JSONObject miphone = jsonObject.getJSONObject("status").getJSONObject("miphone");
        if (miphone.getBoolean("reg")) {
            String hdurl = miphone.getString("hdurl");
            if (StringUtils.isNotBlank(hdurl)) {
                hdurl = hitUrl + hdurl;
                System.out.println(hdurl);
                runBroswer(hdurl);
            } else {
                System.out.println("user is not hit!!!");
            }
        } else {
            System.out.println("user is not register!!!");
        }
    } else {
        System.out.println("user is not login!!!");
    }
}

From source file:org.apache.jackrabbit.core.query.lucene.CountHandler.java

/**
 * Checks if there is a count function in the column names and return the count type based on its parameters.
 * @param columns/*  ww  w  .j  av  a2s. co  m*/
 * @param session
 * @return the count type
 */
public static CountType hasCountFunction(Map<String, PropertyValue> columns, SessionImpl session) {
    CountType countType = null;
    try {
        String repCount = session.getJCRName(REP_COUNT_LPAR);
        for (String column : columns.keySet()) {
            if (column.trim().startsWith(repCount)) {
                countType = new CountType();
                String countSettings = StringUtils.substringBetween(column, repCount, ")");
                if (countSettings.contains("skipChecks=1")) {
                    countType.setSkipChecks(true);
                }
                if (countSettings.contains("approximate=1")) {
                    countType.setApproxCount(true);
                }
                Matcher matcher = APPROX_COUNT_LIMIT_PATTERN.matcher(countSettings);
                if (matcher.matches()) {
                    countType.setApproxCount(true);
                    countType.setApproxCountLimit(Integer.parseInt(matcher.group(1)));
                }
                break;
            }
        }
    } catch (NamespaceException e) {
    }
    return countType;
}

From source file:org.apache.jackrabbit.core.query.lucene.JahiaLuceneQueryFactoryImpl.java

private Query resolveSingleMixedInclusiveExclusiveRangeQuery(String expression) {
    Query qobj = null;//  ww  w. j  ava2 s.c o m
    boolean inclusiveEndRange = expression.endsWith("]");
    boolean exclusiveEndRange = expression.endsWith("}");
    int inclusiveBeginRangeCount = StringUtils.countMatches(expression, "[");
    int exclusiveBeginRangeCount = StringUtils.countMatches(expression, "{");
    if (((inclusiveEndRange && exclusiveBeginRangeCount == 1 && inclusiveBeginRangeCount == 0)
            || (exclusiveEndRange && inclusiveBeginRangeCount == 1 && exclusiveBeginRangeCount == 0))) {
        String fieldName = (inclusiveEndRange || exclusiveEndRange)
                ? StringUtils.substringBefore(expression, inclusiveEndRange ? ":{" : ":[")
                : "";
        if (fieldName.indexOf(' ') == -1) {
            fieldName = fieldName.replace("\\:", ":");
            String rangeExpression = StringUtils.substringBetween(expression, inclusiveEndRange ? "{" : "[",
                    inclusiveEndRange ? "]" : "}");
            String part1 = StringUtils.substringBefore(rangeExpression, " TO");
            String part2 = StringUtils.substringAfter(rangeExpression, "TO ");
            SchemaField sf = new SchemaField(fieldName, JahiaQueryParser.STRING_TYPE);
            qobj = JahiaQueryParser.STRING_TYPE.getRangeQuery(null, sf, part1.equals("*") ? null : part1,
                    part2.equals("*") ? null : part2, !inclusiveEndRange, inclusiveEndRange);
        }
    }
    return qobj;
}

From source file:org.apache.synapse.mediators.elementary.Target.java

/**
 * Handles enrichment of properties when defined as a custom type
 *
 * @param xpath          expression to get property
 * @param synContext     messageContext used in the mediation
 * @param sourceNodeList node list which used to change the target
 * @param synLog         the Synapse log to use
 *//*from  w  w  w. j a va 2s . c o  m*/
private void handleProperty(SynapseXPath xpath, MessageContext synContext, ArrayList<OMNode> sourceNodeList,
        SynapseLog synLog) {

    String scope = XMLConfigConstants.SCOPE_DEFAULT;
    Pattern p = Pattern.compile(XPATH_PROPERTY_PATTERN);
    Matcher m = p.matcher(xpath.getExpression());
    List<String> propList = new ArrayList();
    while (m.find()) {
        propList.add(StringUtils.substringBetween(m.group(), "\'", "\'"));
    }

    if (propList.size() > 1) {
        property = propList.get(1);
        scope = propList.get(0);
    } else {
        property = propList.get(0);
    }

    OMElement documentElement = null;
    Object propertyObj = null;
    Axis2MessageContext axis2smc = (Axis2MessageContext) synContext;

    if (action != null && property != null) {
        if (XMLConfigConstants.SCOPE_DEFAULT.equals(scope)) {
            propertyObj = synContext.getProperty(property);
        } else if (XMLConfigConstants.SCOPE_AXIS2.equals(scope)) {
            propertyObj = axis2smc.getAxis2MessageContext().getProperty(property);
        } else if (XMLConfigConstants.SCOPE_OPERATION.equals(scope)) {
            propertyObj = axis2smc.getAxis2MessageContext().getOperationContext().getProperty(property);
        }

        if (propertyObj != null && propertyObj instanceof OMElement && action.equals(ACTION_ADD_CHILD)) {
            documentElement = (OMElement) propertyObj;
            documentElement = documentElement.cloneOMElement();
            //logic should valid only when adding child elements, and other cases
            //such as sibling and replacement using the else condition
            insertElement(sourceNodeList, documentElement, synLog);
            this.setProperty(scope, synContext, documentElement);
        } else {
            this.setProperty(scope, synContext, sourceNodeList);
        }
    } else {
        this.setProperty(scope, synContext, sourceNodeList);
    }
}

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}.
 *///from  ww  w  . j a  v  a  2  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.apereo.lap.services.storage.mongo.MongoMultiTenantFilter.java

@Override
public void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain fc)
        throws ServletException, IOException {
    logger.debug("applying MongoMultiTenantFilter");
    logger.debug("allow defaultDatabase: " + useDefaultDatabaseName);

    // For now header trumps all sources        
    String tenant = req.getHeader("X-LAP-TENANT");

    if (StringUtils.isBlank(tenant)) {
        // Next try path
        String requestURI = req.getRequestURI();
        if (StringUtils.isBlank(tenant) && StringUtils.isNotBlank(requestURI)
                && StringUtils.startsWith(requestURI, "/api/output/")) {
            tenant = StringUtils.substringBetween(requestURI, "/api/output/", "/");
        }//from w ww  .j av  a2 s.c o  m

        if (StringUtils.isBlank(tenant)) {
            // Next try session
            tenant = tenantService.getTenant();

            // If still blank and a default db is allowed
            if (StringUtils.isBlank(tenant)) {
                if (Boolean.valueOf(useDefaultDatabaseName)) {
                    logger.warn("No tenant available in request. Using default database.");
                    tenant = defaultDatabase;
                } else {
                    throw new MissingTenantException(
                            "No tenant available in request and default database disabled.");
                }
            }
        }
    }

    tenantService.setTenant(tenant);
    logger.debug("Using tenant {}", tenantService.getTenant());

    fc.doFilter(req, res);
}

From source file:org.apereo.portal.layout.dlm.remoting.UpdatePreferencesServlet.java

protected void removeSubscription(IPerson per, String elementId, IUserLayoutManager ulm) {

    // get the fragment owner's ID from the element string
    String userIdString = StringUtils.substringBetween(elementId, Constants.FRAGMENT_ID_USER_PREFIX,
            Constants.FRAGMENT_ID_LAYOUT_PREFIX);
    int userId = NumberUtils.toInt(userIdString, 0);

    // construct a new person object representing the fragment owner
    RestrictedPerson fragmentOwner = PersonFactory.createRestrictedPerson();
    fragmentOwner.setID(userId);/*  www  .j  a va2 s . c  om*/
    fragmentOwner.setUserName(userIdentityStore.getPortalUserName(userId));

    // attempt to find a subscription for this fragment
    IUserFragmentSubscription subscription = userFragmentInfoDao.getUserFragmentInfo(per, fragmentOwner);

    // if a subscription was found, remove it's registration
    if (subscription != null) {
        userFragmentInfoDao.deleteUserFragmentInfo(subscription);
        ulm.loadUserLayout(true);
    }

    // otherwise, delete the node
    else {
        ulm.deleteNode(elementId);
    }

}

From source file:org.b3log.latke.cron.Cron.java

/**
 * Parses the specified schedule into {@link #period execution period}.
 * //from  ww  w  . java 2s . c  o m
 * @param schedule the specified schedule
 */
private void parse(final String schedule) {
    final int num = Integer.valueOf(StringUtils.substringBetween(schedule, " ", " "));
    final String timeUnit = StringUtils.substringAfterLast(schedule, " ");

    LOGGER.log(Level.FINEST, "Parsed cron job[schedule={0}]: [num={1}, timeUnit={2}]",
            new Object[] { schedule, num, timeUnit });

    if ("hours".equals(timeUnit)) {
        period = num * SIXTY * SIXTY * THOUSAND;
    } else if ("minutes".equals(timeUnit)) {
        period = num * SIXTY * THOUSAND;
    }
}

From source file:org.b3log.latke.servlet.RequestProcessors.java

/**
 * Scans classpath (classes directory) to discover request processor classes.
 *///w  w  w  .j  av  a 2s  .co m
private static void discoverFromClassesDir() {
    final String webRoot = AbstractServletListener.getWebRoot();
    final File classesDir = new File(
            webRoot + File.separator + "WEB-INF" + File.separator + "classes" + File.separator);
    @SuppressWarnings("unchecked")
    final Collection<File> classes = FileUtils.listFiles(classesDir, new String[] { "class" }, true);
    final ClassLoader classLoader = RequestProcessors.class.getClassLoader();

    try {
        for (final File classFile : classes) {
            final String path = classFile.getPath();
            final String className = StringUtils
                    .substringBetween(path, "WEB-INF" + File.separator + "classes" + File.separator, ".class")
                    .replaceAll("\\/", ".").replaceAll("\\\\", ".");
            final Class<?> clz = classLoader.loadClass(className);

            if (clz.isAnnotationPresent(RequestProcessor.class)) {
                LOGGER.log(Level.FINER, "Found a request processor[className={0}]", className);
                final Method[] declaredMethods = clz.getDeclaredMethods();

                for (int i = 0; i < declaredMethods.length; i++) {
                    final Method mthd = declaredMethods[i];
                    final RequestProcessing annotation = mthd.getAnnotation(RequestProcessing.class);

                    if (null == annotation) {
                        continue;
                    }

                    addProcessorMethod(annotation, clz, mthd);
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "Scans classpath (classes directory) failed", e);
    }
}

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

/**
 * Resolves the specified URI with the specified URI template.
 *
 * @param uri         the specified URI/*from  w w  w .  jav  a 2s . c o m*/
 * @param uriTemplate the specified URI template
 * @return resolved mappings of name and argument, returns {@code null} if failed
 */
public static Map<String, String> resolve(final String uri, final String uriTemplate) {
    final String[] parts = URLs.decode(uri).split("/");
    final String[] templateParts = uriTemplate.split("/");
    if (parts.length != templateParts.length) {
        return null;
    }

    final Map<String, String> ret = new HashMap<>();
    for (int i = 0; i < parts.length; i++) {
        final String part = parts[i];
        final String templatePart = templateParts[i];
        if (part.equals(templatePart)) {
            continue;
        }

        String name = StringUtils.substringBetween(templatePart, "{", "}");
        if (StringUtils.isBlank(name)) {
            return null;
        }

        final String templatePartTmp = StringUtils.replace(templatePart, "{" + name + "}", "");
        final String arg = StringUtils.replace(part, templatePartTmp, "");

        ret.put(name, arg);
    }

    return ret;
}