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

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

Introduction

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

Prototype

public static String substringBefore(final String str, final String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.netflix.imfutility.conversion.executor.ConversionOperationParser.java

private String addQuotes(String param) {
    if (!param.contains(" ") && !param.contains("\n") && !param.contains("\r")) {
        return param;
    }//from   w  w  w  .ja v  a 2s .c o  m
    if (!param.contains("=")) {
        return addQuotesIfNeeded(param);
    }
    String subParam = StringUtils.substringAfter(param, "=");
    String quotedSubParam = addQuotesIfNeeded(subParam);
    return StringUtils.substringBefore(param, "=") + "=" + quotedSubParam;
}

From source file:com.eryansky.common.orm.hibernate.HibernateDao.java

private String prepareCountHql(String orgHql) {
    String fromHql = orgHql;/*from ww  w  .jav  a  2s  .  c o m*/
    // select??order by???count,?.
    fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    fromHql = StringUtils.substringBefore(fromHql, "order by");

    String countHql = "select count(*) " + fromHql;
    return countHql;
}

From source file:com.project.framework.dao.BaseDao.java

/**
 * count.//from w ww  .  j  a  va 2s.co m
 * 
 * ????,???count?.
 */
public long countResult(final String queryString, final Object... values) {
    String fromHql = queryString;
    //select??order by???count,?.
    fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    fromHql = StringUtils.substringBefore(fromHql, "order by");

    String countHql = "select count(*) " + fromHql;

    try {
        Long count = executeUniqueQuery(countHql, values);
        return count;
    } catch (Exception e) {
        throw new RuntimeException("queryString can't be auto count, queryString is:" + countHql, e);
    }
}

From source file:com.neatresults.mgnltweaks.neatu2b.ui.action.AddU2BMetadataSaveDialogAction.java

public String getVideoId() {
    String fieldName = getDefinition().getIdFieldName();
    Property prop = item.getItemProperty(fieldName);
    if (prop == null) {
        throw new NullPointerException(fieldName
                + " is not set or name of the required field for this dialog is not correctly configured.");
    }//ww  w.j a v a  2  s  .co  m
    String maybeId = (String) prop.getValue();
    if (maybeId == null) {
        return null;
    }
    if (maybeId.startsWith("http")) {
        maybeId = StringUtils.substringBefore(StringUtils.substringAfter(maybeId, "?v="), "&");
    }
    return maybeId;
}

From source file:bear.core.BearMain.java

/**
 * -VbearMain.appConfigDir=src/main/groovy/examples -VbearMain.buildDir=.bear/classes -VbearMain.script=dumpSampleGrid -VbearMain.projectClass=SecureSocialDemoProject -VbearMain.propertiesFile=.bear/test.properties
 *//*from   ww w .j a va 2  s. c  o  m*/
public static void main(String[] args) throws Exception {
    int i = ArrayUtils.indexOf(args, "--log-level");

    if (i != -1) {
        LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.toLevel(args[i + 1]));
    }

    i = ArrayUtils.indexOf(args, "-q");

    if (i != -1) {
        LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.WARN);
    }

    GlobalContext global = GlobalContext.getInstance();

    BearMain bearMain = null;

    try {
        bearMain = new BearMain(global, getCompilerManager(), args);
    } catch (Exception e) {
        if (e.getClass().getSimpleName().equals("MissingRequiredOptionException")) {
            System.out.println(e.getMessage());
        } else {
            Throwables.getRootCause(e).printStackTrace();
        }

        System.exit(-1);
    }

    if (bearMain.checkHelpAndVersion()) {
        return;
    }

    AppOptions2 options2 = bearMain.options;

    if (options2.has(AppOptions2.UNPACK_DEMOS)) {
        String filesAsText = ProjectGenerator.readResource("/demoFiles.txt");

        int count = 0;

        for (String resource : filesAsText.split("::")) {
            File dest = new File(BEAR_DIR + resource);
            System.out.printf("copying %s to %s...%n", resource, dest);

            writeStringToFile(dest, ProjectGenerator.readResource(resource));

            count++;
        }

        System.out.printf("extracted %d files%n", count);

        return;
    }

    if (options2.has(AppOptions2.CREATE_NEW)) {
        String dashedTitle = options2.get(AppOptions2.CREATE_NEW);

        String user = options2.get(AppOptions2.USER);
        String pass = options2.get(AppOptions2.PASSWORD);

        List<String> hosts = options2.getList(AppOptions2.HOSTS);

        List<String> template;

        if (options2.has(AppOptions2.TEMPLATE)) {
            template = options2.getList(AppOptions2.TEMPLATE);
        } else {
            template = emptyList();
        }

        ProjectGenerator g = new ProjectGenerator(dashedTitle, user, pass, hosts, template);

        if (options2.has(AppOptions2.ORACLE_USER)) {
            g.oracleUser = options2.get(AppOptions2.ORACLE_USER);
        }

        if (options2.has(AppOptions2.ORACLE_PASSWORD)) {
            g.oraclePassword = options2.get(AppOptions2.ORACLE_PASSWORD);
        }

        File projectFile = new File(BEAR_DIR, g.getProjectTitle() + ".groovy");
        File pomFile = new File(BEAR_DIR, "pom.xml");

        writeStringToFile(projectFile, g.processTemplate("TemplateProject.template"));

        writeStringToFile(new File(BEAR_DIR, dashedTitle + ".properties"),
                g.processTemplate("project-properties.template"));
        writeStringToFile(new File(BEAR_DIR, "demos.properties"),
                g.processTemplate("project-properties.template"));
        writeStringToFile(new File(BEAR_DIR, "bear-fx.properties"),
                g.processTemplate("bear-fx.properties.template"));

        writeStringToFile(pomFile, g.generatePom(dashedTitle));

        System.out.printf("Created project file: %s%n", projectFile.getPath());
        System.out.printf("Created maven pom: %s%n", pomFile.getPath());

        System.out.println("\nProject files have been created. You may now: " + "\n a) Run `bear "
                + g.getShortName() + ".ls` to quick-test your minimal setup"
                + "\n b) Import the project to IDE or run smoke tests, find more details at the project wiki: https://github.com/chaschev/bear/wiki/.");

        return;
    }

    Bear bear = global.bear;

    if (options2.has(AppOptions2.QUIET)) {
        global.put(bear.quiet, true);
        LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.WARN);
    }

    if (options2.has(AppOptions2.USE_UI)) {
        global.put(bear.useUI, true);
    }

    if (options2.has(AppOptions2.NO_UI)) {
        global.put(bear.useUI, false);
    }

    List<?> list = options2.getOptionSet().nonOptionArguments();

    if (list.size() > 1) {
        throw new IllegalArgumentException("too many arguments: " + list + ", "
                + "please specify an invoke line, project.method(arg1, arg2)");
    }

    if (list.isEmpty()) {
        throw new UnsupportedOperationException("todo implement running a single project");
    }

    String invokeLine = (String) list.get(0);

    String projectName;
    String method;

    if (invokeLine.contains(".")) {
        projectName = StringUtils.substringBefore(invokeLine, ".");
        method = StringUtils.substringAfter(invokeLine, ".");
    } else {
        projectName = invokeLine;
        method = null;
    }

    if (method == null || method.isEmpty())
        method = "deploy()";
    if (!method.contains("("))
        method += "()";

    Optional<CompiledEntry<? extends BearProject>> optional = bearMain.compileManager.findProject(projectName);

    if (!optional.isPresent()) {
        throw new IllegalArgumentException("project was not found: " + projectName + ", loaded classes: \n"
                + Joiner.on("\n").join(bearMain.compileManager.findProjects()) + ", searched in: "
                + bearMain.compileManager.getSourceDirs() + ", ");
    }

    BearProject project = OpenBean.newInstance(optional.get().aClass).injectMain(bearMain);

    GroovyShell shell = new GroovyShell();

    shell.setVariable("project", project);
    shell.evaluate("project." + method);
}

