Example usage for java.util.regex Pattern matches

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

Introduction

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

Prototype

public static boolean matches(String regex, CharSequence input) 

Source Link

Document

Compiles the given regular expression and attempts to match the given input against it.

Usage

From source file:com.roncoo.pay.permission.controller.PmsOperatorController.java

/**
 * ????//from w  ww  .  ja v  a 2s .co  m
 * 
 * @param email
 * @return ??
 */
public static boolean emailFormat(String email) {
    // boolean tag = true;
    String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    boolean result = Pattern.matches(check, email);
    return result;
}

From source file:com.panet.imeta.core.fileinput.FileInputList.java

public static FileInputList createFileList(VariableSpace space, String[] fileName, String[] fileMask,
        String[] fileRequired, boolean[] includeSubdirs, FileTypeFilter[] fileTypeFilters) {
    FileInputList fileInputList = new FileInputList();

    // Replace possible environment variables...
    final String realfile[] = space.environmentSubstitute(fileName);
    final String realmask[] = space.environmentSubstitute(fileMask);

    for (int i = 0; i < realfile.length; i++) {
        final String onefile = realfile[i];
        final String onemask = realmask[i];

        final boolean onerequired = YES.equalsIgnoreCase(fileRequired[i]);
        final boolean subdirs = includeSubdirs[i];
        final FileTypeFilter filter = ((fileTypeFilters == null || fileTypeFilters[i] == null)
                ? FileTypeFilter.ONLY_FILES
                : fileTypeFilters[i]);//from   w  w  w .j a v a2s  . co  m

        if (Const.isEmpty(onefile))
            continue;

        // 
        // If a wildcard is set we search for files
        //
        if (!Const.isEmpty(onemask)) {
            try {
                // Find all file names that match the wildcard in this directory
                //
                FileObject directoryFileObject = KettleVFS.getFileObject(onefile);
                if (directoryFileObject != null && directoryFileObject.getType() == FileType.FOLDER) // it's a directory
                {
                    FileObject[] fileObjects = directoryFileObject.findFiles(new AllFileSelector() {
                        public boolean traverseDescendents(FileSelectInfo info) {
                            return info.getDepth() == 0 || subdirs;
                        }

                        public boolean includeFile(FileSelectInfo info) {
                            // Never return the parent directory of a file list.
                            if (info.getDepth() == 0) {
                                return false;
                            }

                            FileObject fileObject = info.getFile();
                            try {
                                if (fileObject != null && filter.isFileTypeAllowed(fileObject.getType())) {
                                    String name = fileObject.getName().getBaseName();
                                    boolean matches = Pattern.matches(onemask, name);
                                    /*
                                    if (matches)
                                    {
                                        System.out.println("File match: URI: "+info.getFile()+", name="+name+", depth="+info.getDepth());
                                    }
                                    */
                                    return matches;
                                }
                                return false;
                            } catch (FileSystemException ex) {
                                // Upon error don't process the file.
                                return false;
                            }
                        }
                    });
                    if (fileObjects != null) {
                        for (int j = 0; j < fileObjects.length; j++) {
                            if (fileObjects[j].exists())
                                fileInputList.addFile(fileObjects[j]);
                        }
                    }
                    if (Const.isEmpty(fileObjects)) {
                        if (onerequired)
                            fileInputList.addNonAccessibleFile(directoryFileObject);
                    }

                    // Sort the list: quicksort, only for regular files
                    fileInputList.sortFiles();
                } else {
                    FileObject[] children = directoryFileObject.getChildren();
                    for (int j = 0; j < children.length; j++) {
                        // See if the wildcard (regexp) matches...
                        String name = children[j].getName().getBaseName();
                        if (Pattern.matches(onemask, name))
                            fileInputList.addFile(children[j]);
                    }
                    // We don't sort here, keep the order of the files in the archive.
                }
            } catch (Exception e) {
                LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
            }
        } else
        // A normal file...
        {
            try {
                FileObject fileObject = KettleVFS.getFileObject(onefile);
                if (fileObject.exists()) {
                    if (fileObject.isReadable()) {
                        fileInputList.addFile(fileObject);
                    } else {
                        if (onerequired)
                            fileInputList.addNonAccessibleFile(fileObject);
                    }
                } else {
                    if (onerequired)
                        fileInputList.addNonExistantFile(fileObject);
                }
            } catch (Exception e) {
                LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
            }
        }
    }

    return fileInputList;
}

