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:org.mybatisorm.annotation.handler.JoinHandler.java

private String getExplicitJoin(String joinHint, List<Field> fields) {
    StringBuilder sb = new StringBuilder();

    TableHandler handler;/*from w ww.ja va 2s . c om*/
    List<Field> fieldList = new ArrayList<Field>();
    Class<?> clazz;
    Field field;

    Hashtable<Set<Class<?>>, LinkedList<Field[]>> refMap = null;
    if (!Pattern.compile(Pattern.quote(" ON "), Pattern.CASE_INSENSITIVE).matcher(joinHint).find()) {
        refMap = getRefMap(fields);
        if (refMap.isEmpty())
            throw new InvalidAnnotationException("The references for join has not been found");
    }

    QueryTokenizer tokenizer = new QueryTokenizer(joinHint);
    QueryTokenizer.TokenType type;
    String text;
    boolean onRequired = false;

    // processing the first class
    type = tokenizer.next();
    if (type != QueryTokenizer.TokenType.IDENTIFIER)
        throw new InvalidJoinException("The join hint must start with the property name.");
    text = tokenizer.getText();
    field = getField(text);
    fieldList.add(field);
    clazz = field.getType();
    handler = HandlerFactory.getHandler(clazz);
    sb.append(handler.getName()).append(" ").append(text).append("_");

    while ((type = tokenizer.next()) != QueryTokenizer.TokenType.EOS) {
        text = tokenizer.getText();
        switch (type) {
        case IDENTIFIER:
            field = getField(text);
            fieldList.add(field);
            clazz = field.getType();
            handler = HandlerFactory.getHandler(clazz);

            sb.append(handler.getName()).append(" ").append(text).append("_");
            onRequired = true;
            break;
        case CLASS_FIELD:
            String[] s = text.split("\\.");
            sb.append(s[0]).append("_.");
            field = getField(getField(s[0]).getType(), s[1]);
            sb.append(ColumnAnnotation.getName(field));
            break;
        case ON:
            onRequired = false;
            sb.append(text);
            break;
        case WS:
            sb.append(text);
            break;
        case ETC:
            if (onRequired) {
                sb.append(getOnPhrase(fieldList, refMap));
                onRequired = false;
            }
            sb.append(text);
            break;
        }
    }
    if (onRequired) {
        sb.append(getOnPhrase(fieldList, refMap));
    }
    return sb.toString();
}

From source file:com.orange.clara.cloud.servicedbdumper.acceptance.AcceptanceExternalTest.java

protected boolean isCfCliAvailableInPath() {
    String exec = "cf";
    return Stream.of(System.getenv("PATH").split(Pattern.quote(File.pathSeparator))).map(Paths::get)
            .anyMatch(path -> Files.exists(path.resolve(exec)));
}

From source file:eu.matejkormuth.rpgdavid.starving.listeners.HiddenCommandsListener.java

