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

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

Introduction

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

Prototype

public static String replaceOnce(String text, String searchString, String replacement) 

Source Link

Document

Replaces a String with another String inside a larger String, once.

Usage

From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java

/**
 * select ??  //  ww w . j ava  2s  . c o m
 * 
 * @param reqQuery
 * @exception
 */
private static Object runSQLOther(final UserDBDAO userDB, String strQuery, final List<Object> listParam)
        throws SQLException, Exception {

    // is tajo
    if (DBDefine.TAJO_DEFAULT == userDB.getDBDefine()) {
        logger.error("Not support TAJO.");
    } else {

        java.sql.Connection javaConn = null;
        PreparedStatement prepareStatement = null;
        try {
            SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
            javaConn = client.getDataSource().getConnection();
            prepareStatement = javaConn.prepareStatement(strQuery);

            // TODO mysql?  https://github.com/hangum/TadpoleForDBTools/issues/3  ?   create table ? ?? '(' ?? ? ?? .
            if (userDB.getDBDefine() == DBDefine.MYSQL_DEFAULT
                    || userDB.getDBDefine() == DBDefine.MARIADB_DEFAULT) {
                final String checkSQL = strQuery.trim().toUpperCase();
                if (StringUtils.startsWithIgnoreCase(checkSQL, "CREATE TABLE")) { //$NON-NLS-1$
                    strQuery = StringUtils.replaceOnce(strQuery, "(", " ("); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }

            //            // hive executeUpdate() ? . 13.08.19-hangum
            //            if(userDB.getDBDefine() == DBDefine.HIVE_DEFAULT | 
            //               userDB.getDBDefine() == DBDefine.HIVE2_DEFAULT 
            //            ) { 
            //               return prepareStatement.execute(strQuery);
            //            } else {

            for (int i = 0; i < listParam.size(); i++) {
                Object objParam = listParam.get(i);
                prepareStatement.setObject(i + 1, objParam);
            }

            return prepareStatement.executeUpdate();

        } finally {
            try {
                prepareStatement.close();
            } catch (Exception e) {
            }
        }
    } // end which db

    return false;
}

From source file:com.cognifide.slice.mapper.impl.SliceReferencePathResolverImpl.java

@Override
public String resolvePlaceholdersInPath(final String initialPath) {
    String path = initialPath;//from   w w  w . j  a  v a  2s.  c  o m
    Matcher matcher = PATTERN.matcher(initialPath);
    while (matcher.find()) {
        String placeholder = matcher.group(1);
        String replacement;
        Class<? extends Annotation> annotationClass = getAnnotation(placeholder);
        if (annotationClass != null) {
            replacement = injector.getInstance(Key.get(String.class, annotationClass));
        } else {
            replacement = getDirectReference(placeholder);
        }
        String group = matcher.group();
        path = StringUtils.replaceOnce(path, group, replacement);
    }
    return path;
}

From source file:com.ariht.maven.plugins.config.io.DirectoryReader.java

/**
 * Read directory creating FileInfo for each file found, include sub-directories.
 *//*from w ww .jav  a  2 s . c o  m*/
public List<FileInfo> readFiles(final String path, final List<String> filesAndDirectoriesToIgnore)
        throws IOException, InstantiationException, IllegalAccessException {
    final List<File> filesToIgnore = convertStringsToFiles(filesAndDirectoriesToIgnore);
    log.debug("Scanning directory: " + path);
    final File directory = new File(path);
    final Collection<File> allFiles = getAllFiles(directory, filesToIgnore);
    if (allFiles.isEmpty()) {
        log.warn("No files found in directory: " + path);
    }
    final List<FileInfo> allFilesInfo = new ArrayList<FileInfo>(allFiles.size());
    final String canonicalBaseDirectory = directory.getCanonicalPath();
    for (final File file : allFiles) {
        final FileInfo fileInfo = new FileInfo(log, file);
        // Remove base directory to derive sub-directory
        final String canonicalFilePath = FilenameUtils.getFullPathNoEndSeparator(file.getCanonicalPath());
        final String subDirectory = FilenameUtils
                .normalize(StringUtils.replaceOnce(canonicalFilePath, canonicalBaseDirectory, ""));
        fileInfo.setRelativeSubDirectory(subDirectory);
        allFilesInfo.add(fileInfo);
    }
    return allFilesInfo;
}

From source file:edu.msoe.se2800.h4.Logger.java

/**
 * Example usage://w  w  w . java 2  s .c om
 * <p/>
 * <code>
 * public class PerfectPerson {<br/>
 * public static final String TAG = "Logger";<br/>
 * public PerfectPerson() {<br/>
 * Logger.INSTANCE.log(TAG, "My eyes are %s and my hair is %s", new String[]{"Green", "Blonde"});<br/> 
 * }<br/>
 * }<br/>
 * </code><br/>
 * will produce (PerfectPerson, My eyes are Green and my hair is Blonde).
 * 
 * @param tag of the class making the call.
 * @param message to be logged. Use %s to indicate fields.
 * @param args Strings to populate fields with. These need to be in the order they are found in
 *            the message
 */
public void log(String tag, String message, String[] args) {
    synchronized (this) {
        OutputStreamWriter writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(FILE_NAME, true));
            DateFormat format = DateFormat.getInstance();

            // Print the date/timestamp
            writer.write(format.format(new Date()));
            writer.write(" | ");

            // Print the tag
            writer.write(tag);
            writer.write(" | ");

            if (StringUtils.countMatches(message, "%s") != args.length) {
                throw new IllegalArgumentException("The number of placeholders in (" + message
                        + ") was not the same as the number of args (" + args.length + ").");
            }
            for (String s : args) {
                message = StringUtils.replaceOnce(message, "%s", s);
            }

            // Print the message
            writer.write(message);
            writer.write("\n");
        } catch (FileNotFoundException e1) {
            System.out.println("The specified file could not be found.");
        } catch (IOException e) {
            System.out.println("Unable to connect to the logger. This call to log() will be ignored.");
        } finally {
            if (writer != null) {
                try {
                    Closeables.close(writer, true);
                } catch (IOException e) {
                }
            }
        }
    }

}

