Example usage for java.util.regex Pattern pattern

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

Introduction

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

Prototype

pattern

Source Link

Usage

From source file:ch.cyberduck.ui.cocoa.controller.PreferencesController.java

public void uploadSkipRegexFieldDidChange(NSNotification sender) {
    String value = this.uploadSkipRegexField.string().trim();
    if (StringUtils.EMPTY.equals(value)) {
        preferences.setProperty("queue.upload.skip.enable", false);
        preferences.setProperty("queue.upload.skip.regex", value);
        this.uploadSkipButton.setState(NSCell.NSOffState);
    }/*from ww  w. ja  v  a  2 s. com*/
    try {
        Pattern compiled = Pattern.compile(value);
        preferences.setProperty("queue.upload.skip.regex", compiled.pattern());
        this.mark(this.uploadSkipRegexField.textStorage(), null);
    } catch (PatternSyntaxException e) {
        this.mark(this.uploadSkipRegexField.textStorage(), e);
    }
}

From source file:ch.cyberduck.ui.cocoa.controller.PreferencesController.java

public void downloadSkipRegexFieldDidChange(NSNotification sender) {
    String value = this.downloadSkipRegexField.string().trim();
    if (StringUtils.EMPTY.equals(value)) {
        preferences.setProperty("queue.download.skip.enable", false);
        preferences.setProperty("queue.download.skip.regex", value);
        this.downloadSkipButton.setState(NSCell.NSOffState);
    }/*from w w w  .j  a v a2  s .co  m*/
    try {
        Pattern compiled = Pattern.compile(value);
        preferences.setProperty("queue.download.skip.regex", compiled.pattern());
        this.mark(this.downloadSkipRegexField.textStorage(), null);
    } catch (PatternSyntaxException e) {
        this.mark(this.downloadSkipRegexField.textStorage(), e);
    }
}

From source file:org.finra.herd.service.helper.Hive13DdlGenerator.java

/**
 * Gets a list of Hive partitions. For single level partitioning, no auto-discovery of sub-partitions (sub-directories) is needed - the business object data
 * will be represented by a single Hive partition instance. For multiple level partitioning, this method performs an auto-discovery of all sub-partitions
 * (sub-directories) and creates a Hive partition object instance for each partition.
 *
 * @param businessObjectDataKey the business object data key
 * @param autoDiscoverableSubPartitionColumns the auto-discoverable sub-partition columns
 * @param s3KeyPrefix the S3 key prefix// w  w  w .  j  a  va  2s  . co m
 * @param storageFiles the storage files
 * @param storageName the storage name
 *
 * @return the list of Hive partitions
 */