@EventHandler
private void onCommand(final PlayerCommandPreprocessEvent event) {
    // Command for listing all items.
    if (event.getMessage().equalsIgnoreCase("/items")) {
        List<Item> items = Starving.getInstance().getItemManager().getItems();
        for (int j = 0; j < items.size(); j++) {
            Item i = items.get(j);//w  ww.  ja va  2s  .  c o m
            event.getPlayer().sendMessage(j + " - " + i.getName());
        }
    }
    // Command for giving custom items.
    else if (event.getMessage().contains("/itemsgive")) {
        List<Item> items = Starving.getInstance().getItemManager().getItems();
        for (int j = 0; j < items.size(); j++) {
            Item i = items.get(j);
            if (j == Integer.valueOf(event.getMessage().split(Pattern.quote(" "))[1])) {
                event.getPlayer().getInventory().addItem(i.toItemStack());
            }

        }
    }
    // Command for giving custom chemicals.
    else if (event.getMessage().contains("/chemical")) {
        if (!event.getMessage().contains(" ")) {
            event.getPlayer().sendMessage("args missing!");
        }

        String args = event.getMessage().split(Pattern.quote(" "))[1];
        String[] chemicals = args.split(Pattern.quote(","));

        ChemicalItem ci = new ChemicalItem("spawnedChemicalItem", new ChemicalCompound()) {
            @Override
            public Recipe getRecipe() {
                return null;
            }

            @Override
            protected void onConsume0(Player player) {
            }
        };

        for (String chemical : chemicals) {
            String[] parts = chemical.split(Pattern.quote(":"));
            String name = parts[0];
            String amount = parts[1];
            for (Chemical ch : Chemicals.all()) {
                if (ch.getName().equalsIgnoreCase(name)) {
                    ci.getContents().add(ch, Float.valueOf(amount));
                }
            }
        }

        event.getPlayer().getInventory().addItem(ci.toItemStack());
    }
    // Command for setting entities target.
    else if (event.getMessage().contains("/settarget")) {
        String[] parts = event.getMessage().split(" ");
        int entity = Integer.valueOf(parts[1]);
        int target = Integer.valueOf(parts[2]);
        for (Entity e : Worlds.first().getEntities()) {
            if (e.getEntityId() == target) {
                Starving.getInstance().getZombieManager().get(entity).setFollowTarget(e);
            }
        }
    }
    // Command for spawning zombie walking the dog.
    else if (event.getMessage().contains("/zombieeaster")) {
        ZombieWithDog.spawn(event.getPlayer().getLocation());
    }
    // Command for settings time.
    else if (event.getMessage().contains("/time set")) {
        String[] parts = event.getMessage().split(" ");
        int time = Integer.valueOf(parts[2]);
        event.getPlayer().sendMessage(ChatColor.YELLOW + "[Starving] Shifting time...");
        Starving.getInstance().getRegistered(TimeUpdater.class).vanllaSetMoveTime(time);
        event.getPlayer().sendMessage(ChatColor.GREEN + "[Starving] Time set!");
    }
    // Command for spawning zombie.
    else if (event.getMessage().contains("/zombie")) {
        String[] parts = event.getMessage().split(" ");
        if (parts.length == 2) {
            int count = Integer.valueOf(parts[1]);

            for (int i = 0; i < count; i++) {
                Starving.getInstance().getZombieManager().spawnAt(event.getPlayer().getLocation()
                        .add((Math.random() - 0.5) * count / 4, 0, (Math.random() - 0.5) * count / 4));
            }
        } else {
            Starving.getInstance().getZombieManager().spawnAt(event.getPlayer().getLocation());
        }
    }
    // Command for testing some random things.
    else if (event.getMessage().contains("/darkness")) {
        ((CraftPlayer) event.getPlayer()).getHandle().playerConnection
                .sendPacket(new PacketPlayOutGameStateChange(7, 0.001f));
        ((CraftPlayer) event.getPlayer()).getHandle().playerConnection
                .sendPacket(new PacketPlayOutGameStateChange(8, 160));
    }
    // Command for testing some random things.
    else if (event.getMessage().contains("/npctest")) {
        String name = "debilko" + (int) Math.floor(Math.random() * 1000000);
        NPC npc = Starving.getInstance().getNPCManager().getMainRegistry().createPlayer()
                .withProfile(UUID.nameUUIDFromBytes(name.getBytes()), name)
                .withSpawnLocation(event.getPlayer().getLocation()).spawn();

        event.getPlayer().teleport(npc.getLocation());
    }
    // Command for generating access key.
    else if (event.getMessage().contains("/genkey")) {
        char[] VALID_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();
        int keyLength = 32;
        char[] key = new char[keyLength];
        for (int i = 0; i < keyLength; i++) {
            key[i] = VALID_CHARS[RandomUtils.nextInt(VALID_CHARS.length - 1)];
        }
        event.getPlayer().sendMessage("Your new accesskey is: " + new String(key));
        Data.of(event.getPlayer()).setRemoteAccesKey(new String(key));
        event.getPlayer().sendMessage("http://starving.eu/key.php?key=" + new String(key));
    }
    // Command for opening custom items inventory.
    else if (event.getMessage().contains("/itemsinv")) {
        ItemManager im = Starving.getInstance().getItemManager();
        int size = (im.getItems().size() / 9);
        Inventory inv = Bukkit.createInventory(null, 9 * (size + 1), ChatColor.GOLD + "Custom items: ");
        List<Item> sorted = im.getItems();
        Collections.sort(sorted, new ItemNameComparator());
        for (Item i : sorted) {
            inv.addItem(i.toItemStack());
        }
        event.getPlayer().openInventory(inv);
    }
    // Command for testing some random things.
    else if (event.getMessage().contains("/itemdropvehicle")) {
        org.bukkit.entity.Item i = ItemDrops.drop(event.getPlayer().getLocation(), Items.of(Material.APPLE));
        i.setVelocity(event.getPlayer().getEyeLocation().getDirection().multiply(3));
        i.setPassenger(event.getPlayer());
        i.setPickupDelay(20 * 15);
    }
    // Command for testing some random things.
    else if (event.getMessage().contains("/peadd")) {
        // FIXME: Please, remove this soon. Only for testing.
        ParticleEmitter pe = new ParticleEmitter(new Location(Bukkit.getWorld("Beta"), 571.5, 68, -235.5), 1f,
                40, ParticleEffect.SMOKE_LARGE);
        pe.setOffsets(0.5f, 0.1f, 0.5f);
        pe.setDirection(new Vector(0.1f, 0, 0.15f));
        Starving.getInstance().getParticleEmmiters().add(pe);
        ParticleEmitter pe2 = new ParticleEmitter(new Location(Bukkit.getWorld("Beta"), 571.5, 68, -235.5), 1f,
                80, ParticleEffect.REDSTONE);
        pe2.setOffsets(0.5f, 0.1f, 0.5f);
        pe2.setColor(new ParticleEffect.OrdinaryColor(255, 0, 255));
        //pe2.setDirection(new Vector(0.1f, 0, 0.15f));
        Starving.getInstance().getParticleEmmiters().add(pe2);
    }
    // Command for testing some random things.
    else if (event.getMessage().contains("/peclear")) {
        Starving.getInstance().getParticleEmmiters().clear();
    }
    // Command for testing some random things.
    else if (event.getMessage().contains("/ason")) {
        Starving.getInstance().getAmbientSoundManager().addPlayer(event.getPlayer());
    }
    // Command for testing some random things.
    else if (event.getMessage().contains("/asoff")) {
        Starving.getInstance().getAmbientSoundManager().removePlayer(event.getPlayer());
    }
}

