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_InternalServlet_Jsp() throws IOException {
    String commonPath = "src/main/webapp/WEB-INF/plugins/jppet/aps/jsp/internalservlet".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(4, actualFiles.size());
    this.compareFiles(actualFiles);
}

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

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

    File filecheck = new File(runFileTransferEntity.getOutFilePath());
    if (runFileTransferEntity.getFailOnError())
        if (!(filecheck.exists() && filecheck.isDirectory())
                && !(runFileTransferEntity.getOutFilePath().contains("hdfs://"))) {
            log.error("invalid output path,Please provide valid path ");
            throw new SFTPUtilException("invalid outputpath");
        }// www .j av  a2 s  .c  om
    boolean fail_if_exist = false;
    JSch jsch = new JSch();
    Session session = null;
    Channel channel = null;
    ChannelSftp sftpChannel = null;
    int retryAttempt = 0;
    int i;
    if (runFileTransferEntity.getRetryAttempt() == 0)
        retryAttempt = 1;
    else
        retryAttempt = runFileTransferEntity.getRetryAttempt();
    for (i = 0; i < retryAttempt; i++) {
        log.info("connection attempt: " + (i + 1));
        try {
            if (runFileTransferEntity.getPrivateKeyPath() != null) {
                jsch.addIdentity(runFileTransferEntity.getPrivateKeyPath());
            }
            log.debug("connection details: " + "/n" + "Username: " + runFileTransferEntity.getUserName() + "/n"
                    + "HostName " + runFileTransferEntity.getHostName() + "/n" + "Portno"
                    + runFileTransferEntity.getPortNo());
            session = jsch.getSession(runFileTransferEntity.getUserName(), runFileTransferEntity.getHostName(),
                    runFileTransferEntity.getPortNo());
            session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
            session.setConfig("StrictHostKeyChecking", "no");
            if (runFileTransferEntity.getPassword() != null) {
                session.setPassword(runFileTransferEntity.getPassword());
            }
            if (runFileTransferEntity.getTimeOut() > 0) {
                session.setTimeout(runFileTransferEntity.getTimeOut());
            }

            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            sftpChannel = (ChannelSftp) channel;
            sftpChannel.setFilenameEncoding(runFileTransferEntity.getEncoding());
            if (runFileTransferEntity.getOutFilePath().contains("hdfs://")) {
                log.debug("HDFS file transferring");
                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);
                String file_loc = runFileTransferEntity.getInputFilePath().substring(0, index);

                sftpChannel.cd(file_loc.replaceAll(Matcher.quoteReplacement("\\"), "/"));

                File isfile = new File(runFileTransferEntity.getOutFilePath() + File.separatorChar + file_name);
                if (runFileTransferEntity.getOverwrite().equalsIgnoreCase("Overwrite If Exists")) {
                    FileOutputStream fout = new FileOutputStream("/tmp/" + file_name);
                    sftpChannel.get(file_name, new BufferedOutputStream(fout));
                    fout.close();

                } else {
                    if ((isfile.exists() && !isfile.isDirectory())) {
                        FileOutputStream fout = new FileOutputStream("/tmp/" + file_name);
                        sftpChannel.get(file_name, new BufferedOutputStream(fout));
                        fout.close();
                    } else {
                        fail_if_exist = true;
                        log.debug("File already exist");
                        throw new SFTPUtilException("file already exist");
                    }

                }

            } else {
                log.debug("File transfer in normal");
                int index = runFileTransferEntity.getInputFilePath()
                        .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');
                String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);
                String file_loc = runFileTransferEntity.getInputFilePath().substring(0, index);
                sftpChannel.cd(file_loc.replaceAll(Matcher.quoteReplacement("\\"), "/"));
                sftpChannel.setFilenameEncoding(runFileTransferEntity.getEncoding());

                File isfile = new File(runFileTransferEntity.getOutFilePath() + File.separatorChar + file_name);
                if (runFileTransferEntity.getOverwrite().equalsIgnoreCase("Overwrite If Exists")) {
                    FileOutputStream fout = new FileOutputStream(
                            runFileTransferEntity.getOutFilePath() + File.separatorChar + file_name);
                    sftpChannel.get(file_name, new BufferedOutputStream(fout));
                    fout.close();

                } else {
                    if (!(isfile.exists() && !isfile.isDirectory())) {
                        FileOutputStream fout = new FileOutputStream(
                                runFileTransferEntity.getOutFilePath() + File.separatorChar + file_name);
                        sftpChannel.get(file_name, new BufferedOutputStream(fout));
                        fout.close();
                    } else {
                        fail_if_exist = true;
                        log.debug("file alreay exist");
                        throw new SFTPUtilException("File Already exist");
                    }

                }

            }
        } catch (JSchException e) {
            if (e.getMessage().compareTo("Auth fail") == 0) {
                log.error("authentication error,please provide valid details");
                if (runFileTransferEntity.getFailOnError())
                    throw new SFTPUtilException(e.getMessage());

            }
            log.error("JSCH api exception", e);

            {
                try {
                    Thread.sleep(runFileTransferEntity.getRetryAfterDuration());
                } catch (Exception e1) {
                    log.error("error in sleep duration of thread");
                }
                continue;
            }

        } catch (Exception e) {
            log.error("error while transferring the file", e);
            if (fail_if_exist) {
                log.error("File already exists");
                throw new SFTPUtilException("File already exists");
            }
            try {
                Thread.sleep(runFileTransferEntity.getRetryAfterDuration());
            } catch (Exception e1) {
                log.error("sleep duration exception", e1);
            }
            continue;
        } catch (Error e) {
            log.error("fatal error ", e);
            throw new SFTPUtilException(e);
        }
        done = true;
        break;

    }

    if (sftpChannel != null) {
        sftpChannel.disconnect();
    }
    if (channel != null) {
        channel.disconnect();
    }
    if (session != null) {
        session.disconnect();
    }
    if (runFileTransferEntity.getFailOnError() && !done) {
        log.error("File transfer failed");
        throw new SFTPUtilException("File transfer failed");
    } else if (!done) {
        log.error("File transfer failed but mentioned fail on error as false");
    }
    log.debug("Fininished SFTPUtil download");
}

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

