Example usage for java.util.regex Pattern quote

List of usage examples for java.util.regex Pattern quote

Introduction

In this page you can find the example usage for java.util.regex Pattern quote.

Prototype

public static String quote(String s) 

Source Link

Document

Returns a literal pattern String for the specified String .

Usage

From source file:hydrograph.ui.propertywindow.widgets.dialogs.lookup.LookupMapDialog.java

private void attachDropFunctionalityToMappingTable() {
    Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
    int operations = DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
    DropTarget target = new DropTarget(mappingTableViewer.getTable(), operations);
    target.setTransfer(types);/*  w w w .ja v a2  s  .  com*/
    target.addDropListener(new DropTargetAdapter() {
        public void dragOver(DropTargetEvent event) {
            event.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
        }

        public void drop(DropTargetEvent event) {
            if (event.data == null) {
                event.detail = DND.DROP_NONE;
                return;
            }

            String[] dropData = ((String) event.data).split(Pattern.quote(MAPPING_TABLE_ITEM_DELIMILATOR));
            for (String data : dropData) {
                LookupMapProperty mappingTableItem = new LookupMapProperty();
                mappingTableItem.setSource_Field(data);
                mappingTableItem.setOutput_Field(data.split("\\.")[1]);
                mappingTableItemList.add(mappingTableItem);

                mappingTableViewer.refresh();
            }
            refreshButtonStatus();
        }
    });
}

From source file:com.kixeye.chassis.bootstrap.configuration.ConfigurationBuilder.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void initApplicationFileConfiguration() {
    if (applicationPropertiesPath == null) {
        LOGGER.debug("No client application properties to configure. Skipping...");
        applicationFileConfiguration = new ConcurrentMapConfiguration();
        return;//  ww w. jav a2  s.  co  m
    }

    this.applicationFileConfiguration = new ConcurrentCompositeConfiguration();

    String path = SystemPropertyUtils.resolvePlaceholders(applicationPropertiesPath);
    LOGGER.debug("Configuring client application properties from path " + applicationPropertiesPath);

    Map applicationProperties = new Properties();

    if (SystemUtils.IS_OS_WINDOWS) {
        if (path.startsWith("file://")) {
            if (!path.startsWith("file:///")) {
                path = path.replaceFirst(Pattern.quote("file://"), "file:///");
            }
        }
    }

    try (InputStream is = resourceLoader.getResource(path).getInputStream()) {
        ((Properties) applicationProperties).load(is);
    } catch (Exception e) {
        BootstrapException.resourceLoadingFailed(path, applicationPropertiesPath, e);
    }

    Map environmentApplicationProperties = getEnvironmentSpecificProperties(path);
    if (environmentApplicationProperties != null) {
        ((ConcurrentCompositeConfiguration) this.applicationFileConfiguration)
                .addConfiguration(new ConcurrentMapConfiguration(environmentApplicationProperties));
    }
    ((ConcurrentCompositeConfiguration) this.applicationFileConfiguration)
            .addConfiguration(new ConcurrentMapConfiguration(applicationProperties));

    if (applicationFileConfiguration.containsKey(BootstrapConfigKeys.PUBLISH_DEFAULTS_KEY.getPropertyName())) {
        this.publishDefaults = applicationFileConfiguration
                .getBoolean(BootstrapConfigKeys.PUBLISH_DEFAULTS_KEY.getPropertyName());
    }
}

From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java