From source file:eionet.cr.web.action.admin.harvestscripts.HarvestScriptParser.java

/**
 *
 * @param script/* ww  w  .  j  ava 2 s  .c  o  m*/
 * @param graphUri
 * @return
 */
public static String deriveSelect(String script, String graphUri) {

    String result = script;
    if (containsToken(result, "DELETE")) {

        if (containsToken(result, "INSERT")) {
            result = substringBeforeToken(result, "DELETE") + "SELECT" + substringAfterToken(result, "INSERT");
        } else {
            result = substringBeforeToken(result, "DELETE") + "SELECT" + substringAfterToken(result, "DELETE");
        }
    } else if (containsToken(result, "INSERT")) {
        result = substringBeforeToken(result, "INSERT") + "SELECT" + substringAfterToken(result, "INSERT");
    }

    if (containsToken(result, "WHERE")) {
        if (!containsToken(result, "FROM")) {
            result = substringBeforeToken(result, "WHERE") + "FROM <" + graphUri + "> WHERE"
                    + substringAfterToken(result, "WHERE");
        }
    } else {
        result = result + " FROM <" + graphUri + "> WHERE {?s ?p ?o}";
    }

    if (containsToken(result, "LIMIT")) {
        result = substringBeforeToken(result, "LIMIT") + "LIMIT " + TEST_RESULTS_LIMIT;
    } else {
        result = result + " LIMIT " + TEST_RESULTS_LIMIT;
    }

    if (containsToken(result, "SELECT")) {

        String afterSelect = substringAfterToken(result, "SELECT");
        afterSelect = StringUtils.replaceOnce(afterSelect, "{", "");
        afterSelect = StringUtils.replaceOnce(afterSelect, "}", "");
        result = substringBeforeToken(result, "SELECT") + "SELECT" + afterSelect;
    }

    return result.trim();
}

From source file:com.comcast.cats.config.ui.recording.MediaInfoBean.java