@Test
public void test_TestJava() throws IOException {
    String commonPath = "src/test/java/com/myportal".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(6, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:com.garyclayburg.attributes.AttributeService.java

public String stripScriptRoot(String groovyRootPath, String absPath) {
    log.debug("groovyrootpath {}", groovyRootPath);
    log.debug("abspath {}", absPath);

    String sanitizedGroovyRootPath = Matcher.quoteReplacement(groovyRootPath);
    return absPath.replaceFirst(sanitizedGroovyRootPath, "");
}

From source file:org.etudes.mneme.impl.ImportQtiServiceImpl.java

/**
 * Find all the items from the root using the path, and combine their text content.
 * /*from  ww  w .ja v a 2s. co  m*/
 * @param textPath
 *        Text XPath
 * @param blanksPath
 *        Blanks XPath
 * @param answersPath
 *        Answers XPath
 * @param root
 *        The Document or Element root
 * @return The question.
 */
protected String buildFillInQuestionText(XPath textPath, XPath blanksPath, XPath answersPath, Object root) {
    StringBuilder rv = new StringBuilder();
    String questionText = null;
    try {
        List hits = textPath.selectNodes(root);
        List blankHits = blanksPath.selectNodes(root);
        List answerHits = answersPath.selectNodes(root);

        if (answerHits.size() != blankHits.size())
            return null;

        int count = 0, blanksCount = 0;

        blanksCount = blankHits.size();

        for (Object o : hits) {
            // add braces for the text
            if (count > 0 && blanksCount > 0) {
                rv.append(" {} ");
                blanksCount--;
            }

            Element e = (Element) o;
            String value = StringUtil.trimToNull(e.getTextContent());
            if (value != null) {
                rv.append(value);
            }
            count++;
        }

        // fill the braces({}) with answers
        questionText = rv.toString();
        Element e;
        String answer;
        for (int index = 0; index < answerHits.size(); index++) {
            e = (Element) answerHits.get(index);
            answer = StringUtil.trimToNull(e.getTextContent());
            questionText = questionText.replaceFirst("\\{\\}", Matcher.quoteReplacement("{" + answer + "}"));
        }
    } catch (JaxenException e) {
        M_log.warn(e.toString());
    }

    if (questionText.length() == 0)
        return null;
    return questionText;
}

From source file:org.apache.synapse.mediators.transform.PayloadFactoryMediator.java

/**
 * Replaces the payload format with SynapsePath arguments which are evaluated using getArgValues().
 *
 * @param format/* w w w  . j a va  2 s  . c  o m*/
 * @param result
 * @param synCtx
 */
private void replace(String format, StringBuffer result, MessageContext synCtx) {
    HashMap<String, String>[] argValues = getArgValues(synCtx);
    HashMap<String, String> replacement;
    Map.Entry<String, String> replacementEntry;
    String replacementValue = null;
    Matcher matcher;

    matcher = pattern.matcher(format);
    try {
        while (matcher.find()) {
            String matchSeq = matcher.group();
            int argIndex;
            try {
                argIndex = Integer.parseInt(matchSeq.substring(1, matchSeq.length()));
            } catch (NumberFormatException e) {
                argIndex = Integer.parseInt(matchSeq.substring(2, matchSeq.length() - 1));
            }
            replacement = argValues[argIndex - 1];
            replacementEntry = replacement.entrySet().iterator().next();
            if (mediaType.equals(JSON_TYPE) && inferReplacementType(replacementEntry).equals(XML_TYPE)) {
                // XML to JSON conversion here
                try {
                    replacementValue = "<jsonObject>" + replacementEntry.getKey() + "</jsonObject>";
                    OMElement omXML = AXIOMUtil.stringToOM(replacementValue);
                    // This is to replace \" with \\" and \\$ with \$. Because for Matcher, $ sign is
                    // a special character and for JSON " is a special character.
                    replacementValue = JsonUtil.toJsonString(omXML).toString()
                            .replaceAll(ESCAPE_DOUBLE_QUOTE_WITH_FIVE_BACK_SLASHES,
                                    ESCAPE_DOUBLE_QUOTE_WITH_NINE_BACK_SLASHES)
                            .replaceAll(ESCAPE_DOLLAR_WITH_TEN_BACK_SLASHES,
                                    ESCAPE_DOLLAR_WITH_SIX_BACK_SLASHES);
                } catch (XMLStreamException e) {
                    handleException(
                            "Error parsing XML for JSON conversion, please check your xPath expressions return valid XML: ",
                            synCtx);
                } catch (AxisFault e) {
                    handleException("Error converting XML to JSON", synCtx);
                }
            } else if (mediaType.equals(XML_TYPE) && inferReplacementType(replacementEntry).equals(JSON_TYPE)) {
                // JSON to XML conversion here
                try {
                    OMElement omXML = JsonUtil.toXml(IOUtils.toInputStream(replacementEntry.getKey()), false);
                    if (JsonUtil.isAJsonPayloadElement(omXML)) { // remove <jsonObject/> from result.
                        Iterator children = omXML.getChildElements();
                        String childrenStr = "";
                        while (children.hasNext()) {
                            childrenStr += (children.next()).toString().trim();
                        }
                        replacementValue = childrenStr;
                    } else { ///~
                        replacementValue = omXML.toString();
                    }
                    //replacementValue = omXML.toString();
                } catch (AxisFault e) {
                    handleException(
                            "Error converting JSON to XML, please check your JSON Path expressions return valid JSON: ",
                            synCtx);
                }
            } else {
                // No conversion required, as path evaluates to regular String.
                replacementValue = replacementEntry.getKey();
                // This is to replace " with \" and \\ with \\\\
                if (mediaType.equals(JSON_TYPE) && inferReplacementType(replacementEntry).equals(STRING_TYPE)
                        && (!replacementValue.startsWith("{") && !replacementValue.startsWith("["))) {
                    replacementValue = replacementValue
                            .replaceAll(Matcher.quoteReplacement("\\\\"),
                                    ESCAPE_BACK_SLASH_WITH_SIXTEEN_BACK_SLASHES)
                            .replaceAll("\"", ESCAPE_DOUBLE_QUOTE_WITH_TEN_BACK_SLASHES);
                } else if ((mediaType.equals(JSON_TYPE)
                        && inferReplacementType(replacementEntry).equals(JSON_TYPE))
                        && (!replacementValue.startsWith("{") && !replacementValue.startsWith("["))) {
                    // This is to handle only the string value
                    replacementValue = replacementValue.replaceAll("\"",
                            ESCAPE_DOUBLE_QUOTE_WITH_TEN_BACK_SLASHES);
                }
            }
            matcher.appendReplacement(result, replacementValue);
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        log.error("#replace. Mis-match detected between number of formatters and arguments", e);
    }
    matcher.appendTail(result);
}

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

@Test
public void test_TestJava() throws IOException {
    String commonPath = "src/test/java/org/entando/entando/plugins/jppet".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(6, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:org.rm3l.ddwrt.tiles.syslog.StatusSyslogTile.java

@NotNull
private Spanned findAndHighlightOutput(@NotNull final CharSequence text, @NotNull final String textToFind) {
    final Matcher matcher = Pattern.compile("(" + Pattern.quote(textToFind) + ")", Pattern.CASE_INSENSITIVE)
            .matcher(text);//from   w  w w.  j ava2 s . com
    return Html.fromHtml(matcher
            .replaceAll(Matcher.quoteReplacement(FONT_COLOR_YELLOW_HTML) + "$1"
                    + Matcher.quoteReplacement(SLASH_FONT_HTML))
            .replaceAll(Pattern.quote("\n"), Matcher.quoteReplacement("<br/>")));
}

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

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

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

    target.forEach((paramName, paramValues) -> {
        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 = "";
            }// w  w  w  . java2s. c om
            String variableValue = Matcher.quoteReplacement(val);
            String newParamName = paramNameProperty.get().replaceAll(variableNameMatchPattern, variableValue);
            removeSet.add(paramNameProperty.get());
            removeSet.add(paramName);
            if (newValues.get(paramNameProperty.get()) == null) {
                newValues.put(paramNameProperty.get(), new ArrayList<>(paramValues.size()));
            }
            if (newValues.get(newParamName) == null) {
                newValues.put(newParamName, new ArrayList<>(paramValues.size()));
            }
            List<String> newParamValues = newValues.get(paramNameProperty.get());
            for (int i = 0; i < paramValues.size(); i++) {
                String newParamValue = newParamValues != null && newParamValues.size() > i
                        && newParamValues.get(i) != null ? newParamValues.get(i) : paramValues.get(i);

                // fix for removing JCR values (setting them to an empty
                // string deletes them from the JCR)
                if (null == newParamValue) {
                    newParamValue = "";
                }

                newParamValue = newParamValue.replaceAll(variableNameMatchPattern, variableValue);
                if (newParamName.contains("/") && newParamValue.equals("@" + newParamName)) {
                    // The upload name should actually be the file name, not the full path of the file.
                    removeSet.add(newParamName);
                    newValues.remove(newParamName);
                    newParamName = newParamName.substring(newParamName.lastIndexOf("/") + 1);
                    newValues.put(newParamName, newParamValues);
                }
                if (newValues.get(newParamName).size() == i) {
                    newValues.get(newParamName).add(newParamValue);
                } else {
                    newValues.get(newParamName).set(i, newParamValue);
                }
            }
            if (!paramNameProperty.get().equals(newParamName)) {
                newValues.remove(paramNameProperty.get());
            }
            paramNameProperty.set(newParamName);
        });
    });
    target.keySet().removeAll(removeSet);
    target.putAll(newValues);
}

From source file:org.alfresco.dropbox.service.polling.DropboxPollerImpl.java

private void addNode(final NodeRef parentNodeRef, final Metadata metadata, final String name) {
    AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() {

        public Object doWork() throws Exception {
            NodeRef nodeRef = null;//from w w w.ja  v a  2 s . c  o m

            if (metadata.isDir()) {
                RetryingTransactionCallback<NodeRef> txnWork = new RetryingTransactionCallback<NodeRef>() {
                    public NodeRef execute() throws Exception {
                        NodeRef nodeRef = null;
                        nodeRef = fileFolderService.create(parentNodeRef, name, ContentModel.TYPE_FOLDER)
                                .getNodeRef();

                        Metadata metadata = dropboxService.getMetadata(nodeRef);

                        List<Metadata> list = metadata.getContents();

                        for (Metadata child : list) {
                            String name = child.getPath()
                                    .replaceAll(Matcher.quoteReplacement(metadata.getPath() + "/"), "");

                            addNode(nodeRef, child, name);
                        }

                        return nodeRef;
                    }
                };

                nodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false);
            } else {
                log.debug("Adding " + metadata.getPath() + " to Alfresco");

                RetryingTransactionCallback<NodeRef> txnWork = new RetryingTransactionCallback<NodeRef>() {
                    public NodeRef execute() throws Exception {
                        NodeRef nodeRef = null;

                        try {
                            nodeRef = fileFolderService.create(parentNodeRef, name, ContentModel.TYPE_CONTENT)
                                    .getNodeRef();
                            Metadata metadata = dropboxService.getFile(nodeRef);

                            dropboxService.persistMetadata(metadata, parentNodeRef);
                        } catch (ContentIOException cio) {
                            cio.printStackTrace();
                        }

                        return nodeRef;
                    }
                };

                nodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false);
            }
            dropboxService.persistMetadata(metadata, nodeRef);
            return null;

        }
    }, AuthenticationUtil.getAdminUserName());
}