From source file:com.adobe.cq.wcm.core.components.internal.models.v2.ImageImpl.java

protected void buildAreas() {
    areas = new ArrayList<>();
    String mapProperty = properties.get(Image.PN_MAP, String.class);
    if (StringUtils.isNotEmpty(mapProperty)) {
        // Parse the image map areas as defined at {@code Image.PN_MAP}
        String[] mapAreas = StringUtils.split(mapProperty, "][");
        for (String area : mapAreas) {
            int coordinatesEndIndex = area.indexOf(")");
            if (coordinatesEndIndex < 0) {
                break;
            }/*from w w w .  ja  v a2s . c o  m*/
            String shapeAndCoords = StringUtils.substring(area, 0, coordinatesEndIndex + 1);
            String shape = StringUtils.substringBefore(shapeAndCoords, "(");
            String coordinates = StringUtils.substringBetween(shapeAndCoords, "(", ")");
            String remaining = StringUtils.substring(area, coordinatesEndIndex + 1);
            String[] remainingTokens = StringUtils.split(remaining, "|");
            if (StringUtils.isBlank(shape) || StringUtils.isBlank(coordinates)) {
                break;
            }
            if (remainingTokens.length > 0) {
                String href = StringUtils.removeAll(remainingTokens[0], "\"");
                if (StringUtils.isBlank(href)) {
                    break;
                }
                String target = remainingTokens.length > 1 ? StringUtils.removeAll(remainingTokens[1], "\"")
                        : "";
                String alt = remainingTokens.length > 2 ? StringUtils.removeAll(remainingTokens[2], "\"") : "";
                String relativeCoordinates = remainingTokens.length > 3 ? remainingTokens[3] : "";
                relativeCoordinates = StringUtils.substringBetween(relativeCoordinates, "(", ")");
                if (href.startsWith("/")) {
                    href = Utils.getURL(request, pageManager, href);
                }
                areas.add(new ImageAreaImpl(shape, coordinates, relativeCoordinates, href, target, alt));
            }
        }
    }
}