private String substituteFilePath(String filePath) {
    String retVal = filePath;/*from w w  w. java2s . c  o  m*/
    try {
        URL filePathURL = new URL(filePath);
        String host = filePathURL.getHost();
        retVal = StringUtils.replaceOnce(filePath, host, AuthController.getHostAddress());
    } catch (MalformedURLException e) {
        logger.debug("Provider doesnt know how to parse this syntax");
    }
    return retVal;
}

From source file:com.ariht.maven.plugins.config.DirectoryReader.java

/**
 * Read directory creating FileInfo for each file found, include sub-directories.
 *//*ww  w . ja  v  a2  s .  c om*/
public List<FileInfo> readFiles(final String path)
        throws IOException, InstantiationException, IllegalAccessException {
    log.debug("Scanning directory: " + path);
    final File directory = new File(path);
    final Collection<File> allFiles = getAllFiles(directory);
    if (allFiles.isEmpty()) {
        log.warn("No files found in directory: " + path);
    }
    final List<FileInfo> allFilesInfo = new ArrayList<FileInfo>(allFiles.size());
    final String canonicalBaseDirectory = directory.getCanonicalPath();
    for (final File file : allFiles) {
        final FileInfo fileInfo = new FileInfo(file);
        // Remove base directory to derive sub-directory
        final String canonicalFilePath = FilenameUtils.getFullPathNoEndSeparator(file.getCanonicalPath());
        final String subDirectory = FilenameUtils.normalize(
                StringUtils.replaceOnce(canonicalFilePath, canonicalBaseDirectory, "") + pathSeparator);
        fileInfo.setRelativeSubDirectory(subDirectory);
        allFilesInfo.add(fileInfo);
    }
    return allFilesInfo;
}

From source file:com.xceptance.xlt.common.util.bsh.ParamInterpreter.java

/**
 * Processes dynamic data on the input and use the set interpreter and its state.
 * /*from ww  w . j  av  a  2s  .c  om*/
 * @param testCase
 *            the currently active testcase, needed for proper property lookup
 * @param input
 *            the input to process
 * @return a processed string or the same, if nothing to process
 */
public String processDynamicData(final AbstractURLTestCase testCase, final String input) {
    if (input == null) {
        return null;
    }

    final List<String> params = new ArrayList<String>();

    // get all position out of the string
    final Matcher matcher = parameterPattern.matcher(input);
    while (matcher.find()) {
        params.add(matcher.group(1));
    }

    // did we find something?
    if (params.isEmpty()) {
        return input;
    }

    String output = input;

    // ok, go over the data
    for (final String param : params) {
        if (param.trim().length() == 0) {
            continue;
        }

        // first try to map it to a property if a test case is set otherwise ask the properties directly
        final String propertyValue = testCase != null ? testCase.getProperty(param)
                : XltProperties.getInstance().getProperty(param);
        if (propertyValue != null) {
            output = StringUtils.replaceOnce(output, "${" + param + "}", propertyValue);
            continue;
        }

        try {
            final Object evalResult = this.eval(param);
            if (evalResult != null) {
                output = StringUtils.replaceOnce(output, "${" + param + "}", evalResult.toString());
            }
        } catch (final EvalError e) {
            XltLogger.runTimeLogger.warn(
                    MessageFormat.format("Unable to process dynamic parameter {0}", "${" + param + "}"), e);
        }
    }

    return output;
}

From source file:com.hangum.tadpole.rdb.core.editors.main.execute.sub.ExecuteBatchSQL.java

/**
 * select? execute  ./*from w w  w  . ja  v a2s  . c o m*/
 * @param errMsg 
 * 
 * @param listQuery
 * @param reqQuery
 * @param userDB
 * @param userType
 * @param intCommitCount
 * @param userEmail
 * @throws Exception
 */
