Hibernate Regex - regex

I am trying to build an API which can search by HQL regex keywords,
EDITED:
The best way to perform regex search in HQL is to use criteria, Restrictions.like() or Restrictions.ilike().
public static List<Object> createQueryAnd(Criteria cri,
ArrayList<Parameters> list) {
for (Parameters p : list) {
String value = (String) p.value;
if (value.contains("*")) {
value = value.replace("*", "%");
} else {
value += "%";
}
Criterion c1 = Restrictions.ilike(p.property, value);
cri.add(c1);
}
return cri.list();
}
Hope this helps someone

HQL does not have regular expressions. If you want to use database provider specific constructs for regular expression, Dialect should be modified. This question contains discussion about how to do that with Oracle database.

Related

Painless - Is it possible to have an Arraylist that contains patterns

I have a list of pattern and I want to loop through it.
I was wondering if it's possible to create a list containing all theses patterns.
Here is an example of what I want to accomplish :
def logs = new ArrayList();
def pattern_list = new ArrayList();
pattern_list.add("/^.*failed.*$/");
pattern_list.add("/^.*disconnect.*$/");
for (log in logs)
{
for (pattern in pattern_list)
{
if (log =~ pattern)
{
// do things
}
}
}
EDIT: I found the solution, remove double quote
pattern_list.add(/^.*failed.*$/);
pattern_list.add(/^.*disconnect.*$/);

Testing criteria creation in a Grails service

I have a Grails service that creates a criteria query with optional parameters like this:
List<Car> search(String make = "%", String model = "%", Integer year = null) {
def c = Car.createCriteria()
return c.list() {
if(make) {
like("make", make)
}
if(model) {
like("model", model)
}
if(year) {
eq("year", year)
}
}
}
(Also, is this the idiomatic way to do this in grails? I'm quite new to the framework and I'm trying to find the right way to do things)
I'd like to test that the proper criteria filters are set according to the values of the parameters of the search method but I'm having no success.
I tried some variations of this:
#TestFor(CarService)
#Mock(Car)
class CarServiceSpec extends Specification {
def car = Mock(Car)
void "empty filters"() {
when: service.search()
then:
with(car.createCriteria()) {
0 * like(*_)
0 * eq(*_)
}
}
}
But I can't seem to find a way to do assertions about the interactions between the CarService and the criteria object.
What am I missing?
The Grails Where query instead of the Criteria query seems to be better choice for an idiomatic way to do this in Grails:
Gorm Where Query

From Hibernate criteria to JPA criteria or QueryDSL

I'm thinking of porting an Hibernate criteria from an old DAO layer to either a JPA criteria or a QueryDSL one.
Since I've never used any of these two, I wonder which API I should use...
Here is the Hibernate criteria:
public Page<ElearningSubscription> findWithPatternLike(String searchPattern, int pageNumber, int pageSize) {
Criteria criteria = getSession().createCriteria(getPersistentClass(), "es");
criteria.createAlias(DB_TABLE_USER_ACCOUNT, "u", CriteriaSpecification.INNER_JOIN);
Conjunction conjunction = Restrictions.conjunction();
String pattern = "%" + searchPattern + "%";
Criterion firstname = Restrictions.ilike("u.firstname", pattern);
Criterion lastname = Restrictions.ilike("u.lastname", pattern);
Criterion email = Restrictions.ilike("u.email", pattern);
Disjunction disjunction = Restrictions.disjunction();
disjunction.add(firstname).add(lastname).add(email);
if (searchPattern.contains(" ")) {
String[] pieces = searchPattern.split(" ");
if (pieces[0] != null) {
Criterion firstnameBis = Restrictions.ilike("u.firstname", pieces[0]);
disjunction.add(firstnameBis);
}
if (pieces[1] != null) {
Criterion lastnameBis = Restrictions.ilike("u.lastname", pieces[1]);
disjunction.add(lastnameBis);
}
}
conjunction.add(disjunction);
OrderList orderList = new OrderList().add(Order.asc("u.firstname")).add(Order.asc("u.lastname")).add(Order.asc("u.email")).add(Order.desc("es.subscriptionDate"));
Page<ElearningSubscription> page = getPage(pageNumber, pageSize, criteria, orderList);
return page;
}
Thanks for any guidance.
Kind Regards,
Stephane Eybert
JPA 2 Criteria is an official standard, but Querydsl is superior in the following aspects
easier and less verbose syntax
customizable code generation
supports multiple backends
This answer is biased, since I am involved in the Querydsl development.