public void test() throws Exception {
    List<List<String>> commands = new ArrayList<List<String>>();

    // CLI uses groovy to parse the path which requires either a double backslash or a single slash
    String applicationAbsolutePath = applicationFile.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/");

    List<String> boostrapApplicationCommand = Arrays.asList("azure:bootstrap-app", "--verbose", "-timeout",
            String.valueOf(TIMEOUT_IN_MINUTES), "-progress", String.valueOf(POLLING_INTERVAL_IN_MINUTES),
            "-azure-svc", AZURE_HOSTED_SERVICE, "-azure-pwd", RDP_PFX_FILE_PASSWORD, "-azure-location",
            "'" + AZURE_REGION + "'", applicationAbsolutePath);

    commands.add(boostrapApplicationCommand);
    runCliCommands(cliExecutablePath, commands, isDebugMode);
    commands.clear();//from   w  ww. java2  s.co m

    String deploymentUrl = deployment.getUrl();

    final URL restAdminMachinesUrl = getMachinesUrl(deploymentUrl);

    log("Getting number of running machines");

    repetativeAssert("Number of machines", new RepetativeConditionProvider() {
        @Override
        public boolean getCondition() {
            try {
                int numberOfMachines = getNumberOfMachines(restAdminMachinesUrl);
                logger.info("Actual numberOfMachines=" + numberOfMachines + ". Expected numberOfMachins="
                        + EXPECTED_NUMBER_OF_MACHINES);
                return EXPECTED_NUMBER_OF_MACHINES == numberOfMachines;
            } catch (Exception e) {
                logger.log(Level.WARNING, "Exception while calculating numberOfMachines", e);
                return false;
            }
        }
    });

    List<String> connectCommand = Arrays.asList("azure:connect-app", "--verbose", "-timeout 5", "-azure-svc",
            AZURE_HOSTED_SERVICE);

    List<String> installApplicationCommand = Arrays.asList("install-application", "--verbose",
            applicationAbsolutePath);

    commands.add(connectCommand);
    commands.add(installApplicationCommand);
    runCliCommands(cliExecutablePath, commands, isDebugMode);
    commands.clear();

    final URI travelApplicationUrl = getTravelApplicationUrl(deploymentUrl).toURI();

    RepetativeConditionProvider applicationInstalledCondition = new RepetativeConditionProvider() {
        @Override
        public boolean getCondition() {
            try {
                URL url = travelApplicationUrl.toURL();
                return isUrlAvailable(url);
            } catch (Exception e) {
                logger.log(Level.WARNING,
                        "Exception while checking if " + travelApplicationUrl.toString() + " is available", e);
                return false;
            }
        }
    };

    repetativeAssert("Failed waiting for travel application", applicationInstalledCondition);

    List<String> setInstancesScaleOutCommand = Arrays.asList("azure:set-instances", "--verbose", "-azure-svc",
            AZURE_HOSTED_SERVICE, TOMCAT_SERVICE, NUMBER_OF_INSTANCES_FOR_TOMCAT_SERVICE);

    commands.add(connectCommand);
    commands.add(setInstancesScaleOutCommand);
    runCliCommands(cliExecutablePath, commands, isDebugMode);
    commands.clear();

    repetativeAssert("Failed waiting for scale out", new RepetativeConditionProvider() {
        @Override
        public boolean getCondition() {
            try {
                int numberOfMachines = getNumberOfMachines(restAdminMachinesUrl);
                logger.info("Actual numberOfMachines=" + numberOfMachines + ". Expected numberOfMachins="
                        + (EXPECTED_NUMBER_OF_MACHINES + 1));
                return numberOfMachines == EXPECTED_NUMBER_OF_MACHINES + 1;
            } catch (Exception e) {
                logger.log(Level.WARNING, "Exception while calculating numberOfMachines", e);
                return false;
            }
        }
    });

    List<String> uninstallApplicationCommand = Arrays.asList("uninstall-application", "--verbose", "-timeout",
            String.valueOf(TIMEOUT_IN_MINUTES), APPLICATION_NAME);

    commands.add(connectCommand);
    commands.add(uninstallApplicationCommand);
    runCliCommands(cliExecutablePath, commands, isDebugMode);
    commands.clear();

    Assert.assertFalse("Travel application should not be running",
            isUrlAvailable(travelApplicationUrl.toURL()));

    List<String> setInstancesScaleInCommand = Arrays.asList("azure:set-instances", "--verbose", "-azure-svc",
            AZURE_HOSTED_SERVICE, TOMCAT_SERVICE, INITIAL_NUMBER_OF_INSTANCES_FOR_TOMCAT_SERVICE);

    commands.add(connectCommand);
    commands.add(setInstancesScaleInCommand);
    runCliCommands(cliExecutablePath, commands, isDebugMode);
    commands.clear();

    repetativeAssert("Failed waiting for scale in", new RepetativeConditionProvider() {
        @Override
        public boolean getCondition() {
            try {
                int numberOfMachines = getNumberOfMachines(restAdminMachinesUrl);
                logger.info("Actual numberOfMachines=" + numberOfMachines + ". Expected numberOfMachins="
                        + EXPECTED_NUMBER_OF_MACHINES);
                return EXPECTED_NUMBER_OF_MACHINES == numberOfMachines;
            } catch (Exception e) {
                logger.log(Level.WARNING, "Exception while calculating numberOfMachines", e);
                return false;
            }
        }
    });

    commands.add(connectCommand);
    commands.add(installApplicationCommand);
    runCliCommands(cliExecutablePath, commands, isDebugMode);
    commands.clear();

    repetativeAssert("Failed waiting for travel application", applicationInstalledCondition);

}