From source file:org.alfresco.po.share.site.document.ContentFormatPageTest.java

@Test(dependsOnMethods = "testBulletPointInsertionInRichTextFormatter", groups = "alfresco-one")
public void testNumberInsertionInRichTextFormatter() {
    if (logger.isTraceEnabled())
        logger.trace("====testNumberInsertionInRichTextFormatter====");
    textEditor.clickTextFormatter(FormatType.NUMBER);
    Assert.assertEquals(commentText, textEditor.getText());
    Assert.assertTrue(/*from   w  ww  .ja va2 s  .c om*/
            Pattern.matches(("<ol[ a-zA-Z=\"]*><li>" + commentText + "</li></ol>"), textEditor.getContent()));
    textEditor.clickTextFormatter(FormatType.NUMBER);
    Assert.assertTrue(textEditor.getContent().contains("<p>" + commentText + "</p>"));
}

From source file:com.xtructure.xutil.id.XId.java

/**
 * Creates a new {@link XId} with the given base string and the given
 * instanceNums//w  w  w  . j  a  v  a2  s. c om
 * 
 * @param base
 *            the base string with which to create the new {@link XId}
 * @param instanceNums
 *            the instance numbers of the new {@link XId}
 * @throws IllegalArgumentException
 *             if base does not match {@link #BASE_REGEX} or if instanceNums
 *             is null or contains any nulls
 */
protected XId(String base, List<Integer> instanceNums) throws IllegalArgumentException {
    if (base == null) {
        throw new IllegalArgumentException("base must not be null");
    }
    if (instanceNums == null) {
        throw new IllegalArgumentException("instanceNums must not be null");
    }
    if (!Pattern.matches(BASE_REGEX, base)) {
        throw new IllegalArgumentException(String.format("%s must match regex %s", base, BASE_REGEX));
    }
    for (Integer i : instanceNums) {
        if (i == null) {
            throw new IllegalArgumentException("instanceNums must not contain nulls");
        }
    }
    this.base = base;
    this.instanceNums = Collections.unmodifiableList(new ArrayList<Integer>(instanceNums));
}

From source file:com.seajas.search.contender.service.modifier.SourceElementModifierService.java

/**
 * Test a given result modifier chain./*from  w ww  .j  a  v  a  2 s  .co  m*/
 * 
 * @param modifierId
 * @param uri
 * @param encodingOverride
 * @param userAgent
 * @throws Exception
 * @return Map<String, Boolean>
 */
