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:mobile.service.RNSService.java

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

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

    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 != price) {
        if (!Pattern.matches("^\\d{0,8}(\\.\\d)?$", price) && !"-1".equals(price)) {
            return ServiceResult.error("100005", "??8?1??");
        } else {
            data.put("price", price);
        }
    }
    if (null != skillsTags) {
        data.set("tags", Json.toJson(skillsTags));
    }
    if (null != attachs) {
        if (attachs.size() > 5) {
            return ServiceResult.error("1005", "???");
        }
        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 = createOrUpdateService(data, null);
    if (!updateResult.isSuccess()) {
        return updateResult;
    }

    return ServiceResult.success();
}

From source file:fr.fastconnect.factory.tibco.bw.maven.packaging.MergePropertiesMojo.java

protected boolean isAWildCard(String key) {
    String regexVariable = "bw\\[[^\\**]*\\]/variables\\[.*\\]/variable\\[.*\\]"; // is a wildcard only if it has a '*' in bw[] for variables (because a variable can have '*' in their name)

    return key.contains("*") && !Pattern.matches(regexVariable, key);
}

From source file:ambroafb.general.AnnotiationUtils.java

private static boolean checkValidationForContentRateAnnotation(Field field, Object currSceneController) {
    boolean contentIsCorrect = false;
    Annotations.ContentRate annotation = field.getAnnotation(Annotations.ContentRate.class);
    Object[] typeAndContent = getNodesTypeAndContent(field, currSceneController);

    if (!Pattern.matches(annotation.valueForIntegerPart(), (String) typeAndContent[1])) {
        String explainFromBundle = GeneralConfig.getInstance().getTitleFor(annotation.explainForIntegerPart());
        String integerPartExp = explainFromBundle.replaceFirst("#",
                "" + Annotations.ContentRate.integerPartLen);
        changeNodeTitleLabelVisual((Node) typeAndContent[0], integerPartExp);
    } else if (!Pattern.matches(annotation.valueForFractionalPart(), (String) typeAndContent[1])) {
        String explainFromBundle = GeneralConfig.getInstance()
                .getTitleFor(annotation.explainForFractionalPart());
        String fractionalPartExp = explainFromBundle.replaceFirst("#",
                "" + Annotations.ContentRate.fractionalPartLen);
        changeNodeTitleLabelVisual((Node) typeAndContent[0], fractionalPartExp);
    } else if (!Pattern.matches(annotation.valueForWhole(), (String) typeAndContent[1])) {
        changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForWhole());
    } else {/*from   ww  w.j a  va2s . co m*/
        changeNodeTitleLabelVisual((Node) typeAndContent[0], "");
        contentIsCorrect = true;
    }
    return contentIsCorrect;
}

From source file:be.fedict.eid.pkira.blm.model.contracthandler.services.FieldValidatorBean.java

protected void validatePhone(String name, String value, List<String> messages) {
    if (value != null && !Pattern.matches(PHONE_PATTERN, value)) {
        messages.add(name + " is not a valid phone number");
    }//from   w  ww.  j av a2 s. c  o m
}

From source file:dhbw.ka.mwi.businesshorizon2.ui.login.LogInScreenPresenter.java

/**
 * Prueft ob es sich um einen gltigen Nachnamen handelt. Gibt "true" fuer
 * gltig und "false" fuer nicht gltig zurueck. Ein Nachname muss mit einem
 * Grobuchstaben beginnen und darf maximal 20 Zeichen lang sein. Beginnt er nicht mit einem Grobuchstabe,
 * wird der erste Buchstabe automatisch in einen Grobuchstabe konvertiert. Weiterhin
 * ist ein Bindestrich "-" erlaubt. Bei keiner Uebereinstimmung wird zudem
 * eine Fehlermeldung an die ViewImpl zur Ausgabe zurueckgegeben.
 * /*from  w  w w  .ja  va2 s  . c  om*/
 * @author Marcel Rosenberger, Annika Weis, Marco Glaser
 * @return Ob es sich um einen gltigen Nachnamen handelt.
 */