From source file:net.sourceforge.cobertura.reporting.ComplexityCalculator.java

/**
 * Computes CCN for a method./* w ww  .ja  v a2 s . c o  m*/
 *
 * @param classData        class data for the class which contains the method to compute CCN for
 * @param methodName       the name of the method to compute CCN for
 * @param methodDescriptor the descriptor of the method to compute CCN for
 * @return CCN for the method
 * @throws NullPointerException if <code>classData</code> is <code>null</code>
 */
public int getCCNForMethod(ClassData classData, String methodName, String methodDescriptor) {
    if (!calculateMethodComplexity) {
        return 0;
    }

    Validate.notNull(classData, "classData must not be null");
    Validate.notNull(methodName, "methodName must not be null");
    Validate.notNull(methodDescriptor, "methodDescriptor must not be null");

    int complexity = 0;
    List<FunctionMetric> methodMetrics = getFunctionMetricsForSingleFile(classData.getSourceFileName());

    // golden method = method for which we need ccn
    String goldenMethodName = methodName;
    boolean isConstructor = false;
    if (goldenMethodName.equals("<init>")) {
        isConstructor = true;
        goldenMethodName = classData.getBaseName();
    }
    // fully-qualify the method
    goldenMethodName = classData.getName() + "." + goldenMethodName;
    // replace nested class separator $ by .
    goldenMethodName = goldenMethodName.replaceAll(Pattern.quote("$"), ".");

    TraceSignatureVisitor v = new TraceSignatureVisitor(Opcodes.ACC_PUBLIC);
    SignatureReader r = new SignatureReader(methodDescriptor);
    r.accept(v);

    // for the scope of this method, signature = signature of the method excluding the method name
    String goldenSignature = v.getDeclaration();
    // get parameter type list string which is enclosed by round brackets ()
    goldenSignature = goldenSignature.substring(1, goldenSignature.length() - 1);

    // collect all the signatures with the same method name as golden method
    Map<String, Integer> candidateSignatureToCcn = new HashMap<String, Integer>();
    for (FunctionMetric singleMethodMetrics : methodMetrics) {
        String candidateMethodName = singleMethodMetrics.name.substring(0,
                singleMethodMetrics.name.indexOf('('));
        String candidateSignature = stripTypeParameters(singleMethodMetrics.name
                .substring(singleMethodMetrics.name.indexOf('(') + 1, singleMethodMetrics.name.length() - 1));
        if (goldenMethodName.equals(candidateMethodName)) {
            candidateSignatureToCcn.put(candidateSignature, singleMethodMetrics.ccn);
        }
    }

    // if only one signature, no signature matching needed
    if (candidateSignatureToCcn.size() == 1) {
        return candidateSignatureToCcn.values().iterator().next();
    }

    // else, do signature matching and find the best match

    // update golden signature using reflection
    if (!goldenSignature.isEmpty()) {
        try {
            String[] goldenParameterTypeStrings = goldenSignature.split(",");
            Class<?>[] goldenParameterTypes = new Class[goldenParameterTypeStrings.length];
            for (int i = 0; i < goldenParameterTypeStrings.length; i++) {
                goldenParameterTypes[i] = ClassUtils.getClass(goldenParameterTypeStrings[i].trim(), false);
            }
            Class<?> klass = ClassUtils.getClass(classData.getName(), false);
            if (isConstructor) {
                Constructor<?> realMethod = klass.getDeclaredConstructor(goldenParameterTypes);
                goldenSignature = realMethod.toGenericString();
            } else {
                Method realMethod = klass.getDeclaredMethod(methodName, goldenParameterTypes);
                goldenSignature = realMethod.toGenericString();
            }
            // replace varargs ellipsis with array notation
            goldenSignature = goldenSignature.replaceAll("\\.\\.\\.", "[]");
            // extract the parameter type list string
            goldenSignature = goldenSignature.substring(goldenSignature.indexOf("(") + 1,
                    goldenSignature.length() - 1);
            // strip the type parameters to get raw types
            goldenSignature = stripTypeParameters(goldenSignature);
        } catch (Exception e) {
            logger.error("Error while getting method CC for " + goldenMethodName, e);
            return 0;
        }
    }
    // replace nested class separator $ by .
    goldenSignature = goldenSignature.replaceAll(Pattern.quote("$"), ".");

    // signature matching - due to loss of fully qualified parameter types from JavaCC, get ccn for the closest match
    double signatureMatchPercentTillNow = 0;
    for (Entry<String, Integer> candidateSignatureToCcnEntry : candidateSignatureToCcn.entrySet()) {
        String candidateSignature = candidateSignatureToCcnEntry.getKey();
        double currentMatchPercent = matchSignatures(candidateSignature, goldenSignature);
        if (currentMatchPercent == 1) {
            return candidateSignatureToCcnEntry.getValue();
        }
        if (currentMatchPercent > signatureMatchPercentTillNow) {
            complexity = candidateSignatureToCcnEntry.getValue();
            signatureMatchPercentTillNow = currentMatchPercent;
        }
    }

    return complexity;
}

