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:com.norconex.collector.core.pipeline.importer.SaveDocumentStage.java

public static String urlToPath(final String url) {
    if (url == null) {
        return null;
    }/*from  ww w .j a v a 2 s .  c  om*/
    String sep = File.separator;
    if (sep.equals("\\")) {
        sep = "\\" + sep;
    }

    String domain = url.replaceFirst("(.*?)(://)(.*?)(/)(.*)", "$1_$3");
    domain = domain.replaceAll("[\\W]+", "_");
    String path = url.replaceFirst("(.*?)(://)(.*?)(/)(.*)", "$5");

    String[] segments = path.split("[\\/]");
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < segments.length; i++) {
        String segment = segments[i];
        if (StringUtils.isNotBlank(segment)) {
            boolean lastSegment = (i + 1) == segments.length;
            String[] segParts = splitLargeSegment(segment);
            for (int j = 0; j < segParts.length; j++) {
                String segPart = segParts[j];
                if (b.length() > 0) {
                    b.append(File.separatorChar);
                }
                // Prefixes directories or files with different letter
                // to ensure directory and files can't have the same 
                // names (github #44).
                if (lastSegment && (j + 1) == segParts.length) {
                    b.append("f.");
                } else {
                    b.append("d.");
                }
                b.append(FileUtil.toSafeFileName(segPart));
            }
        }
    }
    if (b.length() > 0) {
        return "d." + domain + File.separatorChar + b.toString();
    }
    return "f." + domain;
}

From source file:packjacket.StaticUtils.java

/**
 * Uploads a file to the PackJacket webserver
 * @param f the fiel to upload//from  www  .j av  a  2  s.  c om
 * @return the id of the log file, or 0 if it crashed
 */