private boolean validateLastName() {
    boolean validLastName;

    // hier wird der Nachname berprft
    if (Pattern.matches("^[A-Z][a-zA-Z\\ \\-]{1,19}$", lastName)) {
        validLastName = true;
        logger.debug("Nachname gltig.");
    } else if (Pattern.matches("^[a-zA-Z\\ \\-]{1,19}$", lastName)) {
        validLastName = true;
        char firstLetter = lastName.charAt(0);
        firstLetter = Character.toUpperCase(firstLetter);
        String upperCaseName = firstLetter + lastName.substring(1);
        this.lastName = upperCaseName;
    } else {
        validLastName = false;
        getView().showErrorMessage("Bitte geben Sie einen gltigen Nachnamen ein.");
        logger.debug("Nachname ungltig.");
    }

    return validLastName;
}

From source file:com.zentri.otademo.ZentriOSBLEService.java

@Override
public void onScanResult(String deviceName) {
    Log.d(TAG, "onScanResult");

    if (deviceName != null && !Pattern.matches(PATTERN_MAC_ADDRESS, deviceName)) {
        Intent intent = new Intent(ACTION_SCAN_RESULT);
        intent.putExtra(EXTRA_NAME, deviceName);
        mBroadcastManager.sendBroadcast(intent);
    }/*from   w  w  w. j a va 2s. co m*/
}

From source file:org.openehealth.coala.beans.PatientBean.java

/**
 * Method to validate search parameters patientID, givenName, lastName and
 * dateOfBirth as a group. This is needed to have proper error notification
 * on failed search field input at search view, if user provides non
 * matching (invalid) input./*w w  w.ja v  a 2 s.  co m*/
 * 
 * @param event
 */