From source file:io.github.apfelcreme.LitePortals.Bungee.LitePortals.java

/**
 * returns the server info with the given ip (xxx.xxx.xxx.xxx.PORT)
 *
 * @param serverIp the ip.port//from  w  w  w  .j  ava  2 s .  c  om
 * @return the serverInfo
 */
public ServerInfo getTargetServer(String serverIp) {
    for (ServerInfo serverInfo : getProxy().getServers().values()) {
        if (serverInfo.getAddress().equals(new InetSocketAddress(serverIp.split(Pattern.quote("."))[0],
                Integer.parseInt(serverIp.split(Pattern.quote("."))[1])))) {
            return serverInfo;
        }
    }
    return null;
}

From source file:com.genentech.chemistry.openEye.apps.SDFALogP.java

private void run(String inFile, boolean outPutCounts) {
    oemolithread ifs = new oemolithread(inFile);
    long start = System.currentTimeMillis();
    int iCounter = 0; //Structures in the SD file.

    OEMolBase mol = new OEGraphMol();
    OEMolBase compMol = new OEGraphMol();
    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;/*www.j a v a2  s .c  om*/

        compMol.Clear();
        oechem.OEAddMols(compMol, mol);
        if (neutralize)
            OETools.neutralize(compMol);

        double alogp = aLogPCalcualtor.computeALogP(compMol);
        oechem.OEAddSDData(mol, ALOGP_TAG, DataFormat.formatNumber(alogp, "r2"));

        if (outPutCounts) {
            int[] counts = aLogPCalcualtor.getAtomCounts();
            for (int i = 1; i < counts.length; i++) {
                if (outputZero || counts[i] > 0)
                    oechem.OEAddSDData(mol, String.format("ALogP_GCount_%03d", i), Integer.toString(counts[i]));
            }
        }

        oechem.OEWriteMolecule(outputOEThread, mol);

        //Output "." to show that the program is running.
        if (iCounter % 100 == 0)
            System.err.print(".");
        if (iCounter % 4000 == 0) {
            System.err.printf(" %d %dsec\n", iCounter, (System.currentTimeMillis() - start) / 1000);
        }
    }

    mol.delete();
    compMol.delete();
    ifs.close();
    inFile = inFile.replaceAll(".*" + Pattern.quote(File.separator), "");
    System.err.printf("%s: Read %d structures from %s. %d sec\n", MY_NAME, iCounter, inFile,
            (System.currentTimeMillis() - start) / 1000);
}

