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.http.util.PathUtils.java

public static String urlToPath(final String url) {
    if (url == null) {
        return null;
    }//from   w ww. ja v a2s .  c  o  m
    String sep = File.separator;
    if (sep.equals("\\")) {
        sep = "\\" + sep;
    }

    String domain = url.replaceFirst("(.*?)(://)(.*?)(/)(.*)", "$1_$3");
    domain = domain.replaceAll("[\\W]+", "_");
    String path = url.replaceFirst("(.*?)(://)(.*?)(/)(.*)", "$5");
    path = path.replaceAll("[\\W]+", "_");
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < path.length(); i++) {
        if (i % PATH_SEGMENT_SIZE == 0) {
            b.append(sep);
        }
        b.append(path.charAt(i));
    }
    path = b.toString();

    //TODO is truncating after 256 a risk of creating false duplicates?
    if (path.length() > MAX_PATH_LENGTH) {
        path = StringUtils.right(path, MAX_PATH_LENGTH);
        if (!path.startsWith(File.separator)) {
            path = File.separator + path;
        }
    }
    return domain + path;
}

From source file:cloudlens.parser.FileReader.java

public static InputStream fetchFile(String urlString) {
    try {/*from ww w .  j a va 2s .co  m*/
        InputStream inputStream;
        URL url;
        if (urlString.startsWith("local:")) {
            final String path = urlString.replaceFirst("local:", "");
            inputStream = Files.newInputStream(Paths.get(path));
        } else if (urlString.startsWith("file:")) {
            url = new URL(urlString);
            inputStream = Files.newInputStream(Paths.get(url.toURI()));
        } else if (urlString.startsWith("http:") || urlString.startsWith("https:")) {
            url = new URL(urlString);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            final Matcher matcher = Pattern.compile("//([^@]+)@").matcher(urlString);
            if (matcher.find()) {
                final String encoding = Base64.getEncoder().encodeToString(matcher.group(1).getBytes());
                conn.setRequestProperty("Authorization", "Basic " + encoding);
            }
            conn.setRequestMethod("GET");
            inputStream = conn.getInputStream();
        } else {
            throw new CLException("supported protocols are: http, https, file, and local.");
        }
        return inputStream;
    } catch (IOException | URISyntaxException e) {
        throw new CLException(e.getMessage());
    }
}

From source file:Main.java

/**
 * Remove the characters caused by Saxon. This is necessary if you parse an
 * attribute because XPath then returns the name of the attribute.
 * /*from w w w .  ja  v a 2 s .c o  m*/
 * @param input
 *            - the return value of Saxon.
 * @return the cleaned String.
 */
public static String removeAttributeChars(final String input) {
    if (input == null) {
        throw new IllegalArgumentException(
                "The value for the parameter input in removeAttributeChars mustn't be empty.");
    }
    // Ex. value: []
    String ret = input.replaceFirst("(\\w)+=(\")", "");
    int lastPos = input.lastIndexOf("\"");
    if (input.length() != 0 && lastPos == input.length() - 1) {
        ret = ret.substring(0, ret.length() - 1);
    }
    return ret;
}

From source file:com.mbrlabs.mundus.editor.utils.Log.java

private static String completeMsg(String msg, Object... params) {
    for (Object p : params)
        msg = msg.replaceFirst("\\{\\}", String.valueOf(p));
    return msg;//from   w w  w. j av  a 2 s.c  o  m
}

From source file:fi.vm.kapa.identification.shibboleth.extauthn.util.CertificateUtil.java

public static X509Certificate getCertificate(String pemCertificate) {
    X509Certificate newCert = null;
    try {/*from  w  ww .  jav  a 2 s.c  o  m*/
        // Add \r after cert header field, Cert API needs this (Legacy method, Apache2-provided cert)
        pemCertificate = pemCertificate.replaceFirst(X509_PEM_HEADER, X509_PEM_HEADER + "\r");

        // Add X509 header and footer, Cert API needs this (SCS method, SCS-provided certificate)
        if (!pemCertificate.contains(X509_PEM_HEADER)) {
            pemCertificate = X509_PEM_HEADER + "\r" + pemCertificate + "\r" + X509_PEM_FOOTER;
        }

        if (StringUtils.isNotBlank(pemCertificate)) {
            InputStream in = new ByteArrayInputStream(pemCertificate.getBytes());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            newCert = (X509Certificate) cf.generateCertificate(in);
        }
    } catch (final CertificateException | NullPointerException e) {
        logger.warn("Error getting client certificate from request", e);
    }
    return newCert;
}