public static void runSQLExecuteBatch(String errMsg, List<String> listQuery, final RequestQuery reqQuery,
        final UserDBDAO userDB, final String userType, final int intCommitCount, final String userEmail)
        throws Exception {
    if (!PermissionChecker.isExecute(userType, userDB, listQuery)) {
        throw new Exception(errMsg);
    }
    // Check the db access control 
    for (String strQuery : listQuery) {
        if (PublicTadpoleDefine.YES_NO.YES.name().equals(userDB.getDbAccessCtl().getDdl_lock())) {
            throw new Exception(errMsg);
        }

        PublicTadpoleDefine.QUERY_DML_TYPE queryType = SQLUtil.sqlQueryType(strQuery);
        if (reqQuery.getSqlType() == SQL_TYPE.DDL) {
            if (PublicTadpoleDefine.YES_NO.YES.name().equals(userDB.getDbAccessCtl().getDdl_lock())) {
                throw new Exception(errMsg);
            }
        }
        if (queryType == QUERY_DML_TYPE.INSERT) {
            if (PublicTadpoleDefine.YES_NO.YES.name().equals(userDB.getDbAccessCtl().getInsert_lock())) {
                throw new Exception(errMsg);
            }
        }
        if (queryType == QUERY_DML_TYPE.UPDATE) {
            if (PublicTadpoleDefine.YES_NO.YES.name().equals(userDB.getDbAccessCtl().getUpdate_lock())) {
                throw new Exception(errMsg);
            }
        }
        if (queryType == QUERY_DML_TYPE.DELETE) {
            if (PublicTadpoleDefine.YES_NO.YES.name().equals(userDB.getDbAccessCtl().getDelete_locl())) {
                throw new Exception(errMsg);
            }
        }
    }

    java.sql.Connection javaConn = null;
    Statement statement = null;

    try {
        if (reqQuery.isAutoCommit()) {
            SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
            javaConn = client.getDataSource().getConnection();
        } else {
            javaConn = TadpoleSQLTransactionManager.getInstance(userEmail, userDB);
        }
        statement = javaConn.createStatement();

        int count = 0;
        for (String strQuery : listQuery) {
            //  ? commit? rollback?    ???
            if (!TransactionManger.calledCommitOrRollback(reqQuery.getSql(), userEmail, userDB)) {

                if (StringUtils.startsWithIgnoreCase(strQuery.trim(), "CREATE TABLE")) { //$NON-NLS-1$
                    strQuery = StringUtils.replaceOnce(strQuery, "(", " ("); //$NON-NLS-1$ //$NON-NLS-2$
                }

            }
            statement.addBatch(strQuery);

            if (++count % intCommitCount == 0) {
                statement.executeBatch();
                count = 0;
            }
        }
        statement.executeBatch();
    } catch (Exception e) {
        logger.error("Execute batch update", e); //$NON-NLS-1$
        throw e;
    } finally {
        try {
            statement.close();
        } catch (Exception e) {
        }

        if (reqQuery.isAutoCommit()) {
            try {
                javaConn.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.github.geequery.codegen.PackageReplacer.java

private boolean processUnit(CompilationUnit unit) {
    if (isTopCommentRemover)
        return true;
    final Holder<Boolean> flag = new Holder<Boolean>(false);
    VoidVisitorAdapter<String> visitor = new VoidVisitorAdapter<String>() {
        @Override//w w w  .  j ava  2  s. co  m
        public void visit(ImportDeclaration n, String arg) {
            String oldName = n.getName().toString();
            if (oldName.startsWith(from)) {
                n.setName(new NameExpr(StringUtils.replaceOnce(oldName, from, to)));
                flag.set(true);
            }
        }

        @Override
        public void visit(PackageDeclaration n, String arg) {
            String oldName = n.getName().toString().concat(".");
            if (oldName.startsWith(from)) {
                String newStr = StringUtils.replaceOnce(oldName, from, to);
                n.setName(new NameExpr(newStr.substring(0, newStr.length() - 1)));
                flag.set(true);
            }
        }

        @Override
        public void visit(ClassOrInterfaceType n, String arg) {
            if (n.getScope() == null)
                return;
            String oldName = n.getScope().toString().concat(".");
            if (oldName.startsWith(from)) {
                String newStr = StringUtils.replaceOnce(oldName, from, to);
                n.setScope(new ClassOrInterfaceType(newStr.substring(0, newStr.length() - 1)));
                flag.set(true);
            }
        }
    };
    visitor.visit(unit, null);
    boolean b = flag.get();
    return b;
}