From source file:info.schnatterer.songbirdDbTools.Utils.ResourceUtils.java

/**
 * Get the relative path from one file to another, specifying the directory separator. If one of the provided
 * resources does not exist, it is assumed to be a file unless it ends with '/' or '\'.
 * //w  w  w .j  a v a  2  s.c o  m
 * @param targetPath
 *            targetPath is calculated to this file
 * @param basePath
 *            basePath is calculated from this file
 * @param pathSeparator
 *            directory separator. The platform default is not assumed so that we can test Unix behavior when
 *            running on Windows (for example)
 * @return <code>targetPath</code> relativized to <code>basePath</code>
 * 
 * @author http://stackoverflow.com/questions/204784/how-to-construct-a-relative
 *         -path-in-java-from-two-absolute-paths-or-urls
 */
public static String getRelativePath(final String basePath, final String targetPath,
        final String pathSeparator) {

    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

    // Undo the changes to the separators made by normalization
    if (pathSeparator.equals("/")) {
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

    } else if (pathSeparator.equals("\\")) {
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);

    } else {
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuffer common = new StringBuffer();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex] + pathSeparator);
        commonIndex++;
    }

    if (commonIndex == 0) {
        // No single common path element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        throw new PathResolutionException("No common path element found for '" + normalizedTargetPath
                + "' and '" + normalizedBasePath + "'");
    }

    // The number of directories we have to backtrack depends on whether the
    // base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    //
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a
    // file or dir. It's not perfect, because
    // the resource referred to by this path may not actually exist, but
    // it's the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();

    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }

    StringBuffer relative = new StringBuffer();

    if (base.length != commonIndex) {

        int numDirsUp;
        if (baseIsFile) {
            numDirsUp = base.length - commonIndex - 1;
        } else {
            numDirsUp = base.length - commonIndex;
        }

        for (int i = 0; i < numDirsUp; i++) {
            relative.append(".." + pathSeparator);
        }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
}

From source file:net.oauth.jsontoken.JsonTokenTestBase.java

/**
 * Convert encoded tokens into a more human-readable form without verifying.
 * Useful for logging.//  w  w w .  j a va 2 s .c  o  m
 */