From source file:dk.deck.resolver.ArtifactResolverRemote.java

private String getSnapshotItemPath(Artifact artifact, MavenVersion version, String timestamp,
        String buildNumber) {//from   ww  w. ja v  a  2 s  . c  o  m
    String artifactPath = artifact.getGroupId().replaceAll(Pattern.quote("."), Matcher.quoteReplacement("/"))
            + "/" + artifact.getArtifactId();
    String artifactVersionPath = artifactPath + "/" + artifact.getVersion();

    String snapshotVersion = version.toSnapshotString(timestamp, buildNumber);
    String artifactFilename = artifact.getArtifactId() + "-" + snapshotVersion + "." + artifact.getPackaging();
    if (!artifact.getClassifier().isEmpty()) {
        artifactFilename = artifact.getArtifactId() + "-" + snapshotVersion + "-" + artifact.getClassifier()
                + "." + artifact.getPackaging();
    }

    String artifactItemPath = artifactVersionPath + "/" + artifactFilename;
    return artifactItemPath;
}

From source file:edu.kit.dama.staging.adapters.DefaultStorageVirtualizationAdapter.java

/**
 * Create the destination folder for the ingest. This folder is located
 * withing the storage virtualization system. For this very basic adapter it
 * will be a folder with with a fixed scheme telling when the object was
 * uploaded by whom and which transfer id it had. The folder will be
 * generated as follows:/*  w w  w  .  j a v  a2s.c om*/
 *
 * <i>archiveURL</i>/<i>pathPattern</i>/SHA1(pTransferId) where
 * <i>pathPattern</i> allows the use or variables like $year, $month, $day
 * and $owner and pTransferId is the numeric id of the transfer.
 *
 * @param pTransferId The transfer id as it comes from the ingest
 * information entity.
 * @param pOwner The owner who ingested the object.
 *
 * @return An AbstractFile representing the destination for the final
 * ingest.
 *
 */