From source file:com.worldline.easycukes.commons.helpers.FileHelper.java

/**
 * Extracts the content of a zip folder in a specified directory
 *
 * @param from a {@link String} representation of the URL containing the zip
 *             file to be unzipped//w w  w .  ja  v a2 s .c o  m
 * @param to   the path on which the content should be extracted
 * @throws IOException if anything's going wrong while unzipping the content of the
 *                     provided zip folder
 */
public static void unzip(@NonNull String from, @NonNull String to, boolean isRemote) throws IOException {
    @Cleanup
    ZipInputStream zip = null;
    if (isRemote)
        zip = new ZipInputStream(new FileInputStream(from));
    else
        zip = new ZipInputStream(FileHelper.class.getResourceAsStream(from));
    log.debug("Extracting zip from: " + from + " to: " + to);
    // Extract without a container directory if exists
    ZipEntry entry = zip.getNextEntry();
    String rootDir = "/";
    if (entry != null)
        if (entry.isDirectory())
            rootDir = entry.getName();
        else {
            final String filePath = to + entry.getName();
            // if the entry is a file, extracts it
            try {
                extractFile(zip, filePath);
            } catch (final FileNotFoundException fnfe) {
                log.warn(fnfe.getMessage(), fnfe);
            }
        }
    zip.closeEntry();
    entry = zip.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        String entryName = entry.getName();
        if (entryName.startsWith(rootDir))
            entryName = entryName.replaceFirst(rootDir, "");
        final String filePath = to + "/" + entryName;
        if (!entry.isDirectory())
            // if the entry is a file, extracts it
            try {
                extractFile(zip, filePath);
            } catch (final FileNotFoundException fnfe) {
                log.warn(fnfe.getMessage(), fnfe);
            }
        else {
            // if the entry is a directory, make the directory
            final File dir = new File(filePath);
            dir.mkdir();
        }
        zip.closeEntry();
        entry = zip.getNextEntry();
    }
    // delete the zip file if recovered from URL
    if (isRemote)
        new File(from).delete();
}

From source file:com.bluexml.side.clazz.service.alfresco.CommonServices.java

public static void log(EObject o, String message) {
    message = message.replaceFirst(Pattern.quote("{object}"), o.toString())
            .replaceFirst(Pattern.quote("{date}"), new Date().toString());
    System.out.println("CommonServices.log() :" + message);
}

From source file:com.leshazlewood.scms.cli.Main.java

private static File toFile(String path) {
    String resolved = path;//from ww w. j a  v a 2 s.  c  o m
    if (path.startsWith("~/") || path.startsWith(("~\\"))) {
        resolved = path.replaceFirst("\\~", System.getProperty("user.home"));
    }
    return new File(resolved);
}

From source file:Main.java

/**
 * Normalizes an absolute URI (lower scheme and host part)
 *
 * @param pString The absolute URI to be normalized
 *//*from ww w. j  a va  2  s  .  c  o m*/
/* package protected */static String normalizeAbsoluteURI(String pString) {

    int index = -1;

    /* lower the scheme part */
    if ((index = pString.indexOf(':')) == -1) {
        return pString;
    }
    String scheme = pString.substring(0, index);
    pString = pString.replaceFirst(scheme, scheme.toLowerCase());

    /* check the presence of "//" */
    if ((index = pString.indexOf("//", index)) == -1) {
        /* no // found, return */
        return pString;
    }

    /* lower the host part ( authority : [user@]host[:port] )*/
    index += 2;
    int indexStart = pString.indexOf("@", index);
    indexStart = (indexStart == -1) ? index : indexStart + 1;
    int indexEnd = pString.indexOf(indexStart, ':');
    if (indexEnd == -1) {
        if ((indexEnd = pString.indexOf("/", indexStart)) == -1) {
            indexEnd = pString.length();
        }
    }
    String host = pString.substring(indexStart, indexEnd);

    return pString.replaceFirst(host, host.toLowerCase());
}

From source file:biz.netcentric.cq.tools.actool.validators.Validators.java

public static boolean isValidRegex(String expression) {
    if (StringUtils.isBlank(expression)) {
        return true;
    }//  w  ww . j ava 2 s .  co  m
    boolean isValid = true;

    if (expression.startsWith("*")) {
        expression = expression.replaceFirst("\\*", "\\\\*");
    }
    try {
        Pattern.compile(expression);
    } catch (PatternSyntaxException e) {
        LOG.error("Error while validating rep glob: {} ", expression, e);
        isValid = false;
    }

    return isValid;
}