public void validateSearchParameters(ComponentSystemEvent event) {
    searchString.delete(0, searchString.length());
    FacesContext fc = FacesContext.getCurrentInstance();
    String messages = fc.getApplication().getMessageBundle();
    Locale locale = new Locale(localeHandler.getLocale());
    ResourceBundle bundle = ResourceBundle.getBundle(messages, locale);

    UIComponent components = event.getComponent();

    UIInput patientIDInput = (UIInput) components.findComponent("patientID");
    String patientID = patientIDInput.getLocalValue().toString();
    UIInput givenNameInput = (UIInput) components.findComponent("givenName");
    String givenName = givenNameInput.getLocalValue().toString();
    UIInput lastNameInput = (UIInput) components.findComponent("lastName");
    String lastName = lastNameInput.getLocalValue().toString();
    UIInput dateOfBirthInput = (UIInput) components.findComponent("dateOfBirth");

    boolean patientIDEmpty = false;
    boolean givenNameEmpty = false;
    boolean lastNameEmpty = false;
    boolean dateOfBirthEmpty = false;
    if (patientIDInput.getLocalValue() == null || patientIDInput.getLocalValue().toString().trim().isEmpty()) {
        patientIDEmpty = true;
    }
    if (givenNameInput.getLocalValue() == null || givenNameInput.getLocalValue().toString().trim().isEmpty()) {
        givenNameEmpty = true;
    }
    if (lastNameInput.getLocalValue() == null || lastNameInput.getLocalValue().toString().trim().isEmpty()) {
        lastNameEmpty = true;
    }
    if (dateOfBirthInput.getLocalValue() == null
            || dateOfBirthInput.getLocalValue().toString().trim().isEmpty()) {
        dateOfBirthEmpty = true;
    }

    if (patientIDEmpty && givenNameEmpty && lastNameEmpty && dateOfBirthEmpty) {
        FacesMessage msg = new FacesMessage(bundle.getString("errors.nonEmptySearchKey"), "");
        msg.setSeverity(FacesMessage.SEVERITY_WARN);
        fc.addMessage(components.getClientId(), msg);
        // passed to the Render Response phase
        fc.renderResponse();
        cleanOutdatedViewState();
        setPatients(new ListDataModel<Patient>());

    } else {
        boolean validationErrorOccured = false;
        // validating correctness of patientID value if it is set
        if (!patientIDEmpty) {
            if (!StringUtils.isNumeric(patientID)) {
                FacesMessage msg = new FacesMessage(bundle.getString("errors.numericPatientID"), "");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                fc.addMessage(patientIDInput.getClientId(), msg);
                validationErrorOccured = true;
            } else { // ok here -> no actions required, move on now :)
            }
            searchString.append(bundle.getString("search.patient_id") + ": " + patientID + " ");
        }
        // validating correctness of givenName value if it is set
        if (!givenNameEmpty) {

            //            String givenNameChecked = checkAndFixWrongCharset(givenName);
            boolean patternOK = Pattern.matches("[a-zA-Z]*[*]?", givenName);
            if (!patternOK) {
                FacesMessage msg = new FacesMessage(bundle.getString("errors.nonNumericGivenName"), "");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                fc.addMessage(givenNameInput.getClientId(), msg);
                validationErrorOccured = true;
            } else { // ok here -> no actions required, move on now :)
            }
            searchString.append(bundle.getString("search.patient_givenName") + ": " + givenName + " ");
        }
        // validating correctness of lastname value if it is set
        if (!lastNameEmpty) {

            //            String lastNameChecked = checkAndFixWrongCharset(lastName);
            boolean patternOK = Pattern.matches("[a-zA-Z]*[*]?", lastName);
            if (!patternOK) {
                FacesMessage msg = new FacesMessage(bundle.getString("errors.nonNumericLastName"), "");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                fc.addMessage(lastNameInput.getClientId(), msg);
                validationErrorOccured = true;
            } else { // ok here -> no actions required, move on now :)
            }
            searchString.append(bundle.getString("search.patient_lastname") + ": " + lastName + " ");
        }
        // validating correctness of dateOfBirth value if it is set
        if (!dateOfBirthEmpty) {
            try {
                // check for a valid date format by casting into a date
                Date dateOfBirth = (Date) dateOfBirthInput.getLocalValue();
                // if we have real Date object -> check for future date
                // value which make no sense here!
                if (dateOfBirth.after(new Date())) {
                    FacesMessage msg = new FacesMessage("Date of birth must not be in the future!", "");
                    msg.setSeverity(FacesMessage.SEVERITY_WARN);
                    fc.addMessage(dateOfBirthInput.getClientId(), msg);
                    validationErrorOccured = true;
                } else { // ok here -> no actions required, move on now :)
                }
            } catch (RuntimeException rt) {
                // occurs if no valid Date object was in the input field
                // given by the user input
                FacesMessage msg = new FacesMessage(
                        "Please provide a valid date of birth in a useful format. Hint: 'Calendar'!", "");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                fc.addMessage(dateOfBirthInput.getClientId(), msg);
                validationErrorOccured = true;
            }
        }
        /*
         * FINALLY CHECK IF ANY ERRORS HAVE OCCURED WHICH CAUSE THE EARLY
         * RENDER RESPONSE... -> STOP ANY SEARCH!
         */
        if (validationErrorOccured) {
            // passed to the Render Response phase
            fc.renderResponse();
            cleanOutdatedViewState();
            setPatients(new ListDataModel<Patient>());
        }
    }
}

From source file:com.openkm.module.db.DbDocumentModule.java

/**
 * Used when big files and FileUpload//w  w  w.  j ava2 s  . co m
 */
