use of java.util.regex.PatternSyntaxException in project openmrs-core by openmrs.
the class OpenmrsUtil method validatePassword.
/**
* Utility to check the validity of a password for a certain {@link User}. Passwords must be
* non-null. Their required strength is configured via global properties:
* <table summary="Configuration props">
* <tr>
* <th>Description</th>
* <th>Property</th>
* <th>Default Value</th>
* </tr>
* <tr>
* <th>Require that it not match the {@link User}'s username or system id
* <th>{@link OpenmrsConstants#GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID}</th>
* <th>true</th>
* </tr>
* <tr>
* <th>Require a minimum length
* <th>{@link OpenmrsConstants#GP_PASSWORD_MINIMUM_LENGTH}</th>
* <th>8</th>
* </tr>
* <tr>
* <th>Require both an upper and lower case character
* <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE}</th>
* <th>true</th>
* </tr>
* <tr>
* <th>Require at least one numeric character
* <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_DIGIT}</th>
* <th>true</th>
* </tr>
* <tr>
* <th>Require at least one non-numeric character
* <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_NON_DIGIT}</th>
* <th>true</th>
* </tr>
* <tr>
* <th>Require a match on the specified regular expression
* <th>{@link OpenmrsConstants#GP_PASSWORD_CUSTOM_REGEX}</th>
* <th>null</th>
* </tr>
* </table>
*
* @param username user name of the user with password to validated
* @param password string that will be validated
* @param systemId system id of the user with password to be validated
* @throws PasswordException
* @since 1.5
* @should fail with short password by default
* @should fail with short password if not allowed
* @should pass with short password if allowed
* @should fail with digit only password by default
* @should fail with digit only password if not allowed
* @should pass with digit only password if allowed
* @should fail with char only password by default
* @should fail with char only password if not allowed
* @should pass with char only password if allowed
* @should fail without both upper and lower case password by default
* @should fail without both upper and lower case password if not allowed
* @should pass without both upper and lower case password if allowed
* @should fail with password equals to user name by default
* @should fail with password equals to user name if not allowed
* @should pass with password equals to user name if allowed
* @should fail with password equals to system id by default
* @should fail with password equals to system id if not allowed
* @should pass with password equals to system id if allowed
* @should fail with password not matching configured regex
* @should pass with password matching configured regex
* @should allow password to contain non alphanumeric characters
* @should allow password to contain white spaces
* @should still work without an open session
*/
public static void validatePassword(String username, String password, String systemId) throws PasswordException {
// default values for all of the global properties
String userGp = "true";
String lengthGp = "8";
String caseGp = "true";
String digitGp = "true";
String nonDigitGp = "true";
String regexGp = null;
AdministrationService svc = null;
try {
svc = Context.getAdministrationService();
} catch (APIException apiEx) {
// if a service isn't available, fail quietly and just do the
// defaults
log.debug("Unable to get global properties", apiEx);
}
if (svc != null && Context.isSessionOpen()) {
// (the session won't be open here to allow for the unit test to
// fake not having the admin service available)
userGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID, userGp);
lengthGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_MINIMUM_LENGTH, lengthGp);
caseGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE, caseGp);
digitGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_DIGIT, digitGp);
nonDigitGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_NON_DIGIT, nonDigitGp);
regexGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_CUSTOM_REGEX, regexGp);
}
if (password == null) {
throw new WeakPasswordException();
}
if ("true".equals(userGp) && (password.equals(username) || password.equals(systemId))) {
throw new WeakPasswordException();
}
if (StringUtils.isNotEmpty(lengthGp)) {
try {
int minLength = Integer.parseInt(lengthGp);
if (password.length() < minLength) {
throw new ShortPasswordException(getMessage("error.password.length", lengthGp));
}
} catch (NumberFormatException nfe) {
log.warn("Error in global property <" + OpenmrsConstants.GP_PASSWORD_MINIMUM_LENGTH + "> must be an Integer");
}
}
if ("true".equals(caseGp) && !containsUpperAndLowerCase(password)) {
throw new InvalidCharactersPasswordException(getMessage("error.password.requireMixedCase"));
}
if ("true".equals(digitGp) && !containsDigit(password)) {
throw new InvalidCharactersPasswordException(getMessage("error.password.requireNumber"));
}
if ("true".equals(nonDigitGp) && containsOnlyDigits(password)) {
throw new InvalidCharactersPasswordException(getMessage("error.password.requireLetter"));
}
if (StringUtils.isNotEmpty(regexGp)) {
try {
Pattern pattern = Pattern.compile(regexGp);
Matcher matcher = pattern.matcher(password);
if (!matcher.matches()) {
throw new InvalidCharactersPasswordException(getMessage("error.password.different"));
}
} catch (PatternSyntaxException pse) {
log.warn("Invalid regex of " + regexGp + " defined in global property <" + OpenmrsConstants.GP_PASSWORD_CUSTOM_REGEX + ">.");
}
}
}
use of java.util.regex.PatternSyntaxException in project h2database by h2database.
the class Function method getValueWithArgs.
private Value getValueWithArgs(Session session, Expression[] args) {
Value[] values = new Value[args.length];
if (info.nullIfParameterIsNull) {
for (int i = 0; i < args.length; i++) {
Expression e = args[i];
Value v = e.getValue(session);
if (v == ValueNull.INSTANCE) {
return ValueNull.INSTANCE;
}
values[i] = v;
}
}
Value v0 = getNullOrValue(session, args, values, 0);
Value resultSimple = getSimpleValue(session, v0, args, values);
if (resultSimple != null) {
return resultSimple;
}
Value v1 = getNullOrValue(session, args, values, 1);
Value v2 = getNullOrValue(session, args, values, 2);
Value v3 = getNullOrValue(session, args, values, 3);
Value v4 = getNullOrValue(session, args, values, 4);
Value v5 = getNullOrValue(session, args, values, 5);
Value result;
switch(info.type) {
case ATAN2:
result = ValueDouble.get(Math.atan2(v0.getDouble(), v1.getDouble()));
break;
case BITAND:
result = ValueLong.get(v0.getLong() & v1.getLong());
break;
case BITGET:
result = ValueBoolean.get((v0.getLong() & (1L << v1.getInt())) != 0);
break;
case BITOR:
result = ValueLong.get(v0.getLong() | v1.getLong());
break;
case BITXOR:
result = ValueLong.get(v0.getLong() ^ v1.getLong());
break;
case MOD:
{
long x = v1.getLong();
if (x == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
result = ValueLong.get(v0.getLong() % x);
break;
}
case POWER:
result = ValueDouble.get(Math.pow(v0.getDouble(), v1.getDouble()));
break;
case ROUND:
{
double f = v1 == null ? 1. : Math.pow(10., v1.getDouble());
double middleResult = v0.getDouble() * f;
int oneWithSymbol = middleResult > 0 ? 1 : -1;
result = ValueDouble.get(Math.round(Math.abs(middleResult)) / f * oneWithSymbol);
break;
}
case TRUNCATE:
{
if (v0.getType() == Value.TIMESTAMP) {
result = ValueTimestamp.fromDateValueAndNanos(((ValueTimestamp) v0).getDateValue(), 0);
} else if (v0.getType() == Value.DATE) {
result = ValueTimestamp.fromDateValueAndNanos(((ValueDate) v0).getDateValue(), 0);
} else if (v0.getType() == Value.TIMESTAMP_TZ) {
ValueTimestampTimeZone ts = (ValueTimestampTimeZone) v0;
result = ValueTimestampTimeZone.fromDateValueAndNanos(ts.getDateValue(), 0, ts.getTimeZoneOffsetMins());
} else if (v0.getType() == Value.STRING) {
ValueTimestamp ts = ValueTimestamp.parse(v0.getString(), session.getDatabase().getMode());
result = ValueTimestamp.fromDateValueAndNanos(ts.getDateValue(), 0);
} else {
double d = v0.getDouble();
int p = v1 == null ? 0 : v1.getInt();
double f = Math.pow(10., p);
double g = d * f;
result = ValueDouble.get(((d < 0) ? Math.ceil(g) : Math.floor(g)) / f);
}
break;
}
case HASH:
result = ValueBytes.getNoCopy(getHash(v0.getString(), v1.getBytesNoCopy(), v2.getInt()));
break;
case ENCRYPT:
result = ValueBytes.getNoCopy(encrypt(v0.getString(), v1.getBytesNoCopy(), v2.getBytesNoCopy()));
break;
case DECRYPT:
result = ValueBytes.getNoCopy(decrypt(v0.getString(), v1.getBytesNoCopy(), v2.getBytesNoCopy()));
break;
case COMPRESS:
{
String algorithm = null;
if (v1 != null) {
algorithm = v1.getString();
}
result = ValueBytes.getNoCopy(CompressTool.getInstance().compress(v0.getBytesNoCopy(), algorithm));
break;
}
case DIFFERENCE:
result = ValueInt.get(getDifference(v0.getString(), v1.getString()));
break;
case INSERT:
{
if (v1 == ValueNull.INSTANCE || v2 == ValueNull.INSTANCE) {
result = v1;
} else {
result = ValueString.get(insert(v0.getString(), v1.getInt(), v2.getInt(), v3.getString()), database.getMode().treatEmptyStringsAsNull);
}
break;
}
case LEFT:
result = ValueString.get(left(v0.getString(), v1.getInt()), database.getMode().treatEmptyStringsAsNull);
break;
case LOCATE:
{
int start = v2 == null ? 0 : v2.getInt();
result = ValueInt.get(locate(v0.getString(), v1.getString(), start));
break;
}
case INSTR:
{
int start = v2 == null ? 0 : v2.getInt();
result = ValueInt.get(locate(v1.getString(), v0.getString(), start));
break;
}
case REPEAT:
{
int count = Math.max(0, v1.getInt());
result = ValueString.get(repeat(v0.getString(), count), database.getMode().treatEmptyStringsAsNull);
break;
}
case REPLACE:
{
if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE || v2 == ValueNull.INSTANCE && database.getMode().getEnum() != Mode.ModeEnum.Oracle) {
result = ValueNull.INSTANCE;
} else {
String s0 = v0.getString();
String s1 = v1.getString();
String s2 = (v2 == null) ? "" : v2.getString();
if (s2 == null) {
s2 = "";
}
result = ValueString.get(StringUtils.replaceAll(s0, s1, s2), database.getMode().treatEmptyStringsAsNull);
}
break;
}
case RIGHT:
result = ValueString.get(right(v0.getString(), v1.getInt()), database.getMode().treatEmptyStringsAsNull);
break;
case LTRIM:
result = ValueString.get(StringUtils.trim(v0.getString(), true, false, v1 == null ? " " : v1.getString()), database.getMode().treatEmptyStringsAsNull);
break;
case TRIM:
result = ValueString.get(StringUtils.trim(v0.getString(), true, true, v1 == null ? " " : v1.getString()), database.getMode().treatEmptyStringsAsNull);
break;
case RTRIM:
result = ValueString.get(StringUtils.trim(v0.getString(), false, true, v1 == null ? " " : v1.getString()), database.getMode().treatEmptyStringsAsNull);
break;
case SUBSTR:
case SUBSTRING:
{
String s = v0.getString();
int offset = v1.getInt();
if (offset < 0) {
offset = s.length() + offset + 1;
}
int length = v2 == null ? s.length() : v2.getInt();
result = ValueString.get(substring(s, offset, length), database.getMode().treatEmptyStringsAsNull);
break;
}
case POSITION:
result = ValueInt.get(locate(v0.getString(), v1.getString(), 0));
break;
case XMLATTR:
result = ValueString.get(StringUtils.xmlAttr(v0.getString(), v1.getString()), database.getMode().treatEmptyStringsAsNull);
break;
case XMLNODE:
{
String attr = v1 == null ? null : v1 == ValueNull.INSTANCE ? null : v1.getString();
String content = v2 == null ? null : v2 == ValueNull.INSTANCE ? null : v2.getString();
boolean indent = v3 == null ? true : v3.getBoolean();
result = ValueString.get(StringUtils.xmlNode(v0.getString(), attr, content, indent), database.getMode().treatEmptyStringsAsNull);
break;
}
case REGEXP_REPLACE:
{
String regexp = v1.getString();
String replacement = v2.getString();
if (database.getMode().regexpReplaceBackslashReferences) {
if ((replacement.indexOf('\\') >= 0) || (replacement.indexOf('$') >= 0)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);
if (c == '$') {
sb.append('\\');
} else if (c == '\\' && ++i < replacement.length()) {
c = replacement.charAt(i);
sb.append(c >= '0' && c <= '9' ? '$' : '\\');
}
sb.append(c);
}
replacement = sb.toString();
}
}
String regexpMode = v3 == null || v3.getString() == null ? "" : v3.getString();
int flags = makeRegexpFlags(regexpMode);
try {
result = ValueString.get(Pattern.compile(regexp, flags).matcher(v0.getString()).replaceAll(replacement), database.getMode().treatEmptyStringsAsNull);
} catch (StringIndexOutOfBoundsException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, replacement);
} catch (PatternSyntaxException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
} catch (IllegalArgumentException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, replacement);
}
break;
}
case RPAD:
result = ValueString.get(StringUtils.pad(v0.getString(), v1.getInt(), v2 == null ? null : v2.getString(), true), database.getMode().treatEmptyStringsAsNull);
break;
case LPAD:
result = ValueString.get(StringUtils.pad(v0.getString(), v1.getInt(), v2 == null ? null : v2.getString(), false), database.getMode().treatEmptyStringsAsNull);
break;
case ORA_HASH:
result = ValueLong.get(oraHash(v0.getString(), v1 == null ? null : v1.getInt(), v2 == null ? null : v2.getInt()));
break;
case TO_CHAR:
switch(v0.getType()) {
case Value.TIME:
case Value.DATE:
case Value.TIMESTAMP:
case Value.TIMESTAMP_TZ:
result = ValueString.get(ToChar.toCharDateTime(v0, v1 == null ? null : v1.getString(), v2 == null ? null : v2.getString()), database.getMode().treatEmptyStringsAsNull);
break;
case Value.SHORT:
case Value.INT:
case Value.LONG:
case Value.DECIMAL:
case Value.DOUBLE:
case Value.FLOAT:
result = ValueString.get(ToChar.toChar(v0.getBigDecimal(), v1 == null ? null : v1.getString(), v2 == null ? null : v2.getString()), database.getMode().treatEmptyStringsAsNull);
break;
default:
result = ValueString.get(v0.getString(), database.getMode().treatEmptyStringsAsNull);
}
break;
case TO_DATE:
result = ToDateParser.toDate(v0.getString(), v1 == null ? null : v1.getString());
break;
case TO_TIMESTAMP:
result = ToDateParser.toTimestamp(v0.getString(), v1 == null ? null : v1.getString());
break;
case ADD_MONTHS:
result = DateTimeFunctions.dateadd("MONTH", v1.getInt(), v0);
break;
case TO_TIMESTAMP_TZ:
result = ToDateParser.toTimestampTz(v0.getString(), v1 == null ? null : v1.getString());
break;
case TRANSLATE:
{
String matching = v1.getString();
String replacement = v2.getString();
result = ValueString.get(translate(v0.getString(), matching, replacement), database.getMode().treatEmptyStringsAsNull);
break;
}
case H2VERSION:
result = ValueString.get(Constants.getVersion(), database.getMode().treatEmptyStringsAsNull);
break;
case DATE_ADD:
result = DateTimeFunctions.dateadd(v0.getString(), v1.getLong(), v2);
break;
case DATE_DIFF:
result = ValueLong.get(DateTimeFunctions.datediff(v0.getString(), v1, v2));
break;
case DATE_TRUNC:
result = DateTimeFunctions.truncateDate(v0.getString(), v1);
break;
case EXTRACT:
result = DateTimeFunctions.extract(v0.getString(), v1);
break;
case FORMATDATETIME:
{
if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE) {
result = ValueNull.INSTANCE;
} else {
String locale = v2 == null ? null : v2 == ValueNull.INSTANCE ? null : v2.getString();
String tz = v3 == null ? null : v3 == ValueNull.INSTANCE ? null : v3.getString();
if (v0 instanceof ValueTimestampTimeZone) {
tz = DateTimeUtils.timeZoneNameFromOffsetMins(((ValueTimestampTimeZone) v0).getTimeZoneOffsetMins());
}
result = ValueString.get(DateTimeFunctions.formatDateTime(v0.getTimestamp(), v1.getString(), locale, tz), database.getMode().treatEmptyStringsAsNull);
}
break;
}
case PARSEDATETIME:
{
if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE) {
result = ValueNull.INSTANCE;
} else {
String locale = v2 == null ? null : v2 == ValueNull.INSTANCE ? null : v2.getString();
String tz = v3 == null ? null : v3 == ValueNull.INSTANCE ? null : v3.getString();
java.util.Date d = DateTimeFunctions.parseDateTime(v0.getString(), v1.getString(), locale, tz);
result = ValueTimestamp.fromMillis(d.getTime());
}
break;
}
case NULLIF:
result = database.areEqual(v0, v1) ? ValueNull.INSTANCE : v0;
break;
// system
case NEXTVAL:
{
Sequence sequence = getSequence(session, v0, v1);
SequenceValue value = new SequenceValue(sequence);
result = value.getValue(session);
break;
}
case CURRVAL:
{
Sequence sequence = getSequence(session, v0, v1);
result = ValueLong.get(sequence.getCurrentValue());
break;
}
case CSVREAD:
{
String fileName = v0.getString();
String columnList = v1 == null ? null : v1.getString();
Csv csv = new Csv();
String options = v2 == null ? null : v2.getString();
String charset = null;
if (options != null && options.indexOf('=') >= 0) {
charset = csv.setOptions(options);
} else {
charset = options;
String fieldSeparatorRead = v3 == null ? null : v3.getString();
String fieldDelimiter = v4 == null ? null : v4.getString();
String escapeCharacter = v5 == null ? null : v5.getString();
Value v6 = getNullOrValue(session, args, values, 6);
String nullString = v6 == null ? null : v6.getString();
setCsvDelimiterEscape(csv, fieldSeparatorRead, fieldDelimiter, escapeCharacter);
csv.setNullString(nullString);
}
char fieldSeparator = csv.getFieldSeparatorRead();
String[] columns = StringUtils.arraySplit(columnList, fieldSeparator, true);
try {
result = ValueResultSet.get(csv.read(fileName, columns, charset));
} catch (SQLException e) {
throw DbException.convert(e);
}
break;
}
case LINK_SCHEMA:
{
session.getUser().checkAdmin();
Connection conn = session.createConnection(false);
ResultSet rs = LinkSchema.linkSchema(conn, v0.getString(), v1.getString(), v2.getString(), v3.getString(), v4.getString(), v5.getString());
result = ValueResultSet.get(rs);
break;
}
case CSVWRITE:
{
session.getUser().checkAdmin();
Connection conn = session.createConnection(false);
Csv csv = new Csv();
String options = v2 == null ? null : v2.getString();
String charset = null;
if (options != null && options.indexOf('=') >= 0) {
charset = csv.setOptions(options);
} else {
charset = options;
String fieldSeparatorWrite = v3 == null ? null : v3.getString();
String fieldDelimiter = v4 == null ? null : v4.getString();
String escapeCharacter = v5 == null ? null : v5.getString();
Value v6 = getNullOrValue(session, args, values, 6);
String nullString = v6 == null ? null : v6.getString();
Value v7 = getNullOrValue(session, args, values, 7);
String lineSeparator = v7 == null ? null : v7.getString();
setCsvDelimiterEscape(csv, fieldSeparatorWrite, fieldDelimiter, escapeCharacter);
csv.setNullString(nullString);
if (lineSeparator != null) {
csv.setLineSeparator(lineSeparator);
}
}
try {
int rows = csv.write(conn, v0.getString(), v1.getString(), charset);
result = ValueInt.get(rows);
} catch (SQLException e) {
throw DbException.convert(e);
}
break;
}
case SET:
{
Variable var = (Variable) args[0];
session.setVariable(var.getName(), v1);
result = v1;
break;
}
case FILE_READ:
{
session.getUser().checkAdmin();
String fileName = v0.getString();
boolean blob = args.length == 1;
try {
long fileLength = FileUtils.size(fileName);
final InputStream in = FileUtils.newInputStream(fileName);
try {
if (blob) {
result = database.getLobStorage().createBlob(in, fileLength);
} else {
Reader reader;
if (v1 == ValueNull.INSTANCE) {
reader = new InputStreamReader(in);
} else {
reader = new InputStreamReader(in, v1.getString());
}
result = database.getLobStorage().createClob(reader, fileLength);
}
} finally {
IOUtils.closeSilently(in);
}
session.addTemporaryLob(result);
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
}
break;
}
case FILE_WRITE:
{
session.getUser().checkAdmin();
result = ValueNull.INSTANCE;
String fileName = v1.getString();
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
try (InputStream in = v0.getInputStream()) {
result = ValueLong.get(IOUtils.copyAndClose(in, fileOutputStream));
}
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
}
break;
}
case TRUNCATE_VALUE:
{
result = v0.convertPrecision(v1.getLong(), v2.getBoolean());
break;
}
case XMLTEXT:
if (v1 == null) {
result = ValueString.get(StringUtils.xmlText(v0.getString()), database.getMode().treatEmptyStringsAsNull);
} else {
result = ValueString.get(StringUtils.xmlText(v0.getString(), v1.getBoolean()), database.getMode().treatEmptyStringsAsNull);
}
break;
case REGEXP_LIKE:
{
String regexp = v1.getString();
String regexpMode = v2 == null || v2.getString() == null ? "" : v2.getString();
int flags = makeRegexpFlags(regexpMode);
try {
result = ValueBoolean.get(Pattern.compile(regexp, flags).matcher(v0.getString()).find());
} catch (PatternSyntaxException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
}
break;
}
case VALUES:
result = session.getVariable(args[0].getSchemaName() + "." + args[0].getTableName() + "." + args[0].getColumnName());
break;
case SIGNAL:
{
String sqlState = v0.getString();
if (sqlState.startsWith("00") || !SIGNAL_PATTERN.matcher(sqlState).matches()) {
throw DbException.getInvalidValueException("SQLSTATE", sqlState);
}
String msgText = v1.getString();
throw DbException.fromUser(sqlState, msgText);
}
default:
throw DbException.throwInternalError("type=" + info.type);
}
return result;
}
use of java.util.regex.PatternSyntaxException in project h2database by h2database.
the class CompareLike method initPattern.
private void initPattern(String p, Character escapeChar) {
if (compareMode.getName().equals(CompareMode.OFF) && !ignoreCase) {
fastCompare = true;
}
if (regexp) {
patternString = p;
try {
if (ignoreCase) {
patternRegexp = Pattern.compile(p, Pattern.CASE_INSENSITIVE);
} else {
patternRegexp = Pattern.compile(p);
}
} catch (PatternSyntaxException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, p);
}
return;
}
patternLength = 0;
if (p == null) {
patternTypes = null;
patternChars = null;
return;
}
int len = p.length();
patternChars = new char[len];
patternTypes = new int[len];
boolean lastAny = false;
for (int i = 0; i < len; i++) {
char c = p.charAt(i);
int type;
if (escapeChar != null && escapeChar == c) {
if (i >= len - 1) {
invalidPattern = true;
return;
}
c = p.charAt(++i);
type = MATCH;
lastAny = false;
} else if (c == '%') {
if (lastAny) {
continue;
}
type = ANY;
lastAny = true;
} else if (c == '_') {
type = ONE;
} else {
type = MATCH;
lastAny = false;
}
patternTypes[patternLength] = type;
patternChars[patternLength++] = c;
}
for (int i = 0; i < patternLength - 1; i++) {
if ((patternTypes[i] == ANY) && (patternTypes[i + 1] == ONE)) {
patternTypes[i] = ONE;
patternTypes[i + 1] = ANY;
}
}
patternString = new String(patternChars, 0, patternLength);
// Clear optimizations
shortcutToStartsWith = false;
shortcutToEndsWith = false;
shortcutToContains = false;
// optimizes the common case of LIKE 'foo%'
if (compareMode.getName().equals(CompareMode.OFF) && patternLength > 1) {
int maxMatch = 0;
while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
maxMatch++;
}
if (maxMatch == patternLength - 1 && patternTypes[patternLength - 1] == ANY) {
shortcutToStartsWith = true;
return;
}
}
// optimizes the common case of LIKE '%foo'
if (compareMode.getName().equals(CompareMode.OFF) && patternLength > 1) {
if (patternTypes[0] == ANY) {
int maxMatch = 1;
while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
maxMatch++;
}
if (maxMatch == patternLength) {
shortcutToEndsWith = true;
return;
}
}
}
// optimizes the common case of LIKE '%foo%'
if (compareMode.getName().equals(CompareMode.OFF) && patternLength > 2) {
if (patternTypes[0] == ANY) {
int maxMatch = 1;
while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
maxMatch++;
}
if (maxMatch == patternLength - 1 && patternTypes[patternLength - 1] == ANY) {
shortcutToContains = true;
}
}
}
}
use of java.util.regex.PatternSyntaxException in project cerberus-source by cerberustesting.
the class WebDriverService method selectRequestedOption.
private void selectRequestedOption(Select select, Identifier property, String element) throws CerberusEventException {
MessageEvent message;
try {
if (property.getIdentifier().equalsIgnoreCase("value")) {
select.selectByValue(property.getLocator());
} else if (property.getIdentifier().equalsIgnoreCase("label")) {
select.selectByVisibleText(property.getLocator());
} else if (property.getIdentifier().equalsIgnoreCase("index") && StringUtil.isInteger(property.getLocator())) {
select.selectByIndex(Integer.parseInt(property.getLocator()));
} else if (property.getIdentifier().equalsIgnoreCase("regexValue") || property.getIdentifier().equalsIgnoreCase("regexIndex") || property.getIdentifier().equalsIgnoreCase("regexLabel")) {
java.util.List<WebElement> list = select.getOptions();
if (property.getIdentifier().equalsIgnoreCase("regexValue")) {
for (WebElement option : list) {
String optionValue = option.getAttribute("value");
Pattern pattern = Pattern.compile(property.getLocator());
Matcher matcher = pattern.matcher(optionValue);
if (matcher.find()) {
select.selectByValue(optionValue);
}
}
} else if (property.getIdentifier().equalsIgnoreCase("regexLabel")) {
for (WebElement option : list) {
String optionLabel = option.getText();
Pattern pattern = Pattern.compile(property.getLocator());
Matcher matcher = pattern.matcher(optionLabel);
if (matcher.find()) {
select.selectByVisibleText(optionLabel);
}
}
} else if (property.getIdentifier().equalsIgnoreCase("regexIndex") && StringUtil.isInteger(property.getLocator())) {
for (WebElement option : list) {
Integer id = 0;
Pattern pattern = Pattern.compile(property.getLocator());
Matcher matcher = pattern.matcher(id.toString());
if (matcher.find()) {
select.selectByIndex(Integer.parseInt(property.getLocator()));
}
id++;
}
}
} else {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_SELECT_NO_IDENTIFIER);
message.setDescription(message.getDescription().replace("%IDENTIFIER%", property.getIdentifier()));
throw new CerberusEventException(message);
}
} catch (NoSuchElementException exception) {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_SELECT_NO_SUCH_VALUE);
message.setDescription(message.getDescription().replace("%ELEMENT%", element));
message.setDescription(message.getDescription().replace("%DATA%", property.getIdentifier() + "=" + property.getLocator()));
throw new CerberusEventException(message);
} catch (WebDriverException exception) {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_SELENIUM_CONNECTIVITY);
message.setDescription(message.getDescription().replace("%ERROR%", exception.getMessage().split("\n")[0]));
LOG.warn(exception.toString());
throw new CerberusEventException(message);
} catch (PatternSyntaxException e) {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_SELECT_REGEX_INVALIDPATERN);
message.setDescription(message.getDescription().replace("%PATERN%", property.getLocator()));
message.setDescription(message.getDescription().replace("%ERROR%", e.getMessage()));
throw new CerberusEventException(message);
}
}
use of java.util.regex.PatternSyntaxException in project cerberus-source by cerberustesting.
the class ControlService method VerifyRegexInElement.
private MessageEvent VerifyRegexInElement(TestCaseExecution tCExecution, String path, String regex) {
LOG.debug("Control : verifyRegexInElement on : " + path + " element against value : " + regex);
MessageEvent mes;
String pathContent = null;
try {
Identifier identifier = identifierService.convertStringToIdentifier(path);
String applicationType = tCExecution.getApplicationObj().getType();
// Get value from the path element according to the application type
if (Application.TYPE_GUI.equalsIgnoreCase(applicationType) || Application.TYPE_APK.equalsIgnoreCase(applicationType) || Application.TYPE_IPA.equalsIgnoreCase(applicationType)) {
pathContent = this.webdriverService.getValueFromHTML(tCExecution.getSession(), identifier);
} else if (Application.TYPE_SRV.equalsIgnoreCase(applicationType)) {
if (tCExecution.getLastServiceCalled() != null) {
String responseBody = tCExecution.getLastServiceCalled().getResponseHTTPBody();
switch(tCExecution.getLastServiceCalled().getResponseHTTPBodyContentType()) {
case AppService.RESPONSEHTTPBODYCONTENTTYPE_XML:
if (!xmlUnitService.isElementPresent(responseBody, path)) {
mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_TEXTINELEMENT_NO_SUCH_ELEMENT);
mes.setDescription(mes.getDescription().replace("%ELEMENT%", path));
return mes;
}
String newPath = StringUtil.addSuffixIfNotAlready(path, "/text()");
pathContent = xmlUnitService.getFromXml(responseBody, newPath);
break;
case AppService.RESPONSEHTTPBODYCONTENTTYPE_JSON:
try {
pathContent = jsonService.getFromJson(responseBody, null, path);
} catch (Exception ex) {
mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_GENERIC);
mes.setDescription(mes.getDescription().replace("%ERROR%", ex.toString()));
return mes;
}
break;
default:
mes = new MessageEvent(MessageEventEnum.CONTROL_NOTEXECUTED_NOTSUPPORTED_FOR_MESSAGETYPE);
mes.setDescription(mes.getDescription().replace("%TYPE%", tCExecution.getLastServiceCalled().getResponseHTTPBodyContentType()));
mes.setDescription(mes.getDescription().replace("%CONTROL%", "verifyRegexInElement"));
return mes;
}
// TODO Give the actual element found into the description.
} else {
mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_NOOBJECTINMEMORY);
return mes;
}
} else {
mes = new MessageEvent(MessageEventEnum.CONTROL_NOTEXECUTED_NOTSUPPORTED_FOR_APPLICATION);
mes.setDescription(mes.getDescription().replace("%CONTROL%", "verifyRegexInElement"));
mes.setDescription(mes.getDescription().replace("%APPLICATIONTYPE%", tCExecution.getApplicationObj().getType()));
return mes;
}
LOG.debug("Control : verifyRegexInElement element : " + path + " has value : " + StringUtil.sanitize(pathContent));
if (path != null && pathContent != null) {
try {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(pathContent);
if (matcher.find()) {
mes = new MessageEvent(MessageEventEnum.CONTROL_SUCCESS_REGEXINELEMENT);
mes.setDescription(mes.getDescription().replace("%STRING1%", path));
mes.setDescription(mes.getDescription().replace("%STRING2%", StringUtil.sanitize(pathContent)));
mes.setDescription(mes.getDescription().replace("%STRING3%", regex));
return mes;
} else {
mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_REGEXINELEMENT);
mes.setDescription(mes.getDescription().replace("%STRING1%", path));
mes.setDescription(mes.getDescription().replace("%STRING2%", StringUtil.sanitize(pathContent)));
mes.setDescription(mes.getDescription().replace("%STRING3%", regex));
return mes;
}
} catch (PatternSyntaxException e) {
mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_REGEXINELEMENT_INVALIDPATERN);
mes.setDescription(mes.getDescription().replace("%PATERN%", regex));
mes.setDescription(mes.getDescription().replace("%ERROR%", e.getMessage()));
return mes;
}
} else if (pathContent != null) {
mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_REGEXINELEMENT_NULL);
return mes;
} else {
mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_REGEXINELEMENT_NO_SUCH_ELEMENT);
mes.setDescription(mes.getDescription().replace("%ELEMENT%", path));
return mes;
}
} catch (NoSuchElementException exception) {
LOG.debug(exception.toString());
mes = new MessageEvent(MessageEventEnum.CONTROL_FAILED_REGEXINELEMENT_NO_SUCH_ELEMENT);
mes.setDescription(mes.getDescription().replace("%ELEMENT%", path));
return mes;
} catch (WebDriverException exception) {
return parseWebDriverException(exception);
}
}
Aggregations