protected static String decodeTokenForHumans(String encodedToken) {
    String[] pieces = encodedToken.split(Pattern.quote("."));
    if (pieces.length != 3) {
        return "invalid token (3 segments expected): " + encodedToken;
    }
    for (int i = 0; i < 3; i++) {
        pieces[i] = new String(Base64.decodeBase64(pieces[i].getBytes()));
    }
    return pieces[0] + "." + pieces[1] + "." + pieces[2];
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.ZipLineStream.java

@Override
public void setProperties(Collection<Map.Entry<String, String>> props) throws Exception {
    if (props == null) {
        return;/*from  www  .  j a  va  2  s  .co  m*/
    }

    super.setProperties(props);

    for (Map.Entry<String, String> prop : props) {
        String name = prop.getKey();
        String value = prop.getValue();
        if (StreamProperties.PROP_FILENAME.equalsIgnoreCase(name)) {
            zipFileName = value;

            if (StringUtils.isNotEmpty(zipFileName)) {
                String zdp[] = zipFileName.split(Pattern.quote(ZIP_PATH_SEPARATOR));

                if (zdp != null) {
                    if (zdp.length > 0) {
                        zipPath = zdp[0];
                    }
                    if (zdp.length > 1) {
                        zipEntriesMask = StringUtils.isEmpty(zdp[1]) ? null
                                : Utils.wildcardToRegex2(zdp[1].replace("\\", "/")); // NON-NLS
                        if (zipEntriesMask != null) {
                            zipEntriesMask = '^' + zipEntriesMask + '$'; // NON-NLS
                        }
                    }
                }
            }
        } else if (StreamProperties.PROP_ARCH_TYPE.equalsIgnoreCase(name)) {
            archType = value;
        }
    }
}

From source file:com.mediaworx.intellij.opencmsplugin.opencms.OpenCmsModule.java

/**
 * Initializes the module with the given configuration data (from the module's configuration dialog)
 * @param moduleConfig the module's configuration data
 *///from ww w . j a v  a  2 s  .c o  m
public void init(OpenCmsModuleConfigurationData moduleConfig) {
    this.moduleConfig = moduleConfig;

    if (moduleConfig.isUseProjectDefaultModuleNameEnabled()) {
        String moduleNamingScheme = pluginConfig.getModuleNamingScheme();
        String moduleFolderName = StringUtils.substringAfterLast(this.moduleBasePath, "/");
        if (moduleNamingScheme != null && moduleNamingScheme.length() > 0) {
            moduleName = moduleNamingScheme.replaceAll(Pattern.quote("${modulename}"), moduleFolderName);
        } else {
            moduleName = moduleFolderName;
        }
    } else {
        moduleName = moduleConfig.getModuleName();
    }

    exportPoints = openCmsConfig.getExportPointsForModule(moduleName);
    moduleResources = openCmsConfig.getModuleResourcesForModule(moduleName);

    String relativeVfsRoot;

    if (moduleConfig.isUseProjectDefaultVfsRootEnabled()) {
        relativeVfsRoot = pluginConfig.getDefaultLocalVfsRoot();
    } else {
        relativeVfsRoot = moduleConfig.getLocalVfsRoot();
    }
    localVfsRoot = this.moduleBasePath + "/" + relativeVfsRoot;
}

From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.JSONTypesExtractorImpl.java

/**
 * Given either a {@link JSONArray} or a {@link JSONObject}, a key ending and a prefix to add, 
 * it looks for keys at any object inside the provided JSON ending with the key ending and adds 
 * the given prefix to that ending.//from  w  w w.java2  s.  c  o  m
 * This method calls itself recursively to traverse inner parts of {@link JSONObject}s.
 * @param jsonRoot The root {@link JSONObject} or {@link JSONArray}. If an object of any other type is provided, 
 *                the method just does nothing.
 * @param oldKeyEnding the ending to look for.
 * @param prefixToAdd the prefix to add to that ending.
 */
private void addPrefixToJSONKeysEndingsRecursive(Object jsonRoot, String oldKeyEnding, String prefixToAdd) {
    if (jsonRoot instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) jsonRoot;
        SortedSet<String> keys = ImmutableSortedSet.<String>naturalOrder().addAll(jsonObject.keySet()).build();
        for (String key : keys) {
            Object value = jsonObject.get(key);
            addPrefixToJSONKeysEndingsRecursive(value, oldKeyEnding, prefixToAdd);
            if (key.endsWith(oldKeyEnding)) {
                String newKey = key.replaceAll(Pattern.quote(oldKeyEnding) + "$", prefixToAdd + oldKeyEnding);
                jsonObject.remove(key);
                jsonObject.put(newKey, value);
            }
        }
    } else if (jsonRoot instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) jsonRoot;
        for (int i = 0; i < jsonArray.length(); i++) {
            Object value = jsonArray.get(i);
            addPrefixToJSONKeysEndingsRecursive(value, oldKeyEnding, prefixToAdd);
        }
    } else {
        return;
    }
}