Example usage for org.apache.commons.lang3 StringUtils split

List of usage examples for org.apache.commons.lang3 StringUtils split

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils split.

Prototype

public static String[] split(final String str, final String separatorChars) 

Source Link

Document

Splits the provided text into an array, separators specified.

Usage

From source file:io.mapzone.controller.vm.http.AuthTokenValidator.java

/**
 * /*from   ww  w . j a va 2  s . c  o  m*/
 *
 * @throws HttpProvisionRuntimeException If project does not exists.
 */
public boolean checkAuthToken() {
    ProjectInstanceIdentifier pid = new ProjectInstanceIdentifier(request);

    // check param token; ignore parameter char case
    Optional<String> requestToken = requestParameter(REQUEST_PARAM_TOKEN);
    if (requestToken.isPresent()) {
        if (!isValidToken(requestToken.get(), pid)) {
            throw new HttpProvisionRuntimeException(401, "Given auth token is not valid for this project.");
        }
        return true;
    }

    // check path parts
    String path = StringUtils.defaultString(request.getPathInfo());
    for (String part : StringUtils.split(path, '/')) {
        if (isValidToken(part, pid)) {
            return true;
        }
    }
    return false;
}

From source file:kenh.xscript.elements.Method.java

/**
 * Process method of {@code Method} element.
 * //from ww w  .  j  a v  a2 s .  c o m
 * @param name
 * @param parameter
 * @throws UnsupportedScriptException
 */
@Processing
public void process(@Attribute(ATTRIBUTE_NAME) String name, @Primal @Attribute(ATTRIBUTE_PARA) String parameter)
        throws UnsupportedScriptException {
    this.name = name;

    if (StringUtils.isBlank(name)) {
        UnsupportedScriptException ex = new UnsupportedScriptException(this, "The method name is empty.");
        throw ex;
    }

    Map<String, Element> methods = this.getEnvironment().getMethods();
    if (methods.containsKey(name)) {
        UnsupportedScriptException ex = new UnsupportedScriptException(this,
                "Reduplicate method. [" + name + "]");
        throw ex;
    }

    if (StringUtils.isNotBlank(parameter)) {
        String[] paras = StringUtils.split(parameter, ",");
        Vector<String[]> allParas = new Vector();
        Vector<String> existParas = new Vector(); // exist parameters
        for (String para : paras) {
            if (StringUtils.isBlank(para)) {
                UnsupportedScriptException ex = new UnsupportedScriptException(this,
                        "Parameter format incorrect. [" + name + ", " + parameter + "]");
                throw ex;
            }

            String[] all = StringUtils.split(para, " ");
            String paraName = StringUtils.trimToEmpty(all[all.length - 1]);
            if (StringUtils.isBlank(paraName) || StringUtils.contains(paraName, "{")) {
                UnsupportedScriptException ex = new UnsupportedScriptException(this,
                        "Parameter format incorrect. [" + name + ", " + parameter + "]");
                throw ex;
            }
            if (existParas.contains(paraName)) {
                UnsupportedScriptException ex = new UnsupportedScriptException(this,
                        "Reduplicate parameter. [" + name + ", " + paraName + "]");
                throw ex;
            } else {
                existParas.add(paraName);
            }

            Vector<String> one = new Vector();
            one.add(paraName);
            for (int i = 0; i < all.length - 1; i++) {
                String s = StringUtils.trimToEmpty(all[i]);
                if (StringUtils.isBlank(s))
                    continue;
                if (s.equals(MODI_FINAL) || s.equals(MODI_REQUIRED)
                        || (s.startsWith(MODI_DEFAULT + "(") && s.endsWith(")"))) {
                    one.add(s);
                } else {
                    UnsupportedScriptException ex = new UnsupportedScriptException(this,
                            "Unsupported modifier. [" + name + ", " + paraName + ", " + s + "]");
                    throw ex;
                }
            }

            String[] one_ = one.toArray(new String[] {});
            allParas.add(one_);
        }

        parameters = allParas.toArray(new String[][] {});
    }

    // store into {methods}
    methods.put(name, this);
}

From source file:io.knotx.launcher.SystemPropsConfiguration.java

/**
 * Update given JsonObject with the data provided in system property during Knotx start.<br>
 * In order to provide such overrides you can use two approches:
 * <ul>//ww  w . j ava  2  s.com
 * <li>-Dio.knotx.KnotxServer.httpPort=9999,
 * -Dio.knotx.KnotxServer.splitter.address=other-address - this will override one property
 * with the value given after '=' </li>
 * <li>-Dio.knotx.KnotxServer.splitter=file:/aaa/bb/cc.json - this will merge the given cc.json
 * file from the field specified</li>
 * </ul>
 *
 * @param descriptor - JsonObject with module descriptor
 * @return JsonObject - updated descriptor
 */
