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:it.biztech.btable.util.Utils.java

public static IBasicFile getFile(String filePath, String basePath) {
    if (StringUtils.isEmpty(filePath)) {
        return null;
    }/*from ww  w.j  a va2s.c  o m*/

    IContentAccessFactory factory = PentahoPluginEnvironment.getInstance().getContentAccessFactory();
    String res = StringUtils.strip(filePath.toLowerCase(), "/");

    if (res.startsWith(BTableConstants.SYSTEM_DIR + "/")) {
        res = StringUtils.strip(res, BTableConstants.SYSTEM_DIR + "/");
        if (res.startsWith(BTableConstants.PLUGIN_SYSTEM_DIR.toLowerCase() + "/")) {
            filePath = filePath.replaceFirst(
                    BTableConstants.SYSTEM_DIR + "/" + BTableConstants.PLUGIN_SYSTEM_DIR + "/", "");
            return factory.getPluginSystemReader(basePath).fetchFile(filePath);
        } else {
            String pluginId = res.substring(0, filePath.indexOf("/"));
            filePath = filePath.replaceFirst(BTableConstants.SYSTEM_DIR + "/" + pluginId + "/", "");
            return factory.getOtherPluginSystemReader(pluginId, basePath).fetchFile(filePath);
        }
    } else if (res.startsWith(BTableConstants.PLUGIN_REPOSITORY_DIR.toLowerCase() + "/")) {
        filePath = filePath.replaceFirst(BTableConstants.PLUGIN_REPOSITORY_DIR + "/", "");
        return factory.getPluginRepositoryReader(basePath).fetchFile(filePath);
    } else {
        if (factory.getPluginSystemReader(basePath).fileExists(filePath)) {
            return factory.getPluginSystemReader(basePath).fetchFile(filePath);
        } else if (factory.getUserContentAccess(basePath).fileExists(filePath)) {
            return factory.getUserContentAccess(basePath).fetchFile(filePath);
        }
    }

    return null;
}

From source file:hydrograph.ui.propertywindow.widgets.utility.FilterOperationClassUtility.java

/**
 * Open selection dialog for Java files, File selection restricted to ".java" extension.
 * @param filterExtension/*from w  w  w  .j av  a  2 s.c om*/
 * @param fileName
 */
public static void browseJavaSelectionDialog(String filterExtension, Text fileName) {
    ResourceFileSelectionDialog dialog = new ResourceFileSelectionDialog("Project", "Select Java Class (.java)",
            new String[] { filterExtension });
    if (dialog.open() == IDialogConstants.OK_ID) {
        IResource resource = (IResource) dialog.getFirstResult();
        String filePath = resource.getRawLocation().toOSString();
        java.nio.file.Path path = Paths.get(filePath);
        String classFile = path.getFileName().toString();
        String name = "";
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String firstLine = reader.readLine();
            if (firstLine.contains(Constants.PACKAGE)) {
                name = firstLine.replaceFirst(Constants.PACKAGE, "").replace(";", "");
                if (!name.equalsIgnoreCase("")) {
                    name = name + "." + classFile.substring(0, classFile.lastIndexOf('.'));
                }

            } else {
                name = classFile.substring(0, classFile.lastIndexOf('.'));
            }

        } catch (IOException e) {
            logger.error("Unable to read file " + filePath, e);
        }
        fileName.setText(name.trim());
        filePath = resource.getRawLocation().toOSString();
        fileName.setData("path", resource.getFullPath().toString());
    }
}

From source file:com.tethrnet.manage.db.SessionAuditDB.java

/**
 * returns terminal logs for user session for host system
 *
 * @param sessionId     session id// w  w  w.  java2  s.c om
 * @param instanceId    instance id for terminal session
 * @return session output for session
 */
public static List<SessionOutput> getTerminalLogsForSession(Connection con, Long sessionId,
        Integer instanceId) {

    List<SessionOutput> outputList = new LinkedList<SessionOutput>();
    try {
        PreparedStatement stmt = con.prepareStatement(
                "select * from terminal_log where instance_id=? and session_id=? order by log_tm asc");
        stmt.setLong(1, instanceId);
        stmt.setLong(2, sessionId);
        ResultSet rs = stmt.executeQuery();
        String output = "";
        while (rs.next()) {
            output = output + rs.getString("output");
        }

        output = output.replaceAll("\\u0007|\u001B\\[K|\\]0;|\\[\\d\\d;\\d\\dm|\\[\\dm", "");
        while (output.contains("\b")) {
            output = output.replaceFirst(".\b", "");
        }
        DBUtils.closeRs(rs);

        SessionOutput sessionOutput = new SessionOutput();
        sessionOutput.setSessionId(sessionId);
        sessionOutput.setInstanceId(instanceId);
        sessionOutput.getOutput().append(output);

        outputList.add(sessionOutput);

        DBUtils.closeRs(rs);

        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    return outputList;

}

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Sends an HTTP GET request to a url//from   ww  w.j  a v  a 2 s .  com
 *
 * @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
 * @param password
 * @return the file written. 
 * @throws Exception 
 */
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) {
        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_" + LibraryConstants.TIMESTAMPFORMATTER.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();
    }
    return file;
}