From source file:io.wcm.tooling.commons.contentpackagebuilder.XmlContentBuilder.java

private String getNamespace(String key) {
    if (!StringUtils.contains(key, ":")) {
        return null;
    }/* w  w  w  .  j  ava 2  s.c  om*/
    String nsPrefix = StringUtils.substringBefore(key, ":");
    return xmlNamespaces.get(nsPrefix);
}

From source file:com.thinkbiganalytics.feedmgr.service.feed.datasource.DerivedDatasourceFactory.java

/**
 * Builds the list of data sources for the specified data transformation feed.
 *
 * @param feed the feed//from  w w  w . jav a 2  s.  c o  m
 * @return the list of data sources
 */
@Nonnull
private Set<Datasource.ID> ensureDataTransformationSourceDatasources(@Nonnull final FeedMetadata feed) {
    // Build the data sources from the view model
    final Set<Datasource.ID> datasources = new HashSet<>();
    final Set<String> tableNames = Optional.ofNullable(feed.getDataTransformation())
            .map(FeedDataTransformation::getTableNamesFromViewModel).orElse(Collections.emptySet());

    if (!tableNames.isEmpty()) {
        DatasourceDefinition datasourceDefinition = datasourceDefinitionProvider
                .findByProcessorType(DATA_TRANSFORMATION_DEFINITION);
        if (datasourceDefinition != null) {
            tableNames.forEach(hiveTable -> {
                String schema = StringUtils.trim(StringUtils.substringBefore(hiveTable, "."));
                String table = StringUtils.trim(StringUtils.substringAfterLast(hiveTable, "."));
                String identityString = datasourceDefinition.getIdentityString();
                Map<String, String> props = new HashMap<String, String>();
                props.put("schema", schema);
                props.put("table", table);
                identityString = propertyExpressionResolver.resolveVariables(identityString, props);
                String desc = datasourceDefinition.getDescription();
                if (desc != null) {
                    desc = propertyExpressionResolver.resolveVariables(desc, props);
                }
                String title = identityString;

                DerivedDatasource derivedDatasource = datasourceProvider.ensureDerivedDatasource(
                        datasourceDefinition.getDatasourceType(), identityString, title, desc,
                        new HashMap<String, Object>(props));
                if (derivedDatasource != null) {
                    datasources.add(derivedDatasource.getId());
                }
            });
        }
    }

    // Build the data sources from the data source ids
    final List<String> datasourceIds = Optional.ofNullable(feed.getDataTransformation())
            .map(FeedDataTransformation::getDatasourceIds).orElse(Collections.emptyList());
    datasourceIds.stream().map(datasourceProvider::resolve).forEach(datasources::add);

    return datasources;
}

From source file:eu.openanalytics.rsb.Util.java

/**
 * Extracts an UriBuilder for the current request, taking into account the possibility of
 * header-based URI override.// w  w w.  ja v a 2  s .c om
 * 
 * @param uriInfo
 * @param httpHeaders
 * @return
 * @throws URISyntaxException
 */
public static UriBuilder getUriBuilder(final UriInfo uriInfo, final HttpHeaders httpHeaders)
        throws URISyntaxException {
    final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();

    final List<String> hosts = httpHeaders.getRequestHeader(HttpHeaders.HOST);
    if ((hosts != null) && (!hosts.isEmpty())) {
        final String host = hosts.get(0);
        uriBuilder.host(StringUtils.substringBefore(host, ":"));

        final String port = StringUtils.substringAfter(host, ":");
        if (StringUtils.isNotBlank(port)) {
            uriBuilder.port(Integer.valueOf(port));
        }
    }

    final String protocol = getSingleHeader(httpHeaders, Constants.FORWARDED_PROTOCOL_HTTP_HEADER);
    if (StringUtils.isNotBlank(protocol)) {
        uriBuilder.scheme(protocol);
    }

    return uriBuilder;
}

From source file:jodtemplate.template.expression.DefaultExpressionHandler.java

private VariableExpression createVariableExpressionNoCheck(final String expressionBody) {
    String defaultValue = StringUtils.substringAfterLast(expressionBody, DEFAULT_VALUE_SEPARATOR).trim();
    defaultValue = StringUtils.remove(defaultValue, '"');
    final String variableWithParams = StringUtils.substringBefore(expressionBody, DEFAULT_VALUE_SEPARATOR);
    final String variable = StringUtils.substringBefore(variableWithParams, PARAMS_VALUE_SEPARATOR);
    final String paramsString = StringUtils.substringAfter(variableWithParams, PARAMS_VALUE_SEPARATOR);
    final List<String> params = Arrays.asList(StringUtils.split(paramsString, PARAMS_VALUE_SEPARATOR));
    final VariableExpression variableExpression = new VariableExpression(variable, params, defaultValue);
    return variableExpression;
}