public List<HivePartitionDto> getHivePartitions(BusinessObjectDataKey businessObjectDataKey,
        List<SchemaColumn> autoDiscoverableSubPartitionColumns, String s3KeyPrefix,
        Collection<String> storageFiles, String storageName) {
    // We are using linked hash map to preserve the order of the discovered partitions.
    LinkedHashMap<List<String>, HivePartitionDto> linkedHashMap = new LinkedHashMap<>();

    Pattern pattern = getHivePathPattern(autoDiscoverableSubPartitionColumns);
    for (String storageFile : storageFiles) {
        // Remove S3 key prefix from the file path. Please note that the storage files are already validated to start with S3 key prefix.
        String relativeFilePath = storageFile.substring(s3KeyPrefix.length());

        // Try to match the relative file path to the expected subpartition folders.
        Matcher matcher = pattern.matcher(relativeFilePath);
        Assert.isTrue(matcher.matches(), String.format(
                "Registered storage file or directory does not match the expected Hive sub-directory pattern. "
                        + "Storage: {%s}, file/directory: {%s}, business object data: {%s}, S3 key prefix: {%s}, pattern: {%s}",
                storageName, storageFile,
                businessObjectDataHelper.businessObjectDataKeyToString(businessObjectDataKey), s3KeyPrefix,
                pattern.pattern()));

        // Create a list of partition values.
        List<String> partitionValues = new ArrayList<>();

        // Add partition values per business object data key.
        partitionValues.add(businessObjectDataKey.getPartitionValue());
        partitionValues.addAll(businessObjectDataKey.getSubPartitionValues());

        // Extract relative partition values.
        for (int i = 1; i <= matcher.groupCount(); i++) {
            partitionValues.add(matcher.group(i));
        }

        // If we did not match all expected partition values, then this storage file path is not part
        // of a fully qualified partition (this is an intermediate folder marker) and we ignore it.
        if (!partitionValues.contains(null)) {
            // Get path for this partition by removing trailing "/" plus an optional file name from the relative file path,
            // or the trailing "_$folder$", which represents an empty partition in S3.
            String partitionPath = relativeFilePath.endsWith(S3_EMPTY_PARTITION)
                    ? relativeFilePath.substring(0, relativeFilePath.length() - S3_EMPTY_PARTITION.length())
                    : relativeFilePath.replaceAll("\\/[^/]*$", "");

            // Check if we already have that partition discovered - that would happen if partition contains multiple data files.
            HivePartitionDto hivePartition = linkedHashMap.get(partitionValues);

            if (hivePartition != null) {
                // Partition is already discovered, so just validate that the relative paths match.
                Assert.isTrue(hivePartition.getPath().equals(partitionPath), String.format(
                        "Found two different locations for the same Hive partition. Storage: {%s}, business object data: {%s}, "
                                + "S3 key prefix: {%s}, path[1]: {%s}, path[2]: {%s}",
                        storageName,
                        businessObjectDataHelper.businessObjectDataKeyToString(businessObjectDataKey),
                        s3KeyPrefix, hivePartition.getPath(), partitionPath));
            } else {
                // Add this partition to the hash map of discovered partitions.
                linkedHashMap.put(partitionValues, new HivePartitionDto(partitionPath, partitionValues));
            }
        }
    }

    List<HivePartitionDto> hivePartitions = new ArrayList<>();
    hivePartitions.addAll(linkedHashMap.values());

    return hivePartitions;
}

From source file:de.ub0r.android.websms.WebSMS.java

/**
 * Send text after the real connector is chosen.
 *
 * @param connector    which connector should be used.
 * @param subconnector which subconnector should be used
 * @param tos          recipients//from w  ww . j ava2  s  .  com
 * @param text         message text
 * @return true if message was sent
 */
private boolean sendReal(final ConnectorSpec connector, final SubConnectorSpec subconnector, final String[] tos,
        final String text) {

    Log.d(TAG, "sendReal(" + connector + "," + subconnector + ")");
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);

    if (!p.getBoolean(PREFS_TRY_SEND_INVALID, false)
            && connector.hasCapabilities(ConnectorSpec.CAPABILITIES_CHARACTER_CHECK)) {
        final String valid = connector.getValidCharacters();
        if (valid == null) {
            Log.i(TAG, "valid: null");
            Toast.makeText(this, R.string.log_error_char_nonvalid, Toast.LENGTH_LONG).show();
            return false;
        }
        final Pattern checkPattern = Pattern.compile("[^" + Pattern.quote(valid) + "]+");
        Log.d(TAG, "pattern: " + checkPattern.pattern());
        final Matcher m = checkPattern.matcher(text);
        if (m.find()) {
            final String illigal = m.group();
            Log.i(TAG, "invalid character: " + illigal);
            Toast.makeText(this, this.getString(R.string.log_error_char_notsendable) + ": " + illigal,
                    Toast.LENGTH_LONG).show();
            return false;
        }
    }

    ToggleButton v = (ToggleButton) this.findViewById(R.id.flashsms);
    final boolean flashSMS = (v.getVisibility() == View.VISIBLE) && v.isEnabled() && v.isChecked();
    final String defPrefix = p.getString(PREFS_DEFPREFIX, "+49");
    final String defSender = p.getString(PREFS_SENDER, "");

    final ConnectorCommand command = ConnectorCommand.send(nextMsgId(this), subconnector.getID(), defPrefix,
            defSender, tos, text, flashSMS);
    command.setCustomSender(lastCustomSender);
    command.setSendLater(lastSendLater);

    boolean sent = false;
    try {
        if (subconnector.hasFeatures(SubConnectorSpec.FEATURE_MULTIRECIPIENTS) || tos.length == 1) {
            Log.d(TAG, "text: " + text);
            Log.d(TAG, "to: ", tos);
            runCommand(this, connector, command);
        } else {
            ConnectorCommand cc;
            for (String t : tos) {
                if (t.trim().length() < 1) {
                    continue;
                }
                cc = (ConnectorCommand) command.clone();
                cc.setRecipients(t);
                Log.d(TAG, "text: " + text);
                Log.d(TAG, "to: ", tos);
                runCommand(this, connector, cc);
            }
        }
        sent = true;
    } catch (Exception e) {
        Log.e(TAG, "error running command", e);
        Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();
    }
    if (sent) {
        this.reset(false);
        try {
            Thread.sleep(SLEEP_BEFORE_EXIT);
        } catch (InterruptedException e) {
            Log.e(TAG, null, e);
        }
        this.finish();
        return true;
    }
    return false;
}

