Example usage for java.util.regex Matcher quoteReplacement

List of usage examples for java.util.regex Matcher quoteReplacement

Introduction

In this page you can find the example usage for java.util.regex Matcher quoteReplacement.

Prototype

public static String quoteReplacement(String s) 

Source Link

Document

Returns a literal replacement String for the specified String .

Usage

From source file:org.entando.edo.builder.TestBuilder.java

@Test
public void test_Widget_Jsp() throws IOException {
    String commonPath = "src/main/webapp/WEB-INF/plugins/jppet/aps/jsp/widgets".replaceAll("/",
            Matcher.quoteReplacement(File.separator));

    String actualPath = ACTUAL_BASE_FOLDER + commonPath;

    File actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    List<File> actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(1, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:com.jsmartframework.web.manager.FilterControl.java

private String completeScripts(HttpServletRequest httpRequest, String html) {
    // Stand alone script with mapped exposed variables
    Script varScript = getExposeVarScripts(httpRequest);

    // Stand alone functions mapped via function tag
    Script funcScript = getFunctionScripts(httpRequest);

    // General page scripts executed when document is ready
    DocScript docScript = (DocScript) httpRequest.getAttribute(REQUEST_PAGE_DOC_SCRIPT_ATTR);

    StringBuilder scriptBuilder = new StringBuilder(headerScripts);
    if (varScript != null) {
        scriptBuilder.append(varScript.getHtml());
    }//from w  w  w  .  j  a  v a  2  s  .  com
    if (funcScript != null) {
        scriptBuilder.append(funcScript.getHtml());
    }
    if (docScript != null) {
        scriptBuilder.append(docScript.getHtml());
    }

    // Place the scripts before the last script tag inside body
    Matcher scriptMatcher = SCRIPT_BODY_PATTERN.matcher(html);
    if (scriptMatcher.find()) {
        return scriptMatcher.replaceFirst("$1" + Matcher.quoteReplacement(scriptBuilder.toString()) + "$2");
    }

    // Place the scripts before the end body tag
    Matcher bodyMatcher = CLOSE_BODY_PATTERN.matcher(html);
    if (!bodyMatcher.find()) {
        throw new RuntimeException("HTML tag [body] could not be find. Please insert the body tag in your JSP");
    }
    return bodyMatcher.replaceFirst(Matcher.quoteReplacement(scriptBuilder.toString()) + "$1");
}

From source file:org.entando.edo.builder.TestBuilderNoPlugin.java

@Test
public void test_Widget_Tags() throws IOException {
    String commonPath = "src/main/java/com/myportal/aps/tags".replaceAll("/",
            Matcher.quoteReplacement(File.separator));

    String actualPath = ACTUAL_BASE_FOLDER + commonPath;

    File actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    List<File> actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(2, actualFiles.size());
    this.compareFiles(actualFiles);

    //------/*  ww  w . j  a va 2s .co  m*/
    commonPath = "src/main/tld/sandbox".replaceAll("/", Matcher.quoteReplacement(File.separator));

    actualPath = ACTUAL_BASE_FOLDER + commonPath;

    actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(1, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:org.entando.edo.builder.TestBuilder.java

@Test
public void test_Widget_Tags() throws IOException {
    String commonPath = "src/main/java/org/entando/entando/plugins/jppet/aps/tags".replaceAll("/",
            Matcher.quoteReplacement(File.separator));

    String actualPath = ACTUAL_BASE_FOLDER + commonPath;

    File actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    List<File> actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(2, actualFiles.size());
    this.compareFiles(actualFiles);

    //------/*from w w w . j ava2s . com*/
    commonPath = "src/main/tld/plugins/jppet".replaceAll("/", Matcher.quoteReplacement(File.separator));

    actualPath = ACTUAL_BASE_FOLDER + commonPath;

    actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(1, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:org.springframework.aop.interceptor.CustomizableTraceInterceptor.java

/**
 * Adds the {@code String} representation of the method return value
 * to the supplied {@code StringBuffer}. Correctly handles
 * {@code null} and {@code void} results.
 * @param methodInvocation the {@code MethodInvocation} that returned the value
 * @param matcher the {@code Matcher} containing the matched placeholder
 * @param output the {@code StringBuffer} to write output to
 * @param returnValue the value returned by the method invocation.
 *//*from  ww w.  j ava2 s .c om*/
private void appendReturnValue(MethodInvocation methodInvocation, Matcher matcher, StringBuffer output,
        @Nullable Object returnValue) {

    if (methodInvocation.getMethod().getReturnType() == void.class) {
        matcher.appendReplacement(output, "void");
    } else if (returnValue == null) {
        matcher.appendReplacement(output, "null");
    } else {
        matcher.appendReplacement(output, Matcher.quoteReplacement(returnValue.toString()));
    }
}

From source file:org.stirrat.ecm.speedyarchiver.SpeedyArchiverServices.java

/**
 * Extract zip file into an archive folder.
 * //from   w w  w. java  2  s .c  o m
 * @param zipFilename
 * @param folder
 */
private void extractZipFile(String zipFilename, File folder) {
    try {

        File archiveFolderPath = createDestinationFolder(folder);

        if (archiveFolderPath == null) {
            throw new ServiceException("Unable to create destination folder: " + archiveFolderPath);
        }

        byte[] readBuffer = new byte[READ_BUFFER_SIZE];

        ZipInputStream zipStream = null;

        ZipEntry zipFileEntry;

        zipStream = new ZipInputStream(new FileInputStream(zipFilename));

        zipFileEntry = zipStream.getNextEntry();

        while (zipFileEntry != null) {

            // convert to system folder separator char
            String entryName = zipFileEntry.getName().replaceAll("\\\\|/",
                    Matcher.quoteReplacement(File.separator));

            SystemUtils.trace(traceSection, "entryname " + entryName);

            File newFile = new File(entryName);
            String directory = newFile.getParent();

            if (directory != null && !directory.equalsIgnoreCase("")) {

                SystemUtils.trace(traceSection, "creating a directory structure: " + directory);

                try {
                    new File(archiveFolderPath + File.separator + directory).mkdirs();

                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                }
            }

            FileOutputStream outStream = new FileOutputStream(archiveFolderPath + File.separator + entryName);

            int n;
            while ((n = zipStream.read(readBuffer, 0, READ_BUFFER_SIZE)) > -1) {
                outStream.write(readBuffer, 0, n);
            }

            outStream.close();
            zipStream.closeEntry();
            zipFileEntry = zipStream.getNextEntry();

        }

        zipStream.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.jbosson.plugins.amq.ArtemisMBeanDiscoveryComponent.java

protected static String formatMessage(String messageTemplate, Map<String, String> variableValues) {

    StringBuffer result = new StringBuffer();

    // collect keys and values to determine value size limit if needed
    final Map<String, String> replaceMap = new HashMap<String, String>();

    final Matcher matcher = PROPERTY_NAME_PATTERN.matcher(messageTemplate);
    int count = 0;
    while (matcher.find()) {
        final String key = matcher.group(1);
        final String value = variableValues.get(key);

        if (value != null) {
            replaceMap.put(key, value);/*from   ww w . j ava  2 s  .c  o  m*/
            matcher.appendReplacement(result, Matcher.quoteReplacement(value));
        } else {
            matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group()));
        }

        count++;
    }
    matcher.appendTail(result);

    // check if the result exceeds MAX_LENGTH for formatted properties
    if (!replaceMap.isEmpty() && result.length() > MAX_LENGTH) {
        // sort values according to size
        final SortedSet<String> values = new TreeSet<String>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.length() - o2.length();
            }
        });
        values.addAll(replaceMap.values());

        // find total value characters allowed
        int available = MAX_LENGTH - PROPERTY_NAME_PATTERN.matcher(messageTemplate).replaceAll("").length();

        // fit values from small to large in the allowed size to determine the maximum average
        int averageLength = available / count;
        for (String value : values) {
            final int length = value.length();
            if (length > averageLength) {
                break;
            }
            available -= length;
            count--;
            averageLength = available / count;
        }

        // replace values
        matcher.reset();
        result.delete(0, result.length());
        while (matcher.find()) {
            String value = replaceMap.get(matcher.group(1));
            if (value != null && value.length() > averageLength) {
                value = value.substring(0, averageLength);
            }
            matcher.appendReplacement(result, value != null ? value : matcher.group());
        }
        matcher.appendTail(result);
    }

    return result.toString();
}

From source file:com.jsmartframework.web.manager.FilterControl.java

private String completeVersions(HttpServletRequest httpRequest, String html) {
    if (versionFilePatterns.isEmpty()) {
        return html;
    }//  w  w  w.j  a  v a  2 s  . c o  m
    for (String version : versionFilePatterns.keySet()) {
        Pattern filePattern = versionFilePatterns.get(version);
        Matcher fileMatcher = filePattern.matcher(html);
        html = fileMatcher.replaceAll("$1" + Matcher.quoteReplacement("?" + version));
    }
    return html;
}

From source file:com.adobe.ags.curly.controller.ActionRunner.java

private void applyVariablesToMap(Map<String, String> variables, Map<String, String> target) {
    Set<String> variableTokens = ActionUtils.getVariableNames(action);

    Set removeSet = new HashSet<>();
    Map<String, String> newValues = new HashMap<>();

    target.forEach((paramName, paramValue) -> {
        StringProperty paramNameProperty = new SimpleStringProperty(paramName);
        variableTokens.forEach((String originalName) -> {
            String[] variableNameParts = originalName.split("\\|");
            String variableName = variableNameParts[0];
            String variableNameMatchPattern = Pattern.quote("${" + originalName + "}");
            String val = variables.get(variableName);
            if (val == null) {
                val = "";
            }/*from www  . j ava  2 s .co  m*/
            String variableValue = Matcher.quoteReplacement(val);
            //----
            String newParamValue = newValues.containsKey(paramNameProperty.get())
                    ? newValues.get(paramNameProperty.get())
                    : paramValue;
            String newParamName = paramNameProperty.get().replaceAll(variableNameMatchPattern, variableValue);
            paramNameProperty.set(newParamName);
            newParamValue = newParamValue.replaceAll(variableNameMatchPattern, variableValue);
            if (!newParamName.equals(paramName) || !newParamValue.equals(paramValue)) {
                removeSet.add(paramNameProperty.get());
                removeSet.add(paramName);
                newValues.put(newParamName, newParamValue);
            }
        });
    });
    target.keySet().removeAll(removeSet);
    target.putAll(newValues);
}

From source file:hydrograph.engine.spark.datasource.utils.FTPUtil.java

public void download(RunFileTransferEntity runFileTransferEntity) {
    log.debug("Start FTPUtil download");

    File filecheck = new File(runFileTransferEntity.getOutFilePath());
    if (!(filecheck.exists() && filecheck.isDirectory())
            && !(runFileTransferEntity.getOutFilePath().contains("hdfs://"))) {
        log.error("Invalid output file path. Please provide valid output file path.");
        throw new RuntimeException("Invalid output path");
    }//  www.  j  a va 2s.  c  om
    boolean fail_if_exist = false;
    FTPClient ftpClient = new FTPClient();
    int retryAttempt = runFileTransferEntity.getRetryAttempt();
    int attemptCount = 1;
    int i = 0;
    boolean login = false;
    boolean done = false;
    for (i = 0; i < retryAttempt; i++) {
        try {
            log.info("Connection attempt: " + (i + 1));
            if (runFileTransferEntity.getTimeOut() != 0)
                ftpClient.setConnectTimeout(runFileTransferEntity.getTimeOut());
            log.debug("connection details: " + "/n" + "Username: " + runFileTransferEntity.getUserName() + "/n"
                    + "HostName " + runFileTransferEntity.getHostName() + "/n" + "Portno"
                    + runFileTransferEntity.getPortNo());
            ftpClient.connect(runFileTransferEntity.getHostName(), runFileTransferEntity.getPortNo());

            login = ftpClient.login(runFileTransferEntity.getUserName(), runFileTransferEntity.getPassword());

            if (!login) {
                log.error("Invalid FTP details provided. Please provide correct FTP details.");
                throw new FTPUtilException("Invalid FTP details");
            }
            ftpClient.enterLocalPassiveMode();
            if (runFileTransferEntity.getEncoding() != null)
                ftpClient.setControlEncoding(runFileTransferEntity.getEncoding());
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (runFileTransferEntity.getOutFilePath().contains("hdfs://")) {
                log.debug("Processing for HDFS output path");
                String outputPath = runFileTransferEntity.getOutFilePath();
                String s1 = outputPath.substring(7, outputPath.length());
                String s2 = s1.substring(0, s1.indexOf("/"));
                File f = new File("/tmp");
                if (!f.exists()) {
                    f.mkdir();
                }

                int index = runFileTransferEntity.getInputFilePath()
                        .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');
                String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);

                File isfile = new File(runFileTransferEntity.getOutFilePath() + "\\" + file_name);
                if (runFileTransferEntity.getOverwrite().equalsIgnoreCase("Overwrite If Exists")) {

                    OutputStream outputStream = new FileOutputStream("/tmp/" + file_name);
                    done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream);
                    outputStream.close();
                } else {
                    if (!(isfile.exists() && !isfile.isDirectory())) {
                        OutputStream outputStream = new FileOutputStream("/tmp/" + file_name);

                        done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream);
                        outputStream.close();
                    } else {
                        fail_if_exist = true;
                        throw new RuntimeException("File already exists");
                    }
                }

                Configuration conf = new Configuration();
                conf.set("fs.defaultFS", "hdfs://" + s2);
                FileSystem hdfsFileSystem = FileSystem.get(conf);

                String s = outputPath.substring(7, outputPath.length());
                String hdfspath = s.substring(s.indexOf("/"), s.length());

                Path local = new Path("/tmp/" + file_name);
                Path hdfs = new Path(hdfspath);
                hdfsFileSystem.copyFromLocalFile(local, hdfs);

            } else {
                int index = runFileTransferEntity.getInputFilePath()
                        .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');
                String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);

                File isfile = new File(runFileTransferEntity.getOutFilePath() + File.separatorChar + file_name);
                if (runFileTransferEntity.getOverwrite().equalsIgnoreCase("Overwrite If Exists")) {

                    OutputStream outputStream = new FileOutputStream(runFileTransferEntity.getOutFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/") + "/" + file_name);
                    done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), (outputStream));
                    outputStream.close();
                } else {

                    if (!(isfile.exists() && !isfile.isDirectory())) {

                        OutputStream outputStream = new FileOutputStream(
                                runFileTransferEntity.getOutFilePath().replaceAll(
                                        Matcher.quoteReplacement("\\"), "/") + File.separatorChar + file_name);

                        done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream);
                        outputStream.close();
                    } else {
                        fail_if_exist = true;
                        Log.error("File already exits");
                        throw new FTPUtilException("File already exists");

                    }

                }
            }
        } catch (Exception e) {
            log.error("error while transferring the file", e);
            if (!login) {
                log.error("Login ");

                throw new FTPUtilException("Invalid FTP details");
            }
            if (fail_if_exist) {
                log.error("File already exists ");
                throw new FTPUtilException("File already exists");
            }
            try {
                Thread.sleep(runFileTransferEntity.getRetryAfterDuration());
            } catch (Exception e1) {
                Log.error("Exception occured during sleep");
            } catch (Error err) {
                log.error("fatal error", e);
                throw new FTPUtilException(err);
            }
            continue;
        }

        break;

    }

    if (i == runFileTransferEntity.getRetryAttempt()) {

        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();

            }
        } catch (Exception e) {

            Log.error("Exception while closing the ftp client", e);
        }
        if (runFileTransferEntity.getFailOnError())
            throw new FTPUtilException("File transfer failed ");

    }

    log.debug("Finished FTPUtil download");

}