public Map<String, Boolean> testModifier(Integer modifierId, URI uri, String encodingOverride, String userAgent)
        throws Exception {
    WebResolverSettings settings = new WebResolverSettings();
    settings.setMaximumContentLength(maximumContentLength);
    settings.setUserAgent(userAgent);

    Map<String, Boolean> result = new HashMap<String, Boolean>();

    logger.info("Testing result modifier with ID " + modifierId + " and URI " + uri);

    Modifier modifier = modifierCache.getResultModifierById(modifierId);

    // Retrieve the content

    Content contentResult = getContent(uri, encodingOverride, null, userAgent);

    // Verify the expression in the same way the finalUrl is contrasted to the initial URL

    if (contentResult == null)
        throw new Exception("The given modifier content retrieval for testing purposes failed");

    if (contentResult.getUri() != null && !contentResult.getUri().equals(uri)) {
        if (logger.isInfoEnabled())
            logger.info("Modifier result has different final (post-redirect) URL from original: "
                    + contentResult.getUri());
    }

    if (!Pattern.matches(modifier.getUrlExpression(),
            (contentResult.getUri() != null ? contentResult.getUri() : uri).toString()))
        throw new Exception("The given testing result URL is not covered by the modifier expression");

    InputStream inputStream = contentResult.getInputStream();

    try {
        if (contentResult.getMediaType().startsWith("text/") || contentResult.getMediaType().contains("/xhtml")
                || contentResult.getMediaType().contains("/xml")) {
            Reader reader;

            if (encodingOverride != null)
                reader = new InputStreamReader(inputStream, encodingOverride);
            else
                reader = new XmlHtmlReader(inputStream, contentResult.getContentType(), true);

            try {
                for (ModifierFilter filter : modifier.getFilters()) {
                    StringBuffer current = new StringBuffer(), updated = new StringBuffer();

                    reader = readerToBuffer(current, reader, false);
                    reader = readerToBuffer(updated, modifierFilterProcessor.process(filter, reader), false);

                    result.put("Filter_" + filter.getId(), !current.toString().equals(updated.toString()));
                }

                for (ModifierScript script : modifier.getScripts()) {
                    StringBuffer current = new StringBuffer(), updated = new StringBuffer();

                    reader = readerToBuffer(current, reader, false);

                    reader = readerToBuffer(updated,
                            modifierScriptProcessor.process(script, extractAndClose(reader),
                                    contentResult.getUri() != null ? contentResult.getUri() : uri, settings,
                                    false),
                            false);

                    result.put("Script_" + script.getId(), !current.toString().equals(updated.toString()));
                }
            } catch (IOException e) {
                logger.error("Could not test the given result: " + e.getMessage(), e);
            } catch (ScriptException e) {
                logger.error("Could not test the given result: " + e.getMessage(), e);
            }

            reader.close();
        } else
            throw new Exception("The given test feed URL does not contain appropriate content for testing ("
                    + contentResult.getMediaType().toString() + ") - must be text or XML-based");
    } catch (IOException e) {
        logger.error("Could not test the given result: " + e.getMessage(), e);
    }

    return result;
}

From source file:mobile.service.RNSService.java

/**
 * //w w w  .  j  a  v a2 s  .  c  o  m
 *
 * @param requireId  Id
 * @param title      ?
 * @param industryId Id?
 * @param info       ??
 * @param budget     ?
 * @param skillsTags ?
 * @return
 */
public static ServiceResult updateRequire(Long requireId, String title, Long industryId, String info,
        String budget, List<String> skillsTags, List<Long> attachs) {
    if (null == requireId) {
        throw new IllegalArgumentException("requireId can not be null");
    }

    ObjectNode data = Json.newObject();
    data.put("id", requireId);

    if (null != title) {
        if (StringUtils.isBlank(title)) {
            return ServiceResult.error("100005", "?");
        } else {
            data.put("title", title);
        }
    }
    if (null != industryId) {
        SkillTag tag = SkillTag.getTagById(industryId);
        if (null == tag || tag.getTagType() != SkillTag.TagType.CATEGORY) {
            return ServiceResult.error("100005", "Id" + industryId);
        } else {
            data.put("industry", industryId);
        }
    }
    if (null != info) {
        data.put("info", info);
    }
    if (null != budget) {
        if (!Pattern.matches("^\\d{0,8}(\\.\\d)?$", budget) && !"-1".equals(budget)) {
            return ServiceResult.error("100005", "??8?1??");
        } else {
            data.put("budget", budget);
        }
    }
    if (null != skillsTags) {
        data.set("tags", Json.toJson(skillsTags));
    }
    if (null != attachs) {
        if (attachs.size() > 5) {
            return ServiceResult.error("1006", "??");
        }
        ArrayNode attachsNode = Json.newObject().arrayNode();
        for (Long attachId : attachs) {
            ObjectNode attachNode = Json.newObject();
            attachNode.put("attachId", attachId);
            attachsNode.add(attachNode);
        }
        data.set("attachs", attachsNode);
    }

    ServiceResult updateResult = createOrUpdateRequire(data, null);
    if (!updateResult.isSuccess()) {
        return updateResult;
    }

    return ServiceResult.success();
}