public Document create(String token, Document doc, InputStream is, long size, String userId,
        Ref<FileUploadResponse> fuResponse)
        throws UnsupportedMimeTypeException, FileSizeExceededException, UserQuotaExceededException,
        VirusDetectedException, ItemExistsException, PathNotFoundException, AccessDeniedException,
        RepositoryException, IOException, DatabaseException, ExtensionException, AutomationException {
    log.debug("create({}, {}, {}, {}, {}, {})", new Object[] { token, doc, is, size, userId, fuResponse });
    long begin = System.currentTimeMillis();
    Document newDocument = null;
    Authentication auth = null, oldAuth = null;

    if (Config.SYSTEM_READONLY) {
        throw new AccessDeniedException("System is in read-only mode");
    }

    if (!PathUtils.checkPath(doc.getPath())) {
        throw new RepositoryException("Invalid path: " + doc.getPath());
    }

    String parentPath = PathUtils.getParent(doc.getPath());
    String name = PathUtils.getName(doc.getPath());

    // Add to KEA - must have the same extension
    int idx = name.lastIndexOf('.');
    String fileExtension = idx > 0 ? name.substring(idx) : ".tmp";
    File tmp = File.createTempFile("okm", fileExtension);

    try {
        if (token == null) {
            auth = PrincipalUtils.getAuthentication();
        } else {
            oldAuth = PrincipalUtils.getAuthentication();
            auth = PrincipalUtils.getAuthenticationByToken(token);
        }

        if (Config.MAX_FILE_SIZE > 0 && size > Config.MAX_FILE_SIZE) {
            log.error("Uploaded file size: {} ({}), Max file size: {} ({})",
                    new Object[] { FormatUtil.formatSize(size), size,
                            FormatUtil.formatSize(Config.MAX_FILE_SIZE), Config.MAX_FILE_SIZE });
            String usr = userId == null ? auth.getName() : userId;
            UserActivity.log(usr, "ERROR_FILE_SIZE_EXCEEDED", null, doc.getPath(), FormatUtil.formatSize(size));
            throw new FileSizeExceededException(FormatUtil.formatSize(size));
        }

        // Escape dangerous chars in name
        name = PathUtils.escape(name);

        if (!name.isEmpty()) {
            doc.setPath(parentPath + "/" + name);

            // Check file restrictions
            String mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
            doc.setMimeType(mimeType);

            if (Config.RESTRICT_FILE_MIME && MimeTypeDAO.findByName(mimeType) == null) {
                String usr = userId == null ? auth.getName() : userId;
                UserActivity.log(usr, "ERROR_UNSUPPORTED_MIME_TYPE", null, doc.getPath(), mimeType);
                throw new UnsupportedMimeTypeException(mimeType);
            }

            // Restrict for extension
            if (!Config.RESTRICT_FILE_NAME.isEmpty()) {
                StringTokenizer st = new StringTokenizer(Config.RESTRICT_FILE_NAME, Config.LIST_SEPARATOR);

                while (st.hasMoreTokens()) {
                    String wc = st.nextToken().trim();
                    String re = ConfigUtils.wildcard2regexp(wc);

                    if (Pattern.matches(re, name)) {
                        String usr = userId == null ? auth.getName() : userId;
                        UserActivity.log(usr, "ERROR_UNSUPPORTED_MIME_TYPE", null, doc.getPath(), mimeType);
                        throw new UnsupportedMimeTypeException(mimeType);
                    }
                }
            }

            // Manage temporary files
            byte[] buff = new byte[4 * 1024];
            FileOutputStream fos = new FileOutputStream(tmp);
            int read;

            while ((read = is.read(buff)) != -1) {
                fos.write(buff, 0, read);
            }

            fos.flush();
            fos.close();
            is.close();
            is = new FileInputStream(tmp);

            if (!Config.SYSTEM_ANTIVIR.equals("")) {
                String info = VirusDetection.detect(tmp);

                if (info != null) {
                    String usr = userId == null ? auth.getName() : userId;
                    UserActivity.log(usr, "ERROR_VIRUS_DETECTED", null, doc.getPath(), info);
                    throw new VirusDetectedException(info);
                }
            }

            String parentUuid = NodeBaseDAO.getInstance().getUuidFromPath(parentPath);
            NodeBase parentNode = NodeBaseDAO.getInstance().findByPk(parentUuid);

            // AUTOMATION - PRE
            // INSIDE BaseDocumentModule.create

            // Create node
            Set<String> keywords = doc.getKeywords() != null ? doc.getKeywords() : new HashSet<String>();
            NodeDocument docNode = BaseDocumentModule.create(auth.getName(), parentPath, parentNode, name,
                    doc.getTitle(), doc.getCreated(), mimeType, is, size, keywords, new HashSet<String>(),
                    new HashSet<NodeProperty>(), new ArrayList<NodeNote>(), fuResponse);

            // AUTOMATION - POST
            // INSIDE BaseDocumentModule.create

            // Set returned folder properties
            newDocument = BaseDocumentModule.getProperties(auth.getName(), docNode);

            // Setting wizard properties
            // INSIDE BaseDocumentModule.create

            if (fuResponse.get() == null) {
                fuResponse.set(new FileUploadResponse());
            }

            fuResponse.get().setHasAutomation(AutomationManager.getInstance().hasAutomation());

            if (userId == null) {
                // Check subscriptions
                BaseNotificationModule.checkSubscriptions(docNode, auth.getName(), "CREATE_DOCUMENT", null);

                // Activity log
                UserActivity.log(auth.getName(), "CREATE_DOCUMENT", docNode.getUuid(), doc.getPath(),
                        mimeType + ", " + size);
            } else {
                // Check subscriptions
                BaseNotificationModule.checkSubscriptions(docNode, userId, "CREATE_MAIL_ATTACHMENT", null);

                // Activity log
                UserActivity.log(userId, "CREATE_MAIL_ATTACHMENT", docNode.getUuid(), doc.getPath(),
                        mimeType + ", " + size);
            }
        } else {
            throw new RepositoryException("Invalid document name");
        }
    } finally {
        IOUtils.closeQuietly(is);
        org.apache.commons.io.FileUtils.deleteQuietly(tmp);

        if (token != null) {
            PrincipalUtils.setAuthentication(oldAuth);
        }
    }

    log.trace("create.Time: {}", System.currentTimeMillis() - begin);
    log.debug("create: {}", newDocument);
    return newDocument;
}