public JsonObject updateJsonObject(JsonObject descriptor) {
    final JsonObject object = descriptor.copy();
    envConfig.entrySet().forEach(entry -> {
        String[] path = StringUtils.split(entry.getKey(), ".");
        JsonObject element = object;
        for (int idx = 0; idx < path.length; idx++) {
            if (idx < path.length - 1) {
                if (element.containsKey(path[idx])) {
                    element = element.getJsonObject(path[idx]);
                } else {
                    throw new IllegalArgumentException("Wrong config override. There is no matching element "
                            + entry.getKey() + " in the configuration");
                }
            } else { //last
                if (entry.getValue().getObject() instanceof JsonObject) {
                    element.getJsonObject(path[idx]).mergeIn((JsonObject) entry.getValue().getObject());
                } else {
                    element.put(path[idx], entry.getValue().getObject());
                }
            }
        }
    });
    return object;
}

From source file:com.qcadoo.mes.basic.shift.WorkingHours.java

private TimeRange stringToInterval(final String hoursRange) {
    String[] lowerUpperBound = StringUtils.split(hoursRange, '-');
    LocalTime lower = LocalTime.parse(lowerUpperBound[0], TIME_FORMATTER);
    LocalTime upper = LocalTime.parse(lowerUpperBound[1], TIME_FORMATTER);
    return new TimeRange(lower, upper);
}

From source file:com.thruzero.domain.service.impl.GenericSettingService.java

@Override
public Set<String> splitStringValueFor(final String context, final String name, final String separator) {
    Set<String> result = new HashSet<String>();
    String flattenedResult = getStringValue(context, name);
    String[] tokens = StringUtils.split(flattenedResult, separator);

    if (tokens != null) {
        for (String value : tokens) {
            value = StringUtils.trim(value);

            if (StringUtils.isNotEmpty(value)) {
                result.add(value);/* w ww  .ja v a  2  s .c  om*/
            }
        }
    }

    return result;
}

From source file:com.thruzero.common.core.utils.MapUtilsExt.java

/**
 * Takes the comma separated series of keys and returns a {@code Map} of key/value pairs (trimming each key segment
 * before lookup)./*ww  w  . j a va2  s  .  c  o m*/
 *
 * @param commaSeparatedKeys series of key names (e.g., "foo, bar").
 * @return key/value pair for each key in the series.
 */
public static <K, V> Map<String, String> getValueAsStringMap(final K key, final Map<K, V> map) {
    Object mapValue = map.get(key);

    if (mapValue == null) {
        return null;
    } else {
        Map<String, String> result = new LinkedHashMap<String, String>();
        String[] pairs = StringUtils.split(mapValue.toString(), ']');

        for (String string : pairs) {
            String[] values = StringUtils.split(StringUtils.substring(string, 1, string.length() - 1), ',');
            result.put(values[0], values[1].trim());
        }

        return result;
    }
}

From source file:net.sf.appstatus.web.StatusServlet.java

/**
 * Init the AppStatus Web UI.// ww w.jav  a  2 s . c  o  m
 * <p>
 * Read <b>bean</> init parameter. If defined, switch to Spring-enabled
 * behavior.
 */
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    super.init();

    SpringObjectInstantiationListener instantiation = null;
    String beanName = getInitParameter("bean");
    String[] pagesBeanNames = StringUtils.split(getInitParameter("custom-pages"), ", ");
    Map<String, IPage> pages = new LinkedHashMap<String, IPage>();
    ;

    AppStatus status;
    if (beanName != null) {
        // Using Spring
        instantiation = new SpringObjectInstantiationListener(this.getServletContext());

        // Status
        status = (AppStatus) instantiation.getInstance(beanName);

    } else {
        status = AppStatusStatic.getInstance();

    }

    status.setServletContextProvider(new IServletContextProvider() {
        public ServletContext getServletContext() {
            return StatusServlet.this.getServletContext();
        }
    });

    //
    // Pages
    addPage(pages, new StatusPage());

    if (status.getServiceManager() != null) {
        addPage(pages, new ServicesPage());
    }

    if (status.getBatchManager() != null) {
        addPage(pages, new BatchPage());

    }

    if (status.getLoggersManager() != null) {
        addPage(pages, new LoggersPage());

    }

    // Custom pages
    if (pagesBeanNames != null) {
        for (String pageBean : pagesBeanNames) {

            IPage newPage = null;

            if (instantiation != null) {
                newPage = (IPage) instantiation.getInstance(pageBean);
                if (newPage == null) {
                    try {
                        newPage = (IPage) Thread.currentThread().getContextClassLoader().loadClass(pageBean)
                                .newInstance();
                    } catch (ClassNotFoundException e) {
                        logger.warn("Class {} not found ", pageBean, e);
                    } catch (InstantiationException e) {
                        logger.warn("Cannot instanciate {} ", pageBean, e);
                    } catch (IllegalAccessException e) {
                        logger.warn("Cannot access class {} for instantiation ", pageBean, e);
                    }
                }
            }

            addPage(pages, newPage);

        }
    }

    // Radiator at the end.
    addPage(pages, new RadiatorPage());

    // Init
    statusWeb = new StatusWebHandler();
    statusWeb.setAppStatus(status);
    statusWeb.setApplicationName(
            StringUtils.defaultString(config.getServletContext().getServletContextName(), "No name"));
    statusWeb.setPages(pages);
    statusWeb.init();
}