private AbstractFile createDestination(String pTransferId, IAuthorizationContext pContext) {
    if (pTransferId == null) {//transfer id is part of the destination, so it must not be null
        throw new IllegalArgumentException("Argument 'pTransferId' must not be 'null'");
    }

    String sUrl = archiveUrl.toString();
    if (pathPattern != null) {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        String dynPath = pathPattern;
        dynPath = dynPath.replaceAll(Pattern.quote(YEAR_PATTERN), Integer.toString(year))
                .replaceAll(Pattern.quote(MONTH_PATTERN), Integer.toString(month))
                .replaceAll(Pattern.quote(DAY_PATTERN), Integer.toString(day));
        if (dynPath.contains(OWNER_PATTERN) || dynPath.contains(GROUP_PATTERN)) {//owner/group should be replaced by pattern definition
            if (pContext == null) {//uploader is 'null' but we need it for replacement
                throw new IllegalArgumentException(
                        "Argument 'pOwner' must not be 'null' if pattern contains element '" + OWNER_PATTERN
                                + "' or '" + GROUP_PATTERN + "'");
            } else {//everything is fine

                LOGGER.debug("Replacing owner/group pattern with values from context '{}'", pContext);
                dynPath = dynPath
                        .replaceAll(Pattern.quote(OWNER_PATTERN),
                                Matcher.quoteReplacement(pContext.getUserId().getStringRepresentation()))
                        .replaceAll(Pattern.quote(GROUP_PATTERN),
                                Matcher.quoteReplacement(pContext.getGroupId().getStringRepresentation()));
            }
        }
        LOGGER.debug("Appending pattern-based path '{}' to base destination '{}'",
                new Object[] { dynPath, sUrl });
        sUrl += "/" + dynPath;
    }

    //finally, create abstract file and return
    AbstractFile result;
    try {
        if (!sUrl.endsWith("/")) {
            sUrl += "/";
        }
        LOGGER.debug("Appending SHA1-hashed transfer ID '{}' to current destination '{}'.",
                new Object[] { pTransferId, sUrl });
        sUrl += CryptUtil.stringToSHA1(pTransferId);
        LOGGER.debug("Preparing destination at {}.", sUrl);

        result = new AbstractFile(new URL(sUrl));
        Configuration config = result.getConfiguration();
        String context = pContext.getUserId().getStringRepresentation() + " "
                + pContext.getGroupId().getStringRepresentation();
        LOGGER.debug("Adding repository context {} to custom access protocol configuration.", context);
        config.setProperty("repository.context", context);
        result = new AbstractFile(new URL(sUrl), config);

        //check if destination exists and create it if required
        if (result.exists()) {
            LOGGER.info("Destination at '{}' already exists.", sUrl);
        } else {//try to create destination
            result = AbstractFile.createDirectory(result);
        }

        //check destination
        if (result != null) {//destination could be obtained
            result.clearCachedValues();
            if (result.isReadable() && result.isWriteable()) {
                //everything is fine...return result
                return result;
            } else {
                //destination cannot be accessed
                LOGGER.error("Destination '{}' exists but is not read- or writeable", sUrl);
                result = null;
            }
        } else {
            LOGGER.warn("No result obtained from directory creation.");
        }
    } catch (MalformedURLException mue) {
        LOGGER.error("Failed to create valid destination URL for '" + sUrl + "' and transferId " + pTransferId,
                mue);
        result = null;
    } catch (AdalapiException ae) {
        LOGGER.error("Failed to check/create destination for '" + sUrl + "'", ae);
        result = null;
    }
    return result;
}

From source file:de.tarent.maven.plugins.pkg.AbstractMvnPkgPluginTestCase.java

protected boolean rpmContainsArtifact(String s) throws MojoExecutionException, IOException {
    final Pattern p = Pattern.compile(".*" + Pattern.quote(s) + ".*");
    return rpmContains(p, "--dump");
}

From source file:com.kegare.caveworld.util.CaveUtils.java

public static boolean containsIgnoreCase(String s1, String s2) {
    if (Strings.isNullOrEmpty(s1) || Strings.isNullOrEmpty(s2)) {
        return false;
    }/*from   w  w w  .j a  v a  2 s . c  om*/

    return Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find();
}

From source file:org.springjutsu.validation.ValidationEvaluationContext.java

/**
 * Performs the following operations to localize a sub path
 * (e.g. rule path) to the current context:
 * 1) prepends with template base paths//w ww.ja v  a  2  s  .  com
 * 2) prepends resultant path with nestedPath
 * 3) applies collection replacements 
 * @param subPath the path to localize
 * @return currently localizedPath
 */
protected String localizePath(String subPath) {
    if (PathUtils.containsEL(subPath)) {
        return subPath;
    }
    String localizedPath = PathUtils.appendPath(PathUtils.joinPathSegments(nestedPath),
            PathUtils.joinPathSegments(templateBasePaths), subPath);
    // Apply collection path replacements.
    // Multiple collection paths may build off of one another,
    // so it is important to run all possible path replacements.
    // Path replacement order is maintained by the use of a LinkedHashMap
    for (Map.Entry<String, String> collectionPathReplacement : collectionPathReplacements.entrySet()) {
        if (localizedPath.startsWith(collectionPathReplacement.getKey())) {
            localizedPath = localizedPath.replaceAll("^" + Pattern.quote(collectionPathReplacement.getKey()),
                    collectionPathReplacement.getValue());
        }
    }
    return localizedPath;
}

From source file:adalid.util.velocity.MavenArchetypeBuilder.java

private String alias(boolean shift) {
    final String sep = "[\\_\\-\\.]+";
    final String invalid = "[^a-z0-9]";
    String quoted = Pattern.quote(packageName);
    String prefix = "^" + quoted + sep;
    String suffix = sep + quoted + "$";
    String toUpperCase = shift ? ".toUpperCase()" : "";
    return "${artifactId.toLowerCase()" + remove(prefix) + remove(suffix) + remove(invalid) + toUpperCase + "}";
}