From source file:org.motechproject.mobile.imp.serivce.IMPServiceImpl.java

public String formatPhoneNumber(String requesterPhone) {
    if (requesterPhone == null || requesterPhone.isEmpty()) {
        return null;
    }/*from ww w  .ja v a  2s.c  om*/

    String formattedNumber = requesterPhone;
    if (Pattern.matches(localNumberExpression, requesterPhone)) {
        formattedNumber = defaultCountryCode + requesterPhone.substring(1);
    }

    return formattedNumber;
}

From source file:com.silverpeas.util.StringUtil.java

/**
   *//from   w w w  .  j  a v a2  s .c o  m
   * Validate the form of an email address. <P> Return <tt>true</tt> only if <ul> <li>
   * <tt>aEmailAddress</tt> can successfully construct an
   * {@link javax.mail.internet.InternetAddress} <li>when parsed with "
   *
   * @" as delimiter, <tt>aEmailAddress</tt> contains two tokens which satisfy
   * {@link hirondelle.web4j.util.Util#textHasContent}. </ul> <P> The second condition arises since
   * local email addresses, simply of the form "<tt>albert</tt>", for example, are valid for
   * {@link javax.mail.internet.InternetAddress}, but almost always undesired.
   *
   * @param aEmailAddress the address to be validated
   * @return true is the address is a valid email address - false otherwise.
   */
  public static boolean isValidEmailAddress(String aEmailAddress) {
      if (aEmailAddress == null) {
          return false;
      }
      boolean result;
      try {
          new InternetAddress(aEmailAddress);
          result = Pattern.matches(EMAIL_PATTERN, aEmailAddress);
      } catch (AddressException ex) {
          result = false;
      }
      return result;
  }