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:org.apache.rya.indexing.smarturi.SmartUriAdapter.java

private static String removeTypePrefixFromUri(final String uriString, final String typePrefix) {
    final String localName = new URIImpl(uriString).getLocalName();
    final String beginning = StringUtils.removeEnd(uriString, localName);
    final String replacement = localName.replaceFirst(typePrefix + ".", "");
    final String formattedUriString = beginning + replacement;
    return formattedUriString;
}

From source file:msearch.filmeSuchen.sender.MediathekSrf.java

public static boolean ping(String url) throws SRFException {

    url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

    try {/*from   ww  w  .j a  va 2s.  com*/
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(1000); //1000ms timeout for connect, read timeout to infinity
        connection.setReadTimeout(0);
        int responseCode = connection.getResponseCode();
        connection.disconnect();
        if (responseCode > 399 && responseCode != HttpURLConnection.HTTP_NOT_FOUND) {

            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                throw new SRFException("TEST");
            }
            //MSLog.debugMeldung("SRF: " + responseCode + " + responseCode " + "Url " + url);
            return false;
        }
        return (200 <= responseCode && responseCode <= 399);

    } catch (IOException exception) {
        return false;
    }
}

From source file:de.escidoc.core.common.business.indexing.GsearchHandler.java

/**
 * Delete Index-Lock./*from   w  ww.j  a  v  a2 s.  co m*/
 * 
 * @param response
 *            Errormessage that contains the path to the lockfile
 */
private static void deleteLock(final String response) {
    try {
        String lockfilePath = response.replaceFirst("(?s).*Lock@", "");
        lockfilePath = lockfilePath.replaceFirst("(?s)<.*", "");
        final File file = new File(lockfilePath);
        file.delete();
    } catch (final Exception e) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("Error on deleting lock.");
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Error on deleting lock.", e);
        }
    }
}

From source file:info.varden.anatychia.Main.java

public static String jsonDecode(String json) {
    String p1 = json.replace("\\\"", "\"").replace("\\/", "/").replace("\\b", "\b").replace("\\f", "\f")
            .replace("\\n", "\n").replace("\\t", "\t");
    Pattern p = Pattern.compile("\\\\u[0-9A-Fa-f]{4}");
    Matcher m = p.matcher(p1);/* ww  w.  ja  va 2 s .c  om*/
    while (m.find()) {
        char c = (char) Integer.parseInt(m.group().substring(2), 16);
        p1 = p1.replaceFirst(Pattern.quote(m.group()), String.valueOf(c));
    }
    p1 = p1.replace("\\\\", "\\");
    return p1;
}

From source file:fi.mikuz.boarder.util.FileProcessor.java

private static File replaceBoardPath(File file, File originalBoard, File newBoard) {
    if (file == null)
        return null;
    String filePath = file.getAbsolutePath();
    String originalBoardPath = originalBoard.getAbsolutePath();
    String newBoardPath = newBoard.getAbsolutePath();
    return new File(filePath.replaceFirst(originalBoardPath, newBoardPath));
}

From source file:com.rapidminer.gui.OperatorDocLoader.java