From source file:graphene.util.StringUtils.java

public static String removeLeadingZeros(final String key) {
    return key.replaceFirst("^0+(?!$)", "");
}

From source file:com.example.app.support.address.AddressStandardizer.java

private static String normalizeLine2(String line2) {
    if (line2 == null)
        return null;
    Matcher m = LINE2A.matcher(line2);
    if (m.matches()) {
        for (Map.Entry<String, String> e : getUNIT_MAP().entrySet()) {
            if (line2.startsWith(e.getKey() + ' ')) {
                line2 = line2.replaceFirst(e.getKey() + ' ', e.getValue() + ' ');
                break;
            }//from w w w. jav  a 2 s  .c o m
        }
    }
    return line2;
}

From source file:com.wavemaker.commons.util.TypeConversionUtils.java

/**
 * Method to check Multi-Dimensional Array for import.
 * @param className/* w w  w  . j a  v  a  2 s  .co  m*/
 * @return
 */
public static String checkAndReturnForMultiDimensionalArrays(String className) {
    // Matches the pattern like [[Ljava,lang.String
    Pattern pattern = Pattern.compile("(\\[)*[L][\\w\\W]*");
    final Matcher matcher = pattern.matcher(className);
    if (matcher.matches()) {
        // removes for e.g. [[L from [[Ljava,lang.String
        return className.replaceFirst("(\\[)*[L]", "");
    }
    return null;
}

From source file:se.vgregion.usdservice.USDServiceImpl.java

private static Issue resolveIssue(String refNum, int i, String fallbackType, String associated, Document doc)
        throws XPathExpressionException {
    Issue issue = new Issue();
    issue.setRefNum(refNum);//from   w  w  w  .  j ava2 s  .co m

    // Get summary
    String summary = extractAttribute(i, "summary", XPathConstants.STRING, doc);
    issue.setSummary(summary);

    // Get description
    String description = extractAttribute(i, "description", XPathConstants.STRING, doc);
    issue.setDescription(description);

    // Get status
    String statusSym = extractAttribute(i, "status.sym", XPathConstants.STRING, doc);
    issue.setStatus(statusSym);

    // Get web_url
    String webUrl = extractAttribute(i, "web_url", XPathConstants.STRING, doc);
    webUrl = webUrl.replaceFirst("vgms0005", "vgrusd.vgregion.se");
    issue.setUrl(webUrl);

    // Get type
    String type = extractAttribute(i, "type", XPathConstants.STRING, doc);
    if (StringUtils.isEmpty(type)) {
        type = fallbackType;
    }
    issue.setType(type);

    issue.setAssociated(associated);

    return issue;
}

From source file:at.alladin.rmbt.shared.Helperfunctions.java

public static String anonymizeIp(final InetAddress inetAddress) {
    try {//w  w  w.  j a  v a  2s.c o  m
        final byte[] address = inetAddress.getAddress();
        address[address.length - 1] = 0;
        if (address.length > 4) // ipv6
        {
            for (int i = 6; i < address.length; i++)
                address[i] = 0;
        }

        String result = InetAddresses.toAddrString(InetAddress.getByAddress(address));
        if (address.length == 4)
            result = result.replaceFirst(".0$", "");
        return result;
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.ikanow.aleph2.analytics.spark.utils.SparkTechnologyUtils.java

/**Checks if an aleph2 JAR file with bad internal JARs is cached, does some excising if not
 * @param local_file/*  w  ww.jav a 2 s  . com*/
 * @param root_path
 * @param fc
 * @return
 * @throws IOException
 */
public static Tuple3<File, Path, FileStatus> removeSparkConflictsAndCache(final String local_file,
        final String root_path, final FileContext fc) throws IOException {
    final String renamed_local_file = local_file.replaceFirst(".jar", "_sparkVersion.jar");
    final File f = new File(renamed_local_file);
    final Tuple2<File, Path> f_p = Tuples._2T(f, new Path(root_path + "/" + f.getName()));
    final FileStatus fs = Lambdas.get(() -> {
        try {
            return fc.getFileStatus(f_p._2());
        } catch (Exception e) {
            return null;
        }
    });
    if (null == fs) { //cache doesn't exist
        // Create a new copy without akka in tmp
        File f_tmp = File.createTempFile("aleph2-temp", ".jar");
        JarBuilderUtil.mergeJars(Arrays.asList(local_file), f_tmp.toString(),
                ImmutableSet.of("akka", "scala", "com/typesafe/conf", "reference.conf", //(these definitely need to be removed)
                        "org/jboss/netty", //(not sure about this, can't imagine i actually need it though? If so try putting back in)
                        "org/apache/curator", "org/apache/zookeeper")); //(not sure about these, can try putting them back in if needed)

        return Tuples._3T(f_tmp, f_p._2(), null);
    } else
        return Tuples._3T(f_p._1(), f_p._2(), fs);
}