From source file:com.microsoft.azure.management.resources.ResourceOperationsImpl.java

/**
* Begin moving resources.To determine whether the operation has finished
* processing the request, call GetLongRunningOperationStatus.
*
* @param sourceResourceGroupName Required. Source resource group name.
* @param parameters Required. move resources' parameters.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations./*from   w ww  .ja  v  a 2 s  . c  om*/
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response for long running operations.
*/
@Override
public LongRunningOperationResponse beginMoving(String sourceResourceGroupName, ResourcesMoveInfo parameters)
        throws IOException, ServiceException {
    // Validate
    if (sourceResourceGroupName == null) {
        throw new NullPointerException("sourceResourceGroupName");
    }
    if (sourceResourceGroupName != null && sourceResourceGroupName.length() > 1000) {
        throw new IllegalArgumentException("sourceResourceGroupName");
    }
    if (Pattern.matches("^[-\\w\\._]+$", sourceResourceGroupName) == false) {
        throw new IllegalArgumentException("sourceResourceGroupName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("sourceResourceGroupName", sourceResourceGroupName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginMovingAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(sourceResourceGroupName, "UTF-8");
    url = url + "/moveResources";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-04-01-preview");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED && statusCode != HttpStatus.SC_NO_CONTENT) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        LongRunningOperationResponse result = null;
        // Deserialize Response
        result = new LongRunningOperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("Location").length > 0) {
            result.setOperationStatusLink(httpResponse.getFirstHeader("Location").getValue());
        }
        if (httpResponse.getHeaders("Retry-After").length > 0) {
            result.setRetryAfter(
                    DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
        }
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }
        if (statusCode == HttpStatus.SC_CONFLICT) {
            result.setStatus(OperationStatus.Failed);
        }
        if (statusCode == HttpStatus.SC_ACCEPTED) {
            result.setStatus(OperationStatus.InProgress);
        }
        if (statusCode == HttpStatus.SC_NO_CONTENT) {
            result.setStatus(OperationStatus.Succeeded);
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:org.motechproject.mobile.omi.manager.MessageStoreManagerImpl.java

private String format(String requesterPhone, MessageType type) {
    if (Pattern.matches(localNumberExpression, requesterPhone)) {
        if (type == MessageType.VOICE)
            requesterPhone = requesterPhone.substring(1);
        else/*w  ww.ja  v a2s  .  com*/
            requesterPhone = defaultCountryCode + requesterPhone.substring(1);
    }
    return requesterPhone;
}

From source file:edu.lafayette.metadb.web.metadata.UpdateAdminDescMetadata.java

private static boolean isValidDisplayDate(String value) {
    //must be at least yyyy
    if (value.length() == 0)
        return true;
    if (value.length() < 4)
        return false;
    return isValidSearchDate(value) || (Pattern.matches("\\d\\d\\d\\ds", value))
            || (Pattern.matches("\\d\\d\\d\\d or \\d\\d\\d\\d", value))
            || (Pattern.matches("(after|before) \\d\\d\\d\\d", value))
            || (Pattern.matches("circa \\d\\d\\d\\d(([-](0[1-9]|1[012]))?)", value));

}

From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceDirectoryHandler.java

/**
 * @see WorkspaceDirectoryHandler#ensurePathIsAllowed(String)
 *///  w  w w. j  av  a 2  s  .  c om
@Override
public void ensurePathIsAllowed(String path) throws DisallowedPathException {

    Path pathToCheck = Paths.get("", path);

    Iterator<Path> pathIterator = pathToCheck.iterator();
    while (pathIterator.hasNext()) {
        Path currentPathItem = pathIterator.next();
        String nameToMatch = currentPathItem.getFileName().toString();
        for (String regex : disallowedFolderNamesWorkspace) {
            if (Pattern.matches(regex, nameToMatch)) {
                String message = "The path [" + path + "] contains a disallowed file/folder name ("
                        + nameToMatch + ")";
                throw new DisallowedPathException(path, message);
            }
        }
    }
}