private static String customizeHTMLStringDirty(String HTMLString, String operatorIconPath) {
    HTMLString = HTMLString.replaceFirst("\\<[^\\>]*>",
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");

    // customize operator-name

    String newHtmlString = "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" dir=\"ltr\">" + "<head>"
            + "<table cellpadding=0 cellspacing=0>" + "<tr><td>" + "<img src=\"" + operatorIconPath
            + "\" /></td>" + "<td width=\"5\">" + "</td>" + "<td>"
            + "<h2 class=\"firstHeading\" id=\"firstHeading\">" + CURRENT_OPERATOR_NAME_READ_FROM_RAPIDWIKI;

    if (CURRENT_OPERATOR_PLUGIN_NAME != null && CURRENT_OPERATOR_PLUGIN_NAME.length() > 0) {
        newHtmlString += "<small style=\"font-size:70%;color:#5F5F5F;font-weight:normal;\"> ("
                + CURRENT_OPERATOR_PLUGIN_NAME + ")</small>";
    }/*from   www  .  jav  a 2 s . c o  m*/

    newHtmlString += "</h2>" + "</td></tr>" + "</table>" + "<hr noshade=\"true\">" + "</head>";

    HTMLString = HTMLString.replaceFirst(CORRECT_HTML_STRING_DIRTY, newHtmlString);

    // customize all headlines
    HTMLString = HTMLString.replaceAll("<h2>", "<h4>");
    HTMLString = HTMLString.replaceAll("</h2>", "</h4>");

    // replace all painted circles by icons
    HTMLString = HTMLString.replaceAll("<ul>", "<ul class=\"ports\">");

    // removing all <div class="visualClear"/>
    HTMLString = HTMLString.replaceAll("<div class=\"visualClear\"/>", "");

    // regex: \[theTag\][\w\s]*\[/theTag\]
    Pattern pattern = Pattern.compile("\\</div\\>[\\s]*\\<h4\\>|" + "\\</p\\>[\\s]*\\<h4\\>|"
            + "\\</h4\\>[\\s]*\\<h4\\>|" + "\\</ul\\>[\\s]*\\<h4\\>|" + "\\</h4\\>[\\s]*\\</div\\>");
    Matcher matcher = pattern.matcher(HTMLString);
    while (matcher.find()) {
        String match = matcher.group();
        String replaceString = StringUtils.EMPTY;
        if (match.startsWith("</div")) {
            replaceString = "</div><br/><h4>";
        } else if (match.startsWith("</p")) {
            replaceString = "</p><br/><h4>";
        } else if (match.startsWith("</h4") && !match.contains("div")) {
            replaceString = "</h4><br/><h4>";
        } else if (match.startsWith("</ul")) {
            replaceString = "</ul><br/><h4>";
        } else if (match.startsWith("</h4") && match.contains("div")) {
            replaceString = "</h4><br/><div>";
        }
        HTMLString = HTMLString.replace(match, replaceString);
    }

    // replace <pre...> with <table...> because pre is not supported
    HTMLString = HTMLString.replaceAll("<pre",
            "<table class=pre border=0 bordercolor=black style=border-style:dashed;");
    // width=\"100%\"
    // border-collapse:separate;
    HTMLString = HTMLString.replaceAll("</pre", "</table");

    return HTMLString;
}

From source file:com.asual.lesscss.ResourcePackage.java

public static ResourcePackage fromString(String source) {
    if (!StringUtils.isEmpty(source)) {
        try {//from  w  ww.  ja v a 2  s  .  c  o  m
            String key;
            String path = null;
            String extension = null;
            int slashIndex = source.lastIndexOf("/");
            int dotIndex = source.lastIndexOf(".");
            if (dotIndex != -1 && slashIndex < dotIndex) {
                extension = source.substring(dotIndex + 1);
                path = source.substring(0, dotIndex);
            } else {
                path = source;
            }
            if (extension != null && !extensions.contains(extension)) {
                return null;
            }
            String[] parts = path.replaceFirst("^/", "").split(SEPARATOR);
            if (cache.containsValue(source)) {
                key = getKeyFromValue(cache, source);
            } else {
                key = parts[parts.length - 1];
                byte[] bytes = null;
                try {
                    bytes = Base64.decodeBase64(key.getBytes(ENCODING));
                    bytes = inflate(bytes);
                } catch (Exception e) {
                }
                key = new String(bytes, ENCODING);
            }
            String[] data = key.split(NEW_LINE);
            ResourcePackage rp = new ResourcePackage((String[]) ArrayUtils.subarray(data, 1, data.length));
            int mask = Integer.valueOf(data[0]);
            if ((mask & NAME_FLAG) != 0) {
                rp.setName(parts[0]);
            }
            if ((mask & VERSION_FLAG) != 0) {
                rp.setVersion(parts[rp.getName() != null ? 1 : 0]);
            }
            rp.setExtension(extension);
            return rp;
        } catch (Exception e) {
        }
    }
    return null;
}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

/**
 * Sends an HTTP GET request to a url/*from w  w w.  j  a va  2s. c o m*/
 *
 * @param urlStr            - The URL of the server. (Example: " http://www.yahoo.com/search")
 * @param file              the output file. If it is a folder, it tries to get the file name from the header.
 * @param requestParameters - all the request parameters (Example: "param1=val1&param2=val2").
 *                          Note: This method will add the question mark (?) to the request -
 *                          DO NOT add it yourself
 * @param user              user.
 * @param password          password.
 * @return the file written.
 * @throws Exception if something goes wrong.
 */
public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user,
        String password) throws Exception {
    if (requestParameters != null && requestParameters.length() > 0) {
        urlStr += "?" + requestParameters;
    }
    HttpURLConnection conn = makeNewConnection(urlStr);
    conn.setRequestMethod("GET");
    // conn.setDoOutput(true);
    conn.setDoInput(true);
    // conn.setChunkedStreamingMode(0);
    conn.setUseCaches(false);

    if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) {
        conn.setRequestProperty("Authorization", getB64Auth(user, password));
    }
    conn.connect();

    if (file.isDirectory()) {
        // try to get the header
        String headerField = conn.getHeaderField("Content-Disposition");
        String fileName = null;
        if (headerField != null) {
            String[] split = headerField.split(";");
            for (String string : split) {
                String pattern = "filename=";
                if (string.toLowerCase().startsWith(pattern)) {
                    fileName = string.replaceFirst(pattern, "");
                    break;
                }
            }
        }
        if (fileName == null) {
            // give a name
            fileName = "FILE_" + TimeUtilities.INSTANCE.TIMESTAMPFORMATTER_LOCAL.format(new Date());
        }
        file = new File(file, fileName);
    }

    InputStream in = null;
    FileOutputStream out = null;
    try {
        in = conn.getInputStream();
        out = new FileOutputStream(file);

        byte[] buffer = new byte[(int) maxBufferSize];
        int bytesRead = in.read(buffer, 0, (int) maxBufferSize);
        while (bytesRead > 0) {
            out.write(buffer, 0, bytesRead);
            bytesRead = in.read(buffer, 0, (int) maxBufferSize);
        }
        out.flush();
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
        if (conn != null)
            conn.disconnect();
    }
    return file;
}