From source file:com.buaa.cfs.conf.Configuration.java

/**
 * Set the given property to <code>Pattern</code>. If the pattern is passed as null, sets the empty pattern which
 * results in further calls to getPattern(...) returning the default value.
 *
 * @param name    property name/* w ww .j  a v  a  2 s  .c  o  m*/
 * @param pattern new value
 */
public void setPattern(String name, Pattern pattern) {
    assert pattern != null : "Pattern cannot be null";
    set(name, pattern.pattern());
}

From source file:com.thoughtworks.cruise.utils.configfile.CruiseConfigDom.java

/** Looks for variables of type: ${http_repo*} in REPO_URL property and replaces it. Example:
  *    <repositories>/*from   w w w . j  av  a  2 s  . c  om*/
  *        <repository id="repo-id" name="tw-repo">
  *          <pluginConfiguration id="yum" version="1"/>
  *          <configuration>
  *            <property>
  *              <key>REPO_URL</key>
  *              <value>http://192.168.0.101:8081/${http_repo1}</value>
  *            </property>
  *
  *     TO
  *
  *    <repositories>
  *        <repository id="repo-id" name="tw-repo">
  *          <pluginConfiguration id="yum" version="1"/>
  *          <configuration>
  *            <property>
  *              <key>REPO_URL</key>
  *              <value>http://192.168.0.101:8081/pkgrepo-RANDOM1234</value>
  *            </property>
  *
  *      AND return a map which contains: {"http_repo1" => "pkgrepo-RANDOM1234"}
 */
public Map<String, String> replacePackageRepositoryURIForHttpBasedRepos(Map<String, String> currentRepoNames) {
    Pattern httpRepoNameVariablePattern = Pattern.compile("\\$\\{(http_repo[^\\}]*)\\}");
    Map<String, String> httpRepoNameInConfigToItsNameAtRuntime = new HashMap<String, String>(currentRepoNames);

    List<Element> allRepoUrlPropertyKeys = root()
            .selectNodes("/cruise//repositories/repository/configuration/property/key[text()='REPO_URL']");
    for (Element repoUrlKeyElement : allRepoUrlPropertyKeys) {
        Node repoUrlPropertyInConfig = repoUrlKeyElement.getParent().selectSingleNode("value");
        String existingValueOfRepoUrl = repoUrlPropertyInConfig.getText();

        Matcher matcherForVariable = httpRepoNameVariablePattern.matcher(existingValueOfRepoUrl);
        if (matcherForVariable.find()) {
            String variableName = matcherForVariable.group(1);

            String replacementRepoName = httpRepoNameInConfigToItsNameAtRuntime.get(variableName);
            if (!httpRepoNameInConfigToItsNameAtRuntime.containsKey(variableName)) {
                replacementRepoName = "pkgrepo-" + RandomStringUtils.randomAlphanumeric(10);
                httpRepoNameInConfigToItsNameAtRuntime.put(variableName, replacementRepoName);
            }

            String replacementRepoURL = existingValueOfRepoUrl
                    .replaceFirst(httpRepoNameVariablePattern.pattern(), replacementRepoName);
            repoUrlPropertyInConfig.setText(replacementRepoURL);
        }
    }

    return httpRepoNameInConfigToItsNameAtRuntime;
}

