Example usage for java.lang String replaceFirst

List of usage examples for java.lang String replaceFirst

Introduction

In this page you can find the example usage for java.lang String replaceFirst.

Prototype

public String replaceFirst(String regex, String replacement) 

Source Link

Document

Replaces the first substring of this string that matches the given regular expression with the given replacement.

Usage

From source file:gov.nih.nci.cabig.caaers.utils.DateUtils.java

/**
 * Validate a date to be a valid calendar date.
 * Input may come with date "00" which means the date was not indicated,
 * in which case we are going to use 01 just for validation purposes.
 *
 * @param date - the date to be validates
 * @return boolean - true if the date is valid, false otherwise
 *
 * *//*from w  w w .j  ava  2 s . com*/
public static boolean isValidDate(String date) {
    String cloneDate = null;

    if (date.substring(3, 5).equals("00")) {
        cloneDate = date.replaceFirst("/00/", "/01/");
    } else
        cloneDate = new String(date);

    SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);

    Date testDate;
    try {
        testDate = sdf.parse(cloneDate);
    } catch (ParseException e) {
        return false;
    }

    if (!sdf.format(testDate).equals(cloneDate)) {
        return false;
    }

    return true;
}

From source file:las.DBConnector.java

/**
 * Load CSV test data into SQL Table/*from   ww w .j a v a  2s . c  o  m*/
 *
 * example for clearFirst: boolean check =
 * DBConnector.checkDataExistedInTable("MEMBERS");
 *
 * if (check) { DBConnector.loadCSVIntoTable("src/resources/members.csv",
 * "MEMBERS", true); System.out.println("Test data inserted into MEMBERS
 * table"); }
 *
 * ignore createNewReader, since it uses for loadCSVIntoTable, don't modify
 * it
 *
 * Getter and Setter provided for Separator to set your own separator inside
 * your CSV File
 *
 * @param csvFile : src/resources/xxx.csv (put your csv file under this
 * path)
 * @param tableName: TABLENAME (All in capital letters)
 * @param clearFirst true = if data not existed in SQL Table, write test
 * data inside false = if data exisited in SQL Table, don't write again.
 * @throws java.lang.Exception
 */
public static void loadCSVIntoTable(String csvFile, String tableName, boolean clearFirst) throws Exception {

    CSVReader csvReader = null;
    if (null == DBConnector.conn) {
        throw new Exception("Not a valid connection.");
    }
    try {

        csvReader = DBConnector.getInstance().createNewReader(csvFile);

    } catch (ClassNotFoundException | SQLException | FileNotFoundException e) {
        e.printStackTrace();
        throw new Exception("Error occured while executing file. " + e.getMessage());
    }

    String[] headerRow = csvReader.readNext();

    if (null == headerRow) {
        throw new FileNotFoundException(
                "No columns defined in given CSV file." + "Please check the CSV file format.");
    }

    String questionmarks = StringUtils.repeat("?,", headerRow.length);
    questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1);

    String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
    query = query.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
    query = query.replaceFirst(VALUES_REGEX, questionmarks);

    String[] nextLine;
    PreparedStatement ps = null;
    try {
        conn.setAutoCommit(false);
        ps = conn.prepareStatement(query);

        if (clearFirst) {
            //delete data from table before loading csv
            conn.createStatement().execute("DELETE FROM " + tableName);
        }

        final int batchSize = 1000;
        int count = 0;
        Date date = null;
        while ((nextLine = csvReader.readNext()) != null) {

            if (null != nextLine) {
                int index = 1;
                for (String string : nextLine) {
                    date = DateUtil.convertToDate(string);
                    if (null != date) {
                        ps.setDate(index++, new java.sql.Date(date.getTime()));
                    } else {
                        ps.setString(index++, string);
                    }
                }
                ps.addBatch();
            }
            if (++count % batchSize == 0) {
                ps.executeBatch();
            }
        }
        ps.executeBatch(); // insert remaining records
        conn.commit();
    } catch (SQLException e) {
        conn.rollback();
        e.printStackTrace();
        throw new Exception("Error occured while loading data from file to database." + e.getMessage());
    } finally {
        if (null != ps) {
            ps.close();
        }

        csvReader.close();
    }
}

From source file:ch.njol.skript.expressions.ExprChatFormat.java

@SuppressWarnings({ "null" }) //First parameter is marked as @NonNull and String#replaceAll won't return null
private static String convertToFriendly(String format) {
    format = format.replaceAll("%%", "%").replaceAll("%1\\$s", "[player]").replaceAll("%2\\$s", "[message]");
    //Format uses %s instead of %1$s and %2$s
    if (format.contains("%s")) {
        if (StringUtils.countMatches(format, "%s") >= 2) {
            // Format uses two %s, the order is player, message
            format = format.replaceFirst("%s", "[player]");
            format = format.replaceFirst("%s", "[message]");
        } else {/*from w  w w  .j a  v a2s .  co  m*/
            // Format mixes %<number>$s and %s
            format = format.replaceFirst("%s",
                    (format.contains("[player]") || format.contains("%1$s") ? "[message]" : "[player]"));
        }
    }
    return format;
}

From source file:org.jdal.dao.jpa.JpaUtils.java

/**
 * Create a count query string from a query string
 * @param queryString string to parse/*from   www  . j a  v  a  2  s  .  c om*/
 * @return the count query string
 */
public static String createCountQueryString(String queryString) {
    return queryString.replaceFirst("^.*(?i)from", "select count (*) from ");
}

From source file:io.syndesis.jsondb.impl.JsonRecordSupport.java

static int fromLexSortableStringToInt(String value, char marker) {
    // Trim the initial markers.
    String remaining = value.replaceFirst("^" + Pattern.quote(String.valueOf(marker)) + "+", "");

    int rc = 1;/*  w  w  w. ja  v  a  2 s.co m*/
    while (!remaining.isEmpty()) {
        String x = remaining.substring(0, rc);
        remaining = remaining.substring(rc);
        rc = Integer.parseInt(x);
    }

    return rc;
}

From source file:it.geosolutions.geobatch.destination.common.utils.RemoteBrowserUtils.java

/**
 * Clean first separator for {@link RemoteBrowserProtocol#ftp} protocol
 * // w  ww.j a va2  s. c  o  m
 * @param path absolute remote path, for example: '/path/to/file'
 * @return path without starter '/', for example: 'path/to/file'
 */
private static String cleanRoot(String path) {
    if (path.startsWith("/")) {
        return path.replaceFirst("/", "");
    } else {
        return path;
    }
}

From source file:bammerbom.ultimatecore.bukkit.UltimateCommands.java

public static void onCmd(final CommandSender sender, Command cmd, String label, final String[] args) {
    if (Overrider.checkOverridden(sender, cmd, label, args)) {
        return;//  w  w  w .j  a v  a 2  s .  co  m
    }
    if (label.startsWith("ultimatecore:")) {
        label = label.replaceFirst("ultimatecore:", "");
    }
    for (UltimateCommand cmdr : cmds) {
        if (label.equals(cmdr.getName()) || cmdr.getAliases().contains(label)) {
            cmdr.run(sender, label, args);
            break;
        }
    }
}

From source file:gov.nih.nci.cananolab.util.StringUtils.java

/**
 * Convert to upper case the first letter of each word in the input. Spaces are preserved.
 * @param strWithWords//from  w w  w. ja  v a  2 s.  c  om
 * @return
 */
public static String getCamelCaseFormatInWords(String strWithWords) {
    if (strWithWords == null)
        return strWithWords;

    String[] words = strWithWords.split(" ");
    StringBuilder sb = new StringBuilder();
    for (String word : words) {
        char first = word.charAt(0);
        String upper = word.replaceFirst(String.valueOf(first), String.valueOf(Character.toUpperCase(first)));
        sb.append(upper).append(" ");
    }

    return sb.toString().trim();
}

From source file:org.unitedinternet.cosmo.dav.caldav.report.MultigetReport.java

private static String updateHrefElementWithRequestUrlUUID(Element hrefElement, String davHref,
        String resourceUUID) {/*from  w  ww.  j  a va  2 s.  c  om*/
    if (StringUtils.isNotEmpty(resourceUUID)) {
        Matcher davEmailMatcher = HREF_EMAIL_PATTERN.matcher(davHref);
        if (davEmailMatcher.find()) {
            String email = davEmailMatcher.group(0);
            String newHref = davHref.replaceFirst(email.replaceAll("/", ""), resourceUUID.replaceAll("/", ""));
            hrefElement.getFirstChild().setNodeValue(newHref);
            return newHref;
        }
    }
    return davHref;
}

From source file:com.sec.ose.osi.sdk.protexsdk.bom.BOMReportAPIWrapper.java

public static ArrayList<IdentifiedFilesRow> getIdentifiedFilesFromBOMReport(String projectName,
        UIResponseObserver observer) {/* w w w  .  ja va 2s . c om*/

    log.debug("createIdentifiedFilewRowList");

    String msgHead = "Creating Identified Files Sheet: - " + projectName + "\n";
    observer.setMessageHeader(msgHead);

    // get Identified Files
    String pMessage = msgHead + " > Getting [Identified Files] information from server.\n";
    observer.pushMessage(pMessage);
    ReportEntityList identifiedFilesEntList = ReportAPIWrapper.getIdentifiedFiles(projectName, observer, true);
    if (identifiedFilesEntList == null)
        return null;
    if (identifiedFilesEntList.size() == 0)
        return null;

    // get Compare Code Matches
    pMessage = msgHead + " > Getting [Compare Code Matches] information from server.\n";
    observer.pushMessage(pMessage);
    ReportEntityList compareCodeMatches = ReportAPIWrapper.getCompareCodeMatches(projectName, observer, true);
    if (compareCodeMatches == null)
        return null;
    if (compareCodeMatches.size() == 0)
        return null;

    log.debug("create IdentifiedFilesRow");
    HashSet<String> duplicateCheckSet = new HashSet<String>();
    ArrayList<IdentifiedFilesRow> IdentifiedFilesRowList = new ArrayList<IdentifiedFilesRow>(
            identifiedFilesEntList.size());
    for (ReportEntity entity : identifiedFilesEntList) {

        String filePath = entity.getValue(ReportInfo.IDENTIFIED_FILES.FILE_FOLDER_NAME);
        String componentName = entity.getValue(ReportInfo.IDENTIFIED_FILES.COMPONENT);
        String componentVersion = entity.getValue(ReportInfo.IDENTIFIED_FILES.VERSION);
        String fileComment = entity.getValue(ReportInfo.IDENTIFIED_FILES.COMMENT);
        String fileLicense = parseFileLicense(entity.getValue(ReportInfo.IDENTIFIED_FILES.LICENSE));
        String discoveryType = entity.getValue(ReportInfo.IDENTIFIED_FILES.DISCOVERY_TYPE);

        if (componentName.equals("") && componentVersion.equals("") && fileLicense.equals("")) {
            continue;
        }

        String duplicateCheck = filePath + componentName + fileLicense;
        if (duplicateCheckSet.contains(duplicateCheck) == true) {
            continue;
        }

        duplicateCheckSet.add(duplicateCheck);
        IdentifiedFilesRowList.add(new IdentifiedFilesRow(projectName, filePath, componentName, fileLicense,
                discoveryType, fileComment));
    }

    log.debug("update code match info");
    HashMap<String, CodeMatchEnt> codeMatchInfoMap = new HashMap<String, CodeMatchEnt>(
            compareCodeMatches.size());
    for (ReportEntity entity : compareCodeMatches) {
        String fullPath = entity.getValue(ReportInfo.COMPARE_CODE_MATCHES.FULL_PATH);
        String codeMatchCnt = entity.getValue(ReportInfo.COMPARE_CODE_MATCHES.CODE_MATCH_COUNT);
        String url = entity.getValue(ReportInfo.COMPARE_CODE_MATCHES.COMPARE_CODE_MATCHES_LINK);

        url = url.replaceFirst("127.0.0.1", LoginSessionEnt.getInstance().getProtexServerIP());

        codeMatchInfoMap.put(fullPath, new CodeMatchEnt(fullPath, codeMatchCnt, url));
    }
    for (IdentifiedFilesRow fileEnt : IdentifiedFilesRowList) {
        CodeMatchEnt codeMatchEnt = codeMatchInfoMap.get(fileEnt.getFullPath());
        if (CODE_MATCH.equals(fileEnt.getDiscoveryType())) {
            fileEnt.setUrl(codeMatchEnt.url);
            fileEnt.setCodeMatchCnt(codeMatchEnt.codeMatchCnt);
        }
    }

    String msg = IdentifiedFilesRowList.size() + " files are loaded.";
    observer.pushMessage(msg);
    log.debug(msg);

    log.debug("start Garbage collector in BOMReportAPIWrapper");
    System.gc();
    log.debug("finish Garbage collector in BOMReportAPIWrapper");

    return IdentifiedFilesRowList;

}