From source file:info.magnolia.importexport.DataTransporter.java

/**
 * The opposite of {@link #createExportPath(String)}.
 * I.e. given a path like this <code>.foo.bar..baz.test.....dir.baz....bar</code>, this method will produce <code>/foo/bar.baz/test../dir/baz..bar</code>.
 *//*from w w  w. j a  va 2 s  .  c  o  m*/
public static String revertExportPath(String exportPath) {
    if (".".equals(exportPath)) {
        return "/";
    }

    //TODO I have a feeling there's a simpler way to achieve our goal.
    Matcher matcher = DOT_NAME_PATTERN.matcher(exportPath);

    StringBuilder reversed = new StringBuilder(exportPath.length());

    while (matcher.find()) {
        String group = matcher.group();
        int dotsNumber = StringUtils.countMatches(group, ".");
        if (dotsNumber == 1) {
            reversed.append(group.replaceFirst("\\.", "/"));
        } else {
            String dots = StringUtils.substringBeforeLast(group, ".").replace("..", ".");
            String name = StringUtils.substringAfterLast(group, ".");
            reversed.append(dots);
            //if number is odd, the last dot has to be replaced with a slash
            if (dotsNumber % 2 != 0) {
                reversed.append("/");
            }
            reversed.append(name);
        }
    }
    return reversed.toString();
}

From source file:net.jmhertlein.alphonseirc.AlphonseBot.java

public static List<String> permute(String s) {
    List<String> ret = new LinkedList<>();
    if (s.isEmpty()) {
        ret.add("");
        return ret;
    }/*from  www .  jav a  2s.c o  m*/

    for (char c : s.toCharArray()) {
        for (String subPermute : permute(s.replaceFirst("[" + c + "]", ""))) {
            ret.add(c + subPermute);
        }
    }
    return ret;
}