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.wso2.carbon.identity.workflow.impl.BPELDeployer.java

private void removePlaceHolders(String relativeFilePath, String destination) throws IOException {

    InputStream inputStream = getClass().getResourceAsStream("/" + relativeFilePath);
    String content = IOUtils.toString(inputStream);
    for (Map.Entry<String, String> placeHolderEntry : getPlaceHolderValues().entrySet()) {
        content = content.replaceAll(Pattern.quote(placeHolderEntry.getKey()),
                Matcher.quoteReplacement(placeHolderEntry.getValue()));
    }// www.j  a v  a2s  .co m
    File destinationParent = new File(destination).getParentFile();
    if (!destinationParent.exists()) {
        destinationParent.mkdirs();
    }
    FileOutputStream fileOutputStream = new FileOutputStream(new File(destination), false);
    IOUtils.write(content, fileOutputStream);
    fileOutputStream.flush();
    fileOutputStream.close();
    inputStream.close();
}

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

@Test
public void test_Controller_Struts_Xml() throws IOException {
    String commonPath = "src/main/resources".replaceAll("/", Matcher.quoteReplacement(File.separator));

    String actualPath = ACTUAL_BASE_FOLDER + commonPath;

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

    FileFilter excludeSubfolders = new FileFilter() {
        @Override//from w  w  w  . j a  v  a2 s.  c  o  m
        public boolean accept(File pathname) {
            if (pathname.isDirectory() && !pathname.getName().equals("resources"))
                return false;
            return true;
        }
    };
    List<File> actualFiles = this.searchFiles(actualDir, excludeSubfolders);
    Assert.assertEquals(1, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:main.export.sql.DocBuilder.java

@SuppressWarnings("unchecked")
public Map<String, Object> getFields(Map<String, Object> firstRow, ResultSet rs, Entity entity,
        Map<String, Object> entityMap, Map<String, Object> rootEntityMap) throws SQLException {

    entityMap = new HashMap<String, Object>();

    if (entity.allAttributes.get(MULTI_VALUED) != null
            && entity.allAttributes.get(MULTI_VALUED).equalsIgnoreCase("true")) {
        List<Object> fieldArray = new ArrayList<Object>();
        rs.beforeFirst();//from ww  w .  j  av a  2s  . co m
        while (rs.next()) {
            if (entity.fields.size() > 1) {
                Map<String, Object> entityFieldsMap = new HashMap<String, Object>();
                for (Iterator<Field> iterator = entity.fields.iterator(); iterator.hasNext();) {
                    Field field = (Field) iterator.next();
                    FieldType fieldType = FieldType.valueOf(field.allAttributes.get("type").toUpperCase());
                    entityFieldsMap.put(field.name,
                            convertFieldType(fieldType, rs.getObject(field.column)).get(0));
                }
                fieldArray.add(entityFieldsMap);
            } else if (entity.fields.size() == 1) {
                fieldArray.add(rs.getObject(entity.fields.get(0).column));
            }
        }
        rootEntityMap.put(entity.name, fieldArray);
    } else if (firstRow != null) {
        for (Iterator<Field> iterator = entity.fields.iterator(); iterator.hasNext();) {
            Field field = (Field) iterator.next();
            FieldType fieldType = FieldType.valueOf(field.allAttributes.get("type").toUpperCase());

            if (firstRow.get(field.column) != null) {
                if (entity.pk != null && entity.pk.equals(field.name)) {
                    if (importer.getDataStoreType().equals(DataStoreType.MONGO)) {
                        entityMap.put("_id", convertFieldType(fieldType, firstRow.get(field.column)).get(0));
                    } else if (importer.getDataStoreType().equals(DataStoreType.COUCH)) {
                        // couch db says document id must be string
                        entityMap.put("_id",
                                convertFieldType(FieldType.STRING, firstRow.get(field.column)).get(0));
                    }
                } else {
                    entityMap.put(field.getName(),
                            convertFieldType(fieldType, firstRow.get(field.column)).get(0));
                }

                params.put(entity.name + "." + field.name, firstRow.get(field.column).toString());
            }

        }
    }

    if (entity.entities != null) {
        Entity subEntity = null;
        String query = "", aparam = "";
        for (Iterator<Entity> iterator = entity.entities.iterator(); iterator.hasNext();) {
            subEntity = (Entity) iterator.next();
            subLevel = subConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            query = subEntity.allAttributes.get("query");

            m = p.matcher(query);
            aparam = "";
            try {
                log.info("Parameter Map is: " + params);
                while (m.find()) {
                    aparam = query.substring(m.start() + 2, m.end() - 1);
                    query = query.replaceAll("(\\$\\{" + aparam + "\\})",
                            Matcher.quoteReplacement(StringEscapeUtils.escapeSql(params.get(aparam))));
                    m = p.matcher(query);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            resultSet = subLevel.executeQuery(query);
            if (resultSet.next()) {
                subEntityData = getFields(processor.toMap(resultSet), resultSet, subEntity, null, entityMap);
                if (subEntityData.size() > 0)
                    entityMap.put(subEntity.name, subEntityData);
            }
            resultSet.close();
            subLevel.close();
        }
    }
    return entityMap;
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditN3GeneratorVTwo.java

protected String subInMultiLiterals(String var, List<Literal> values, String n3) {
    if (n3 == null) {
        log.error("subInMultiLiterals was passed a null n3 String");
        return "blankBecauseTargetOrValueWasNull";
    } else if (var == null) {
        log.warn("subInMultiLiterals was passed a null var name");
        return n3;
    } else if (values == null) {
        log.debug("subInMultiLiterals was passed a null value for var '" + var + "'; returning target: '" + n3
                + "'");
        return n3;
    }/*from w w w.j av a2s .c om*/
    String tmp = n3;

    //make the multivalue literal string
    List<String> n3Values = new ArrayList<String>(values.size());
    for (Literal value : values) {
        if (value != null) {
            n3Values.add(formatLiteral(value));
        } else {
            log.debug("value of literal for " + var + " was null");
        }
    }
    String valueString = org.apache.commons.lang.StringUtils.join(n3Values, ",");

    //Substitute it in to n3
    String varRegex = "\\?" + var + "(?=\\p{Punct}|\\p{Space}|$)";

    String out = null;
    if (valueString != null)
        out = tmp.replaceAll(varRegex, Matcher.quoteReplacement(valueString));
    else
        out = n3;

    return out;
}

From source file:org.apache.beam.sdk.io.LocalFileSystem.java

private MatchResult matchOne(String spec) throws IOException {
    if (spec.toLowerCase().startsWith("file:")) {
        spec = spec.substring("file:".length());
    }//from  w w  w .ja  va2  s  .  c  o m

    if (SystemUtils.IS_OS_WINDOWS) {
        List<String> prefixes = Arrays.asList("///", "/");
        for (String prefix : prefixes) {
            if (spec.toLowerCase().startsWith(prefix)) {
                spec = spec.substring(prefix.length());
            }
        }
    }

    File file = Paths.get(spec).toFile();
    if (file.exists()) {
        return MatchResult.create(Status.OK, ImmutableList.of(toMetadata(file)));
    }

    File parent = file.getAbsoluteFile().getParentFile();
    if (!parent.exists()) {
        return MatchResult.create(Status.NOT_FOUND, Collections.<Metadata>emptyList());
    }

    // Method getAbsolutePath() on Windows platform may return something like
    // "c:\temp\file.txt". FileSystem.getPathMatcher() call below will treat
    // '\' (backslash) as an escape character, instead of a directory
    // separator. Replacing backslash with double-backslash solves the problem.
    // We perform the replacement on all platforms, even those that allow
    // backslash as a part of the filename, because Globs.toRegexPattern will
    // eat one backslash.
    String pathToMatch = file.getAbsolutePath().replaceAll(Matcher.quoteReplacement("\\"),
            Matcher.quoteReplacement("\\\\"));

    final PathMatcher matcher = java.nio.file.FileSystems.getDefault().getPathMatcher("glob:" + pathToMatch);

    // TODO: Avoid iterating all files: https://issues.apache.org/jira/browse/BEAM-1309
    Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().preOrderTraversal(parent);
    Iterable<File> matchedFiles = Iterables.filter(files,
            Predicates.and(com.google.common.io.Files.isFile(), new Predicate<File>() {
                @Override
                public boolean apply(File input) {
                    return matcher.matches(input.toPath());
                }
            }));

    List<Metadata> result = Lists.newLinkedList();
    for (File match : matchedFiles) {
        result.add(toMetadata(match));
    }
    if (result.isEmpty()) {
        // TODO: consider to return Status.OK for globs.
        return MatchResult.create(Status.NOT_FOUND,
                new FileNotFoundException(String.format("No files found for spec: %s.", spec)));
    } else {
        return MatchResult.create(Status.OK, result);
    }
}

From source file:com.adobe.acs.commons.rewriter.impl.StaticReferenceRewriteTransformerFactory.java

private String handleMatchingPatternAttribute(Pattern pattern, String attrValue) {
    String unescapedValue = StringEscapeUtils.unescapeHtml(attrValue);
    Matcher m = pattern.matcher(unescapedValue);
    StringBuffer sb = new StringBuffer(unescapedValue.length());

    while (m.find()) {
        String url = m.group(1);/*ww  w.  ja v  a 2s. com*/
        for (String prefix : prefixes) {
            if (url.startsWith(prefix)) {
                // prepend host
                url = prependHostName(url);
                m.appendReplacement(sb, Matcher.quoteReplacement(url));
                // First prefix match wins
                break;
            }
        }

    }
    m.appendTail(sb);

    return sb.toString();
}

From source file:ch.ksfx.web.services.seriesbrowser.SeriesBrowser.java

public void openNode(NavigationTreeNode ntn, StringBuilder markup, ComponentResources componentResources,
        List<String> nodes, List<String> filteredSeriesNames, List<String> openedNodes) {
    for (NavigationTreeNode child : ntn.getChildrens()) {
        openedNodes.add(child.getLocator());

        if (nodes.contains(child.getLocator())) {
            markup.append(snip/* w  w  w. ja va 2s .  c  om*/
                    .replaceAll("#MARGIN#",
                            (new Integer(margin * StringUtils.countMatches(child.getLocator(), "-")))
                                    .toString())
                    .replaceAll("#NAME#",
                            Matcher.quoteReplacement("<a href='"
                                    + componentResources.createEventLink("closeNode", child.getLocator())
                                            .toURI()
                                    + "'><span class=\"glyphicon glyphicon-folder-open\"></span>&nbsp;&nbsp;"
                                    + child.getName() + "</a> "
                                    + getCategoryTitleMarkupForLocator(child.getLocator()))));
            for (TimeSeries ts : child.getSeries()) {
                if (filteredSeriesNames == null || filteredSeriesNames.isEmpty()
                        || filteredSeriesNames.contains(ts.getName())) {
                    markup.append(snip
                            .replaceAll("#MARGIN#",
                                    (new Integer(
                                            margin * (StringUtils.countMatches(child.getLocator(), "-") + 1)))
                                                    .toString())
                            .replaceAll("#NAME#",
                                    "<a href='"
                                            + pageRenderLinkSource.createPageRenderLinkWithContext(
                                                    "viewTimeSeries", ts.getId()).toURI()
                                            + "'><span class=\"glyphicon glyphicon-th-list\"></span>&nbsp;"
                                            + ts.getName() + "</a>"));
                }
            }

            openNode(child, markup, componentResources, nodes, filteredSeriesNames, openedNodes);
        } else {
            markup.append(snip
                    .replaceAll("#MARGIN#",
                            (new Integer(margin * StringUtils.countMatches(child.getLocator(), "-")))
                                    .toString())
                    .replaceAll("#NAME#",
                            Matcher.quoteReplacement("<a href='"
                                    + componentResources.createEventLink("openNode", child.getLocator()).toURI()
                                    + "'><span class=\"glyphicon glyphicon-folder-close\"></span>&nbsp;&nbsp;"
                                    + child.getName() + "</a> "
                                    + getCategoryTitleMarkupForLocator(child.getLocator()))));
        }
    }
}

From source file:co.pugo.convert.ConvertServlet.java

/**
 * search and replace image links with base64 encoded image
 * @param content document content as String
 * @param imageData map of extracted imageData
 * @return content after image links have been replaced with base64 code
 *///from   ww w.j a v  a 2 s  .co m
private String replaceImgSrcWithBase64(String content, Map<String, String> imageData) {
    for (Entry<String, String> entry : imageData.entrySet()) {
        String base64String = entry.getValue();
        Tika tika = new Tika();
        String mimeType = tika.detect(Base64.decodeBase64(base64String));
        content = content.replaceAll(entry.getKey(),
                Matcher.quoteReplacement("data:" + mimeType + ";base64," + base64String));
    }
    return content;
}

From source file:org.wso2.esb.integration.common.utils.ESBIntegrationTest.java

protected void loadESBConfigurationFromClasspath(String relativeFilePath) throws Exception {
    relativeFilePath = relativeFilePath.replaceAll("[\\\\/]", Matcher.quoteReplacement(File.separator));

    OMElement synapseConfig = esbUtils.loadResource(relativeFilePath);
    updateESBConfiguration(synapseConfig);

}

From source file:com.aptana.jira.core.JiraManager.java

/**
 * Creates a JIRA ticket.//from w w w  . j  a  va  2s .  com
 * 
 * @param type
 *            the issue type (bug, feature, or improvement)
 * @param priority
 *            the issue's priority
 * @param severity
 *            the issue's severity (Blocker, Major, Minor, Trivial, None)
 * @param summary
 *            the summary of the ticket
 * @param description
 *            the description of the ticket
 * @return the JIRA issue created
 * @throws JiraException
 * @throws IOException
 */
public JiraIssue createIssue(JiraIssueType type, JiraIssueSeverity severity, String summary, String description)
        throws JiraException, IOException {
    if (user == null) {
        throw new JiraException(Messages.JiraManager_ERR_NotLoggedIn);
    }

    HttpURLConnection connection = null;
    try {
        connection = createConnection(getCreateIssueURL(), user.getUsername(), user.getPassword());
        connection.setRequestMethod("POST"); //$NON-NLS-1$
        connection.setDoOutput(true);
        String severityJSON;
        String versionString;
        if ((TITANIUM_COMMUNITY.equals(projectKey) && type == JiraIssueType.IMPROVEMENT)
                || (!TITANIUM_COMMUNITY.equals(projectKey) && type != JiraIssueType.BUG)) {
            // Improvements in TC don't get Severities, nor do Story or Improvements in Aptana Studio!
            severityJSON = StringUtil.EMPTY;
        } else {
            severityJSON = severity.getParameterValue() + ",\n"; //$NON-NLS-1$
        }

        // If we're submitting against TC, we can't do version, we need to stuff that into the Environment
        if (TITANIUM_COMMUNITY.equals(projectKey)) {
            versionString = MessageFormat.format("\"{0}\": \"{1}\"", PARAM_ENVIRONMENT, getProjectVersion()); //$NON-NLS-1$
        } else {
            versionString = "\"" + PARAM_VERSION + "\": [{\"name\": \"" + getProjectVersion() + "\"}]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
        // @formatter:off
        String data = "{\n" + //$NON-NLS-1$
                "    \"fields\": {\n" + //$NON-NLS-1$
                "       \"project\":\n" + //$NON-NLS-1$
                "       { \n" + //$NON-NLS-1$
                "          \"key\": \"" + projectKey + "\"\n" + //$NON-NLS-1$ //$NON-NLS-2$
                "       },\n" + //$NON-NLS-1$
                "       \"summary\": \"" + summary.replaceAll("\"", "'") + "\",\n" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                "       \"description\": \"" //$NON-NLS-1$
                + description.replaceAll("\"", "'").replaceAll("\n", Matcher.quoteReplacement("\\n")) + "\",\n" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$//$NON-NLS-5$
                + "       \"issuetype\": {\n" + "          \"name\": \"" + type.getParameterValue(projectKey) + "\"\n" + //$NON-NLS-3$
                "       },\n" + //$NON-NLS-1$
                severityJSON + "       " + versionString + "\n" + //$NON-NLS-1$ //$NON-NLS-2$
                "   }\n" + //$NON-NLS-1$
                "}"; //$NON-NLS-1$
        // @formatter:on

        OutputStream out = connection.getOutputStream();
        IOUtil.write(out, data);
        out.close();

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
            String output = IOUtil.read(connection.getInputStream());
            return createIssueFromJSON(output);
        }
        // failed to create the ticket
        // TODO Parse the response as JSON!
        throw new JiraException(IOUtil.read(connection.getErrorStream()));
    } catch (JiraException je) {
        throw je;
    } catch (Exception e) {
        throw new JiraException(e.getMessage(), e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}