From source file:com.sonicle.webtop.core.sdk.ServiceVersion.java

@Override
public int compareTo(ServiceVersion o) {
    if (o == null)
        return 1;
    if ((o.getValue() == null) && (this.getValue() == null))
        return 0;
    if (o.getValue() == null)
        return 1;
    if (this.getValue() == null)
        return -1;

    String[] thisTokens = StringUtils.split(this.getValue(), ".");
    String[] thatTokens = StringUtils.split(o.getValue(), ".");

    int length = Math.max(thisTokens.length, thatTokens.length);
    for (int i = 0; i < length; i++) {
        int thisToken = i < thisTokens.length ? Integer.parseInt(thisTokens[i]) : 0;
        int thatToken = i < thatTokens.length ? Integer.parseInt(thatTokens[i]) : 0;
        if (thisToken < thatToken)
            return -1;
        if (thisToken > thatToken)
            return 1;
    }//  w ww . j  a va 2  s.c o m
    return 0;
}

From source file:com.mingo.query.util.QueryUtils.java

/**
 * Gets elements of  composite query id.
 *
 * @param compositeQueryId composite query id
 * @return elements of  composite query id
 *//*from  w w  w  .  jav  a2s .co  m*/
public static String[] getCompositeIdElements(String compositeQueryId) {
    return StringUtils.split(compositeQueryId, ".");
}

From source file:net.ontopia.topicmaps.nav2.servlets.DataIntegrationServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/plain; charset=utf-8");

    // get topic map id
    String topicMapId = topicMapId = getInitParameter("topicMapId");
    if (topicMapId == null)
        throw new ServletException("Topic map identifier is not specified.");

    // parse path
    String path = request.getPathInfo();
    if (path == null)
        throw new ServletException("Path is missing.");
    path = path.substring(1);/*from w w w  .j a  v  a 2s  .  com*/

    String[] args = StringUtils.split(path, "/");
    String name = args[0];
    String action = args[1];

    // get topics query
    String topicsQuery = getInitParameter("topicsQuery");
    if (topicsQuery == null)
        throw new ServletException("Parameter 'topicsQuery' is not specified.");

    // get characteristcs query
    String characteristicsQuery = getInitParameter("characteristicsQuery");
    if (characteristicsQuery == null)
        throw new ServletException("Parameter 'characteristicsQuery' is not specified.");

    TopicMapStoreIF targetStore = TopicMaps.createStore(topicMapId, false);
    try {
        final TopicMapIF target = targetStore.getTopicMap();

        // transform input document to topic map
        final TopicMapIF source = transformRequest(name, request.getInputStream(),
                targetStore.getBaseAddress());

        // find topics to synchronize
        QueryProcessorIF qp = QueryUtils.getQueryProcessor(source);

        List candidates = new ArrayList();
        QueryResultIF qr = qp.execute(topicsQuery);
        try {
            while (qr.next()) {
                // synchronize topic
                candidates.add(qr.getValue(0));
            }
        } finally {
            qr.close();
        }

        if ("updated".equals(action) || "created".equals(action)) {

            DeciderIF tfilter = new DeciderIF() {
                @Override
                public boolean ok(Object o) {
                    return true;
                }
            };

            Iterator iter = candidates.iterator();
            while (iter.hasNext()) {
                TopicIF src = (TopicIF) iter.next();

                DeciderIF sfilter;
                if (characteristicsQuery == null) {
                    // let everything through
                    sfilter = tfilter;

                } else {
                    // let the characteristics query decide what gets synchronized
                    Collection characteristics = new HashSet();
                    QueryResultIF cqr = qp.execute(characteristicsQuery,
                            Collections.singletonMap("topic", src));
                    try {
                        while (cqr.next()) {
                            // synchronize topic
                            characteristics.add(cqr.getValue(0));
                        }
                    } finally {
                        cqr.close();
                    }
                    sfilter = new ContainmentDecider(characteristics);
                }
                // synchronize topic
                TopicMapSynchronizer.update(target, src, tfilter, sfilter);
            }
        } else if ("deleted".equals(action)) {

            Iterator iter = candidates.iterator();
            while (iter.hasNext()) {
                TopicIF src = (TopicIF) iter.next();
                Collection affectedTopics = IdentityUtils.findSameTopic(target, src);
                Iterator aiter = affectedTopics.iterator();
                while (aiter.hasNext()) {
                    TopicIF affectedTopic = (TopicIF) aiter.next();
                    affectedTopic.remove();
                }
            }
        } else {
            throw new ServletException("Unsupported action: " + action);
        }

        targetStore.commit();
    } catch (Exception e) {
        targetStore.abort();
        throw new ServletException(e);
    } finally {
        targetStore.close();
    }
}