From source file:org.alfresco.filesys.repo.ContentDiskDriver.java

/**
 * Rename the specified file./*w w w.  j  a  v a2 s .  c om*/
 * 
 * @param sess Server session
 * @param tree Tree connection
 * @param oldName java.lang.String
 * @param newName java.lang.String
 * @exception java.io.IOException The exception description.
 */
public void renameFile(final SrvSession sess, final TreeConnection tree, final String oldName,
        final String newName) throws IOException {
    // Create the transaction (initially read-only)

    beginReadTransaction(sess);

    // Get the device context

    final ContentContext ctx = (ContentContext) tree.getContext();

    // DEBUG

    if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
        logger.debug("Rename oldName=" + oldName + ", newName=" + newName);

    try {
        // Get the file/folder to move

        final NodeRef nodeToMoveRef = getNodeForPath(tree, oldName);

        // Check if the node is a link node

        if (nodeToMoveRef != null
                && nodeService.getProperty(nodeToMoveRef, ContentModel.PROP_LINK_DESTINATION) != null)
            throw new AccessDeniedException("Cannot rename link nodes");

        // Get the new target folder - it must be a folder

        String[] splitPaths = FileName.splitPath(newName);
        String[] oldPaths = FileName.splitPath(oldName);

        final NodeRef targetFolderRef = getNodeForPath(tree, splitPaths[0]);
        final NodeRef sourceFolderRef = getNodeForPath(tree, oldPaths[0]);
        final String name = splitPaths[1];

        // Check if this is a rename within the same folder

        final boolean sameFolder = splitPaths[0].equalsIgnoreCase(oldPaths[0]);

        // Get the file state for the old file, if available

        final FileState oldState = ctx.getStateCache().findFileState(oldName, true);

        // Check if we are renaming a folder, or the rename is to a different folder

        boolean isFolder = cifsHelper.isDirectory(nodeToMoveRef);

        if (isFolder == true || sameFolder == false) {

            // Rename or move the file/folder

            doInWriteTransaction(sess, new CallableIO<Void>() {

                public Void call() throws IOException {
                    if (sameFolder == true)
                        cifsHelper.rename(nodeToMoveRef, name);
                    else
                        cifsHelper.move(nodeToMoveRef, sourceFolderRef, targetFolderRef, name);
                    return null;
                }
            });

            // Update the old file state

            if (oldState != null) {
                // Update the file state index to use the new name

                ctx.getStateCache().renameFileState(newName, oldState, isFolder);
            }

            // DEBUG

            if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                logger.debug("  Renamed " + (isFolder ? "folder" : "file") + " using "
                        + (sameFolder ? "rename" : "move"));
        } else {

            // Rename a file within the same folder
            //
            // Check if the target file already exists

            final int newExists = fileExists(sess, tree, newName);
            final FileState newState = ctx.getStateCache().findFileState(newName, true);

            List<Runnable> postTxn = doInWriteTransaction(sess, new CallableIO<List<Runnable>>() {

                public List<Runnable> call() throws IOException {
                    List<Runnable> postTxn = new LinkedList<Runnable>();

                    NodeRef targetNodeRef = null;

                    boolean isFromVersionable = nodeService.hasAspect(nodeToMoveRef,
                            ContentModel.ASPECT_VERSIONABLE);
                    boolean typesCompatible = true;

                    // HACK ALF-3856: Version History lost when Versionable Content renamed via CIFS
                    //                This code will move into the repo layer (or just above it)
                    //                and this complexity removed from here.
                    //          Attempt to detect normal renames.  Hack alert!
                    Pattern renameShufflePattern = ctx.getRenameShufflePattern();
                    boolean renameShuffle = isRenameShuffle(oldName, newName, renameShufflePattern);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Rename file: \n" + "   Old name:      " + oldName + "\n"
                                + "   New name:      " + newName + "\n" + "   Pattern:       "
                                + renameShufflePattern.pattern() + "\n" + "   Is shuffle:    " + renameShuffle
                                + "\n" + "   Source folder: " + sourceFolderRef + "\n" + "   Target folder: "
                                + targetFolderRef + "\n" + "   Node:          " + nodeToMoveRef + "\n"
                                + "   Aspects:       " + nodeService.getAspects(nodeToMoveRef));

                    }

                    if (newExists == FileStatus.FileExists) {

                        // Use the existing file as the target node

                        targetNodeRef = getNodeForPath(tree, newName);
                    } else if (renameShuffle) {
                        logger.debug("is rename shuffle");
                        // Check if the target has a renamed or delete-on-close state

                        if (newState.getFileStatus() == FileRenamed) {
                            logger.debug("file status == FileRenamed");

                            // DEBUG

                            if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                                logger.debug("  Using renamed node, " + newState);

                            NodeRef newStateNode = (NodeRef) newState.getFilesystemObject();
                            QName oldType = nodeService.getType(nodeToMoveRef);
                            QName newType = nodeService.getType(newStateNode);
                            if (oldType.equals(newType)) {

                                // Use the renamed node to clone aspects/state if it is of the correct type

                                cloneNode(name, newStateNode, nodeToMoveRef, ctx);
                            } else {
                                logger.debug("not renamed, must create new node");
                                // Otherwise we must create a node of the correct type
                                targetNodeRef = cifsHelper.createNode(ctx.getRootNode(), newName, newType);

                                // Force a copy to this target
                                typesCompatible = false;

                                // DEBUG

                                if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                                    logger.debug("  Created new node for " + newName + " type " + newType
                                            + ", isFromVersionable=false");

                                // Copy aspects from the original state

                                cloneNode(name, newStateNode, targetNodeRef, ctx);
                            }

                            //Change state for tmp node to allow delete it without special permission
                            String newStateNodeName = (String) nodeService.getProperty(newStateNode,
                                    ContentModel.PROP_NAME);
                            FileState stateForTmp = ctx.getStateCache().findFileState(
                                    newName.substring(0, newName.lastIndexOf("\\")) + "\\" + newStateNodeName,
                                    true);
                            stateForTmp.addAttribute(CanDeleteWithoutPerms, true);
                            stateForTmp.setFileStatus(FileStatus.FileExists);
                            stateForTmp.setExpiryTime(System.currentTimeMillis() + FileState.DeleteTimeout);
                            if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                                logger.debug("  Set CanDeleteWithoutPerms=true for " + stateForTmp);

                        } else if (newState.getFileStatus() == DeleteOnClose) {
                            logger.debug("file state is delete on close");

                            // DEBUG

                            if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                                logger.debug("  Restoring delete-on-close node, " + newState);

                            // Restore the deleted node so we can relink the new version to the old history/properties

                            NodeRef archivedNode = getNodeArchiveService()
                                    .getArchivedNode((NodeRef) newState.getFilesystemObject());

                            // DEBUG

                            if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                                logger.debug("  Found archived node " + archivedNode);

                            if (archivedNode != null && getNodeService().exists(archivedNode)) {
                                // Restore the node

                                targetNodeRef = getNodeService().restoreNode(archivedNode, null, null, null);

                                // DEBUG

                                if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                                    logger.debug("  Restored node " + targetNodeRef + ", version=" + nodeService
                                            .getProperty(targetNodeRef, ContentModel.PROP_VERSION_LABEL));

                                // Check if the deleted file had a linked node, due to a rename

                                NodeRef linkNode = (NodeRef) newState.findAttribute(AttrLinkNode);

                                if (linkNode != null && nodeService.exists(linkNode)) {

                                    // Clone aspects from the linked node onto the restored node

                                    cloneNode(name, linkNode, targetNodeRef, ctx);

                                    // DEBUG

                                    if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME)) {
                                        logger.debug("  Moved aspects from linked node " + linkNode);

                                        // Check if the node is a working copy

                                        NodeRef mainNodeRef = checkOutCheckInService
                                                .getCheckedOut(targetNodeRef);
                                        if (mainNodeRef != null) {
                                            // Check if the main document is still locked
                                            LockType lockTyp = lockService.getLockType(mainNodeRef);
                                            logger.debug("  Main node ref lock type = " + lockTyp);
                                        }
                                    }
                                }
                            }
                        }

                        // Check if the node being renamed is versionable

                        else if (isFromVersionable == true) {
                            logger.debug("from node is versionable");

                            // Create a new node for the target

                            targetNodeRef = cifsHelper.createNode(ctx.getRootNode(), newName,
                                    nodeService.getType(nodeToMoveRef));

                            // DEBUG

                            if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                                logger.debug("  Created new node for " + newName + ", isFromVersionable=true");

                            // Copy aspects from the original file

                            cloneNode(name, nodeToMoveRef, targetNodeRef, ctx);

                            //Change state for tmp node to allow delete it without special permission
                            FileState stateForTmp = ctx.getStateCache().findFileState(newName, true);
                            stateForTmp.addAttribute(CanDeleteWithoutPerms, true);
                            stateForTmp.setFileStatus(FileStatus.FileExists);
                            stateForTmp.setExpiryTime(System.currentTimeMillis() + FileState.DeleteTimeout);
                            if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                                logger.debug("  Set CanDeleteWithoutPerms=true for " + stateForTmp);
                        }
                    }

                    // If the original or target nodes are not versionable and types are compatible then just use a standard rename of the node
                    if (!renameShuffle
                            || (!isFromVersionable && typesCompatible && (targetNodeRef == null || nodeService
                                    .hasAspect(targetNodeRef, ContentModel.ASPECT_VERSIONABLE) == false))) {
                        logger.debug("do simple rename");

                        // Rename the file/folder

                        cifsHelper.rename(nodeToMoveRef, name);

                        postTxn.add(new Runnable() {
                            public void run() {
                                // Mark the new file as existing

                                newState.setFileStatus(FileExists);
                                newState.setFilesystemObject(nodeToMoveRef);
                                newState.setFileSize(oldState.getFileSize());

                                // the date is updated to be properly saved when the document is closed, see MNT-214
                                newState.updateModifyDateTime(oldState.getModifyDateTime());

                                // Make sure the old file state is cached for a short while, the file may not be open so the
                                // file state could be expired

                                oldState.setExpiryTime(System.currentTimeMillis() + FileState.DeleteTimeout);

                                // Indicate that this is a renamed file state, set the node ref of the file that was renamed

                                oldState.setFileStatus(FileRenamed);
                                oldState.setFilesystemObject(nodeToMoveRef);
                            }
                        });

                        // DEBUG

                        if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                            logger.debug("  Use standard rename for " + name + "(versionable="
                                    + isFromVersionable + ", targetNodeRef=" + targetNodeRef + ")");
                    } else {

                        // Make sure we have a valid target node

                        if (targetNodeRef == null) {

                            // DEBUG

                            if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                                logger.debug("  No target node for rename");

                            // Throw an error

                            throw new AccessDeniedException("No target node for file rename");
                        }

                        // Copy content data from the old file to the new file

                        copyContentData(sess, tree, nodeToMoveRef, targetNodeRef, newName);

                        final NodeRef finalTargetNodeRef = targetNodeRef;
                        postTxn.add(new Runnable() {

                            public void run() {
                                // Mark the new file as existing

                                newState.setFileStatus(FileExists);
                                newState.setFilesystemObject(finalTargetNodeRef);
                                newState.setFileSize(oldState.getFileSize());

                                // the date is updated to be properly saved when the document is closed, see MNT-214
                                newState.updateModifyDateTime(oldState.getModifyDateTime());

                                // Make sure the old file state is cached for a short while, the file may not be open so the
                                // file state could be expired

                                oldState.setExpiryTime(System.currentTimeMillis() + FileState.DeleteTimeout);

                                // Indicate that this is a deleted file state, set the node ref of the file that was renamed

                                oldState.setFileStatus(DeleteOnClose);
                                oldState.setFilesystemObject(nodeToMoveRef);

                                // Link to the new node, a new file may be renamed into place, we need to transfer aspect/locks

                                oldState.addAttribute(AttrLinkNode, finalTargetNodeRef);

                                // DEBUG

                                if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
                                    logger.debug("  Cached delete state for " + oldName);
                            }
                        });

                        logger.debug("delete the old file");

                        // Delete the old file
                        if (renameShuffle && isFromVersionable && permissionService.hasPermission(nodeToMoveRef,
                                PermissionService.EDITOR) == AccessStatus.ALLOWED) {
                            AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() {
                                @Override
                                public Object doWork() throws Exception {
                                    if (logger.isDebugEnabled()) {
                                        logger.debug(
                                                "Rename shuffle for versioning content is assumed. Deleting "
                                                        + nodeToMoveRef + " as system user");
                                    }
                                    if (renameCSVShufflePattern.matcher(newName.toLowerCase()).matches()) {
                                        Map<QName, Serializable> props = Collections.emptyMap();
                                        nodeService.addAspect(nodeToMoveRef, ContentModel.ASPECT_SOFT_DELETE,
                                                props);
                                    } else {
                                        nodeService.deleteNode(nodeToMoveRef);
                                    }
                                    return null;
                                }

                            }, AuthenticationUtil.getSystemUserName());
                        } else {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Deleting " + nodeToMoveRef + " as user: "
                                        + AuthenticationUtil.getFullyAuthenticatedUser());
                            }
                            nodeService.deleteNode(nodeToMoveRef);
                        }

                    }

                    return postTxn;
                }
            });

            logger.debug("running post txns");
            // Run the required state-changing logic once the retrying transaction has completed successfully
            for (Runnable runnable : postTxn) {
                runnable.run();
            }
        }
    } catch (org.alfresco.repo.security.permissions.AccessDeniedException ex) {
        // Debug

        if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
            logger.debug("Rename file - access denied, " + oldName);

        // Convert to a filesystem access denied status

        throw new AccessDeniedException("Rename file " + oldName);
    } catch (NodeLockedException ex) {
        // Debug

        if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
            logger.debug("Rename file", ex);

        // Convert to an filesystem access denied exception

        throw new AccessDeniedException("Node locked " + oldName);
    } catch (InvalidNodeRefException ex) {
        // Debug

        if (logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_RENAME))
            logger.debug("Rename file - file doesn't exist, " + oldName, ex);

        // Convert to a filesystem access denied status

        throw new FileNotFoundException("File doesn't exist " + oldName);
    } catch (RuntimeException ex) {
        // Unexpected Exception being consumed here - hence the error logging.
        logger.error("Unable to rename file" + oldName, ex);

        // Convert to a general I/O exception

        throw new AccessDeniedException("Rename file " + oldName);
    }
}