How to efficiently convert DataSet.Tables to List<DataTable>?

I see many posts about converting the table(s) in a DataSet to a list of DataRows or other row data but I was unable to find anything about this question. This is what I came up with using .Net 3.0:
public static List<DataTable> DataSetToList(DataSet ds)
{
List<DataTable> result = new List<DataTable>();
foreach (DataTable dtbl in ds.Tables)
{
result.Add(dtbl);
}
return result;
}
Is there a better way, excluding an extension method?
Thanks
Based on Why LINQ casting with a Data.DataTableCollection this will work;
List<DataTable> result = new List<DataTable>(ds.Tables.Cast<DataTable>())
IEnumerable<DataTable> sequence = dt.AsEnumerable();
or
List<DataTable> list = dt.AsEnumerable().ToList();

Json regex deserialization with JSON.Net

I'm trying to read the following example json from a text file into a string using the JSON.Net parsing library.
Content of C:\temp\regeLib.json
{
"Regular Expressions Library":
{
"SampleRegex":"^(?<FIELD1>\d+)_(?<FIELD2>\d+)_(?<FIELD3>[\w\&-]+)_(?<FIELD4>\w+).txt$"
}
}
Example code to try and parse:
Newtonsoft.Json.Converters.RegexConverter rConv = new Newtonsoft.Json.Converters.RegexConverter();
using (StreamReader reader = File.OpenText(libPath))
{
string foo = reader.ReadToEnd();
JObject jo = JObject.Parse(foo);//<--ERROR
//How to use RegexConverter to parse??
Newtonsoft.Json.JsonTextReader jtr = new Newtonsoft.Json.JsonTextReader(reader);
JObject test = rConv.ReadJson(jtr);//<--Not sure what parameters to provide
string sampleRegex = test.ToString();
}
It seems I need to use the converter, I know the code above is wrong, but I can't find any examples that describe how / if this can be done. Is it possible to read a regular expression token from a text file to a string using JSON.Net? Any help is appreciated.
UPDATE:
Played with it more and figured out I had to escape the character classes, once I made the correction below I was able to parse to a JObject and use LINQ to query for the regex pattern.
Corrected content C:\temp\regeLib.json
{
"Regular Expressions Library":
{
"SampleRegex":"^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
}
}
Corrected code
using (StreamReader reader = File.OpenText(libPath))
{
string content = reader.ReadToEnd().Trim();
JObject regexLib = JObject.Parse(content);
string sampleRegex = regexLib["Regular Expressions Library"]["SampleRegex"].ToString();
//Which then lets me do the following...
Regex rSampleRegex = new Regex(sampleRegex);
foreach (string sampleFilePath in Directory.GetFiles(dirSampleFiles, "*"))
{
filename = Path.GetFileName(sampleFilePath);
if (rSampleRegex.IsMatch(filename))
{
//Do stuff...
}
}
}
Not sure if this is the best approach, but it seems to work for my case.
i don't understand why you have to store such a small regex in a json file, are you going to expand the regex in the future?
if so, rather than doing this
JObject regexLib = JObject.Parse(content);
string sampleRegex = regexLib["Regular Expressions Library"]["SampleRegex"].ToString();
Consider using json2csharp to make classes, at least it's strongly-typed and make it more maintainable.
I think a more appropriate json would look like this (assumptions):
{
"Regular Expressions Library": [
{
"SampleRegex": "^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
},
{
"SampleRegex2": "^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
}
]
}
It would make more sense this way to store a regex in a "settings" file