public static long uploadLog(File f) {
    long id = 0;
    try {
        //Sets up the HTTP interaction
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost("http://packjacket.sourceforge.net/log/up.php");

        //Adds file to a POST
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(f, "image/jpeg");
        mpEntity.addPart("uploadedfile", cbFile);

        //Uplaods file
        httppost.setEntity(mpEntity);
        RunnerClass.logger.info("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        //Receives the status message
        RunnerClass.logger.info("Status: " + response.getStatusLine());
        if (resEntity != null) {
            //Get the id that the server reports
            String s = EntityUtils.toString(resEntity);
            RunnerClass.logger.info("Result: " + s);
            id = Long.parseLong(s.replaceFirst("222 ", "").replace("\n", ""));
        }
        if (resEntity != null)
            resEntity.consumeContent();

        //Close connection
        httpclient.getConnectionManager().shutdown();
    } catch (Exception ex) {
        RunnerClass.logger.info("Internet not available");
    }
    return id;
}

From source file:Main.java

public static <T> String join(Collection<T> col, String separator) {
    String ret = "";
    if (col != null && col.size() > 0) {
        for (Object x : col) {
            if (x instanceof java.lang.String) {
                ret += separator + (String) x;
            } else {
                ret += separator + x.toString();
            }//  ww w.j  a  va 2  s  .c om
        }
    }
    return ret.replaceFirst(separator, "");

}

From source file:com.reactivetechnologies.platform.rest.MethodInvocationHandler.java

/**
 * Generate the async request ID//from w w w .  j  a va 2 s. c o m
 * @param event
 * @return
 */
static String makeAsyncRequestKey(Event<?> event) {
    String key = Digestor.md5().addLong(event.hashBytes()).addString(event.getCorrelationId()).toLongString();

    return key.startsWith("-") ? key.replaceFirst("-", "0") : key;

}

From source file:net.bulletin.pdi.xero.step.support.Helpers.java

/**
 * <p>This can be used with keys and so on in order to obfuscate the string for the logs.</p>
 *///from  w w  w.  jav  a  2 s.c  o m

public static String obfuscateAuthenticationDetailForLog(String value) {
    if (null == value || value.length() < 8) {
        return "?";
    }

    // some certificates are presented with lines such as;
    // -----BEGIN PRIVATE KEY----- at the start and
    // -----END PRIVATE KEY----- at the end; this will remove those.

    value = value.replaceFirst("^[\\s-]+[A-Z ]+[\\s-]+", "").replaceAll("[\\s-]+[A-Z ]+[\\s-]+$", "");
    return value.substring(0, 2) + "..." + value.substring(value.length() - 2, value.length());
}

From source file:gridool.db.partitioning.phihash.monetdb.MonetDBCsvLoadOperation.java

private static String getCopyIntoQuery(@Nonnull final String query, final long numRecords) {
    return query.replaceFirst("COPY ", "COPY " + numRecords + " RECORDS ");
}

From source file:cz.autoclient.github.local.ReleaseFileLocal.java

public static long sizeToNumber(String size) {
    //System.out.println("Parsing size!");
    // Space divides the size and the multipier (k, M, G...)
    int firstSpace = size.indexOf(' ');
    double multiplier = 1;
    // replace bytes to leae the multiplier alone
    size = size.replaceFirst("\\s*(B|b|Bytes)\\s*$", "");
    //System.out.println("Size: "+size);
    // If the space wasn't replaced there's stull some stuff
    if (firstSpace < size.length()) {
        //get the stuff after the space (if any)
        String unit = size.substring(firstSpace + 1);
        switch (unit) {
        case "T":
            multiplier = 1e12;/* w  w  w .  j  a  va  2 s.co m*/
            break;
        case "G":
            multiplier = 1e9;
            break;
        case "M":
            multiplier = 1e6;
            break;
        case "k":
            multiplier = 1e3;
            break;
        }
    }
    return (long) (Double.parseDouble(size.substring(0, firstSpace)) * multiplier);
}

From source file:it.webappcommon.lib.StringHelper.java

public static String removePrefix(String aString, String prefix, String separator) {

    String res = aString;

    if (res.indexOf(prefix + separator) > -1) {

        res = res.replaceFirst(prefix + separator, "");

        logger.debug(String.format("Rimosso %s da: %s", prefix + separator, prefix));
    }/* w  w w.j a va  2  s.co  m*/

    return res;
}

From source file:Main.java

/**
 * Extracts aggregation-definition-prim-keys out of the table-names of the given sql.
 *
 * @param sql sql-statement of report-definition.
 * @return Collection with aggregation-definition prim keys.
 *//*from   w w w.j a  va  2  s.co m*/
public static Collection<String> extractAggregationPrimKeysFromSql(final String sql) {
    final Collection<String> primKeys = new ArrayList<String>();
    if (sql != null) {
        String workSql = sql.replaceAll("\\s+", " ");
        workSql = workSql.replaceAll("\\s+", " ");
        boolean condition = false;
        if (workSql.matches("(?i).* (where|order by|group by) .*")) {
            condition = true;
        }
        final String fromClause = condition
                ? workSql.replaceFirst("(?i).*?from(.*?)(where|order by|group by).*", "$1")
                : workSql.replaceFirst("(?i).*?from(.*)", "$1");
        final String[] tables = fromClause.split(",");
        for (String table : tables) {
            if (table.matches(".*?_.*")) {
                table = table.replaceFirst(".*?\\.", "").trim();
                if (table.startsWith("_")) {
                    table = table.replaceFirst("_", "");
                }
                primKeys.add(table.replaceFirst("(.*?)_.*", "$1"));
            }
        }
    }
    return primKeys;
}

From source file:Main.java

public static String mergeUri(String uri, Object[] args, SparseArray<String> paramKeys,
        Map<String, String> methodStaticUri, Map<String, String> globalParamKeys) {

    if (paramKeys != null && paramKeys.size() > 0 && args != null && args.length > 0) {
        for (int i = 0, key = paramKeys.keyAt(i); i < paramKeys.size(); key = paramKeys.keyAt(++i)) {
            uri = uri.replaceFirst(":" + paramKeys.get(key), String.valueOf(args[key]));
        }//from ww w .j a  v a2s . c  om
    }
    if (methodStaticUri != null && methodStaticUri.size() > 0) {
        for (Map.Entry<String, String> e : methodStaticUri.entrySet()) {
            uri = uri.replaceFirst(":" + e.getKey(), e.getValue());
        }
    }
    if (globalParamKeys != null && globalParamKeys.size() > 0) {
        for (Map.Entry<String, String> e : globalParamKeys.entrySet()) {
            uri = uri.replaceFirst(":" + e.getKey(), e.getValue());
        }
    }

    return uri;
}