From source file:net.bashtech.geobot.ReceiverBot.java

private boolean containsLink(String message, Channel ch) {
    String[] splitMessage = message.toLowerCase().split(" ");
    for (String m : splitMessage) {
        for (Pattern pattern : linkPatterns) {

            Matcher match = pattern.matcher(m);
            if (match.matches()) {
                log("RB: Link match on " + pattern.pattern());
                if (ch.checkPermittedDomain(m))
                    return false;
                else
                    return true;
            }/*from   w ww  . j  a  v  a 2s  .co m*/
        }
    }

    return false;
}

From source file:org.apache.sling.osgi.obr.OSGiBundleRepositoryServlet.java

private void listBundles(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String category = this.getParameter(req, "category", Repository.CATEGORY_ALL_BUNDLES);

    String regexp = this.getParameter(req, "regexp", "");
    Pattern pattern = null;
    if (regexp.length() > 0) {
        try {/*  ww w . j a v  a  2 s  .  co  m*/
            String regexpInt = regexp;

            // turn regexp into substring match if not bounded by ^/$
            if (!regexpInt.startsWith("^") && !regexpInt.startsWith(".*"))
                regexpInt = ".*" + regexpInt;
            if (!regexpInt.endsWith("$") && !regexpInt.endsWith(".*"))
                regexpInt = regexpInt + ".*";

            pattern = Pattern.compile(regexpInt);
        } catch (PatternSyntaxException pse) {
            // don't care, but clear the variable
            regexp = "";
        }
    }

    // set cookies
    this.setCookie(resp, "category", category);
    this.setCookie(resp, "regexp", regexp);

    PrintWriter pw = this.head(resp);

    pw.print("<h1>Welcome to the OSGi Bundle Repository ");
    pw.print(this.repository.getName());
    pw.println("</h1>");

    pw.print("<p>This repository was last updated: ");
    pw.println(new Date(this.repository.getLastModified()));

    pw.println("<hr />");
    pw.println("<h2>Tasks</h2>");

    pw.println("<table border='0' width='100%'>");

    pw.print("<tr><td nowrap>Repository Descriptor</td>");
    pw.print("<td width='99%'><a href='");
    pw.print(this.getRelativeURI(req, "repository.xml"));
    pw.print("'>");
    pw.print("repository.xml");
    pw.println("</a></td></tr>");

    pw.print("<tr><td nowrap>Repository Download (complete)</td>");
    pw.print("<td width='99%'><a href='");
    pw.print(this.getRelativeURI(req, "repository.zip"));
    pw.print("'>");
    pw.print("repository.zip");
    pw.println("</a></td><tr>");

    pw.print("<tr><td nowrap>Bundle Upload</td>");
    pw.print("<td width='99%'><form method='POST' enctype='multipart/form-data'>");
    pw.print("<input type='file' name='bundlefile'>");
    pw.print("<input type='submit' value='Upload Bundle'>");
    pw.print("</form>");
    pw.println("</td></tr>");

    pw.println("</table>");

    pw.println("<hr />");

    pw.println("<form name='selection'>");
    pw.println("<table width='100%' border='0' cellspacing='0' cellpadding='0'>");
    pw.println("<tr><td><h2>Available Resources</h2></td>");
    pw.println("<td align='right'>");
    pw.println("By Name (Reg Exp): <input type='text' name='regexp' value='" + regexp + "'>");
    pw.println("&nbsp;&nbsp;|&nbsp;&nbsp;");
    pw.println("By Category: <select name='category' onChange='form.submit();'>");
    Iterator categories = this.repository.getBundleCategories(null).iterator();
    while (categories.hasNext()) {
        Object cat = categories.next();
        String selected = category.equals(cat) ? "selected" : "";
        pw.print("<option value='" + cat + "' " + selected + ">");
        pw.print(cat);
        pw.println("</option>");
    }
    pw.println("</select>");
    pw.println("&nbsp;&nbsp;|&nbsp;&nbsp;");
    pw.println("<input type='submit' value='Show'/>");
    pw.println("&nbsp;&nbsp;|&nbsp;&nbsp;");
    pw.println(
            "<input type='button' value='Download Selected' onClick='document.forms[\"selectiveDump\"].submit();'");
    pw.println("</td></tr>");
    pw.println("</table>");
    pw.println("</form>");

    pw.print("<form name='selectiveDump' method='post' action='" + this.getRelativeURI(req, "repository.zip")
            + "'>");

    pw.println("<center>");
    pw.println("<table width='80%' border='1' cellspacing='0' cellpadding='3'>");

    boolean haveBundles = false;
    Iterator bi = this.repository.getResourcesByCategory(category);
    while (bi.hasNext()) {
        Resource res = (Resource) bi.next();

        // ignore the resource if the name does not match the regexp
        if (pattern != null && !pattern.matcher(res.getSymbolicName()).matches()) {
            continue;
        }

        String uri = this.getRelativeURI(req, res.getResourceName());
        this.dumpRow(pw,
                "<input name='bundle' type='checkbox' value='" + res.getResourceName() + "'></td><td><a href='"
                        + uri + "?info=info" + "'>" + res + "</a>",
                "<a href='" + uri + "?remove=remove" + "'>remove</a>");

        haveBundles = true;
    }

    // indicate no matching bundles
    if (!haveBundles) {
        StringBuffer msg = new StringBuffer();
        msg.append("No Bundle found ");
        if (pattern != null) {
            msg.append("whose Symbolic Name matches regular expression '");
            msg.append(pattern.pattern());
            msg.append("' and ");
        }
        msg.append("which has Category " + category);
        this.dumpRow(pw, msg.toString(), null);
    }

    pw.println("</table>");
    pw.println("</center>");

    pw.println("</form>");

    this.foot(pw);
}