jpa containing query with list - java

I have a table Called Media that has a column "tagList" of type List. I want to search media based on list of input tag.
I need a method like this.
List<Media> findByTagListContaining(<List> inputTagList);
This gives error but
List<Media> findByTagListContaining(String inputTag);
works fine. How to make first one works. I need partial matching as well for example if any row has tagList ["mentos","bollywood","comedy"]
and inputTagList is ["men","boll"] that row should come in result.

Hello, You can try this.
{
List<String> inputTagList = new ArrayList<String>();
inputTagList.add("men");
inputTagList.add("boll");
findByTagListContaining(inputTagList);
}
call your find By Tag List method
List<Media> findByTagListContaining(List<String> inputTagList){
String inputTagString = "[";
for(String strTemp : inputTagList){
//here create you own pattern matching code. Ex:
inputTagString+= "'" + strTemp + "%'" + ",";
}
inputTagString+="%]";
//And your inputTagString is ready to match you element ["mentos","bollywood","comedy"]
}

Related

Pull string from RDF node

Im trying to get the data in a more readable format when using a SPARQL query with Jena, however I have no idea how to extract the data in a proper way.
As for now, the output is:
"http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#SaucelitoCanyon"
Where instead would like to just have the "SaucelitoCanyon" as a output.
public JenaQuery() {
String wineRegion = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
+ "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n"
+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
+ "PREFIX wine:<http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#>\n"
+ "SELECT ?region ?winery \n"
+ "WHERE {?wine wine:locatedIn ?region . \n"
+ "?region wine:locatedIn wine:CaliforniaRegion . \n"
+ "?wine wine:hasMaker ?winery}";
String inputFileName = "wine.rdf";
// create an empty model
Model model = ModelFactory.createDefaultModel();
// use the FileManager to find the input file
InputStream in;
in = FileManager.get().open(inputFileName);
if (in == null) {
throw new IllegalArgumentException(
"File: " + inputFileName + " not found");
}
// read the RDF/XML file
model.read(in, null);
try (QueryExecution qexec = QueryExecutionFactory.create(wineRegion, model)) {
ResultSet results = qexec.execSelect();
while (results.hasNext()) {
QuerySolution row = results.next();
RDFNode winery = row.get("winery");
System.out.println(winery);
}
qexec.close();
}
}
Since you've already got the prefix in the SPARQL query, you can use the strafter and str functions to convert the URIs to strings and take the suffix after the prefix. In the following, I've used values ?winery { ... } to bind ?winery to a particular URI, but your query already takes care of that. The important part is the bind afterward that takes care of the string processing.
PREFIX wine: <http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#>
SELECT ?winery ?localname
WHERE {
values ?winery { wine:SomeWinery }
bind( strafter(str(?winery),str(wine:)) as ?localname )
}
winery localname
<http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#SomeWinery> "SomeWinery"
That said, in well structured ontologies, individuals will often have an rdfs:label that should provide a string label for an individual. When it's available, you might consider simply retrieving that value. E.g.,
SELECT ?winery ?name
WHERE {
#-- ...
?winery rdfs:label ?name
}
This was previously described in my answer to retrieving the class name of a specific subclass in owl, but that question didn't involve Jena, so it's not quite a duplicate, even though the same SPARQL-based solution works.
Note that in Jena you have two nice Java sources for nice qName conversions: Prologue and PrefixMapping. Your Model is a PrefixMapping and your Query (if you compiled it) is a Prologue. Both of these objects have a #shortForm(String uri) method that you can use to get a shortened form of a URI without modifying your query.
If your model has prefixes defined in it, you can use PrefixMapping#shortForm(String) as follows (pseudocode):
final Model m = // TODO
final String shortForm = m.shortForm(winery.asResource().getURI());
If you compile your Query using QueryFactory, then you can use query-specific prefixes in Prologue#shortForm(String) as follows (pseudocode):
final Query q = QueryFactory.create(/* TODO */);
final String shortForm = q.shortForm(winery.asResource().getURI());
It's then worth knowing that this will give you a name of the form wine:SaucelitoCanyon (if the wine: prefix is defined, otherwise it will give you http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#SaucelitoCanyon). You would still need to split the resulting string to get just the local name which may be a little verbose:
final String longName = winery.asResource().getURI();
final String localName;
if( !shortForm.equals(longName) ) {
localName = shortForm.split(":")[1];
}
else {
throw new IllegalStateException("could not resolve prefix for "+longName);
}
This provides you a guarantee that you are using the local name associated with some prefix in your model or your query.
You can use the "getLocalName" function in Jena. That will get you the local name of the resource, which is what you seem to be looking for:
QuerySolution row = results.next();
RDFNode winery = row.get("winery");
String r = winery.asNode().getLocalName();
System.out.println(r);
Alternatively you can get the node as a resource directly, which saves you one line of code:
String r = row.getResource("winery").getLocalName();
Edit: as stated in the comments below, this answer will only be valid if your prefix "wine" is as you have declared it in your code. Otherwise the results may not be as desired.

Parse a plain text into a Java Object

I´m parsing a plain text and trying to convert into an Object.
The text looks like(and i can´t change the format):
"N001";"2014-08-12-07.11.37.352000";" ";"some#email.com ";4847 ;"street";"NAME SURNAME ";26 ;"CALIFORNIA ";21
and The Object to convert:
String index;
String timestamp;
String mail;
Integer zipCode
...
I´ve tried with:
StringTokenizer st1 = new StringTokenizer(N001\";\"2014-08-12-07.11.37.352000\";\" \";\"some#email.com \";4847 ;\"street\";\"NAME SURNAME \";26 ;\"CALIFORNIA \";21);
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken(";").replaceAll("\"",""));
}
And the output is the correct one, i´ve thinking to have a counter and hardcoding with a case bucle and set the field deppending the counter, but the problem is that I have 40 fields...
Some idea?
Thanks a lot!
String line = "N001";"2014-08-12-07.11.37.352000";" ";"some#email.com ";4847 ;"street";"NAME SURNAME ";26 ;"CALIFORNIA ";21
StringTokenizer st1 = new StringTokenizer(line, ";");
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken().replaceAll("\"",""));
}
Or you can use split method and directly get a array of values using the delimiter ;
String []values = line.split(";");
then iterate through the array and get and cast the values they way you want
Regardless of the way you are parsing the file, you somehow need to define the mapping of column-to-field (and how to parse the text).
if this is a CVS file, you could use a library like super-csv. All you need to do is write a mapping definition.
I would first split your input String based on the semi-colon separator, then clean up the values.
For instance:
String input = "\"N001\";\"2014-08-12-07.11.37.352000\";\" " +
"\";\"some#email.com " +
"\";4847 ;\"street\";\"NAME " +
"SURNAME \";26 ;\"CALIFORNIA " +
"\";21 ";
// raw split
String[] split = input.split(";");
System.out.printf("Raw: %n%s%n", Arrays.toString(split));
// cleaning up whitespace and double quotes
ArrayList<String> cleanValues = new ArrayList<String>();
for (String s: split) {
String clean = s.replaceAll("[\\s\"]", "");
if (!clean.isEmpty()) {
cleanValues.add(clean);
}
}
System.out.printf("Clean: %n%s%n", cleanValues);
Output
Raw:
["N001", "2014-08-12-07.11.37.352000", " ", "some#email.com ", 4847 , "street", "NAME SURNAME ", 26 , "CALIFORNIA ", 21 ]
Clean:
[N001, 2014-08-12-07.11.37.352000, some#email.com, 4847, street, NAMESURNAME, 26, CALIFORNIA, 21]
Note
In order to map the values to your variables you will need to know their index in advance, and it will have to be consistent.
Then you can use the get(int i) method to retrieve them from your List - e.g. cleanValues.get(2) will get you the e-mail, etc.
Note (2)
If you do not know the indices in advance or they may vary, then you are in trouble.
You can of course try to get those indices by using regular expressions but I suspect you might end up complicating your life quite a bit.
you can use Java Reflection to automate your process.
Iterate over the fields
Field[] fields = dummyRow.getClass().getFields();
and set your values
SomeClass object = construct.newInstance();
field.set(object , value);

How to use arraylist as a parameter in IN clause of SQL

I have a array list of integers . I want to use this list in the IN clause of SQL query. I tried to do the below, but i know it wont work. Can someone suggest a better way .
List<Integer> **plcList** = new ArrayList<Integer>();
String finalQuery = "
select plc,direction,ROUND(AVG(CAST(speed as float)),2) as speed,COUNT(plc) as count,time_id
from processed
WHERE plc IN " + " " + "(**plcList**)"+ " " + "
group by plc, direction, time_id";
I suggest to have a look on this one: PreparedStatement IN clause alternatives?
And this page: http://www.javaranch.com/journal/200510/Journal200510.jsp#a2
In your case, you could just loop to build the integer list as Abdul mentioned above.
I am not a Java prof. but I would suggest you to loop throug your list and make string with comma seperated values. Like in PHP we do this with implode function. And hence your final string would be something like this
1,2,3,4,5
and then use it in your sql query
I am not sure about my code but try this as I am not a Java programmar (
make the necessary changes if any syntax error)
String intlist = "";
for (String temp : list)
{
intlist += ","+temp;
}
String Str = new String(intlist);
String sqlstring = Str.substring(1);
Try this..
List<Integer> myList = new ArrayList<Integer>();
StringBuilder builder = new StringBuilder();
// length of the list
int locSize = myList.size();
Object[] args = new Object[locSize];
for( int i = 0; i < locSize; i++ ) {
builder.append(" ?, " );
args[i]= myList.get(i);
}
You can then use this in your query, something like this.
....WHERE plc IN ("+ builder.toString() +") group by plc, direction, time_id";
Refer passing object[] to sql query for similar question.

How can I split these two object strings so I can put into database

while (pCur.moveToNext()) {
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String pon = name ;
System.out.println("phone" + phone + name);
listItems.add(pon + phone) ;
adapter.notifyDataSetChanged();
}
I am getting the phone number and name from a persons contacts. i have to stringify each object to pass it along to my list view (multiple check). now i select multiple choices i want to again separate the two (the contact name and the phone number associated with it) so i can put them into separate columns in my database. how can i split the two once it is a string in an array adapter?
how can i split these two object strings so i can put into database
Well. Probably in your ListView you have your data formatted as(also you can ensure specific format for easier work in a future).
John 23459395
Now when you select items from your ListView, you can access to them and save them into temporary List. Then each item in List you can split with split() method.
List<String> selectedItems = new ArrayList<String>();
// selection from ListView
String[] temp;
for (String s: selectedItems) {
temp = s.split(" "); // or other regex based on format of source
// insert into db
}
But this depends on format of source.
Update:
Your actual approach you can improve. Look, now you are fetching name and phoneNumber from Cursor
I recommend you to create own class for instance called User that will have properties name, phonenumber, etc. Then you create ArrayList<User>() and set it as datasource to your ListAdapter.
I don't now if you are using own implemented subclass of Adapter or not. If not, you need to override toString() method in your User class to get proper string representation of User.
Use a string inbbetween name and phone and use that string to split it again.
Code Sample
while (pCur.moveToNext()) {
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String pon = name ;
System.out.println("phone" + phone + name);
/* Following code changed here...Hoping that "!##$" doesnt exists in pon or phone data. Or you can replace it with some other string which will not come in these objects. */
listItems.add(pon +"!##$"+ phone) ;
adapter.notifyDataSetChanged();
}
How to retrive and split: Sample method
ArrayList<String> listItems = new ArrayList<String>();
listItems.add("Joseph!##$325625123");
listItems.add("John!##$5214252142");
for (String strData : listItems)
{
int index = strData.indexOf("!##$");
if (index > -1)
{
String name = strData.substring(0, index);
String phone = strData.substring(index + 4);// 4 is the length of the substitute string
System.out.println(name + ", " + phone);
// Code to insert name and phone database
}
}
Result of above method will be as below
Joseph, 325625123
John, 5214252142

Inserting multiple values in one row

I need to insert data from my parsed XML file to mySQL table. Problem is that I have few attributes and don't know how to insert them in one row. I tried with updateString but it writes only last attribute.
Here is example from XML file:
<Tr rn=\"999999999999999\" vr=\"T\" sSpre=\"S\" reg=\"P\" dSpre=\"2010-09-30\" dOdprt=\"2000-01-01\" iban=\"SI56\" eno=\"R\" vir=\"R\" maticnaPps=\"00000000\"><Imetnik davcna=\"0000000\" matSub=\"0000000\" drz=\"705\"><PopolnoIme>xxx</PopolnoIme><KratkoIme>xxx</KratkoIme><Naslov sifTipNaslova=\"01\" sifObcina=\"039\" sifPosta=\"1303\" sifUlica=\"0000\" sifNaselje=\"059\" stHisna=\"027\" sifHsmid=\"11694551\"><Obcina>xxx</Obcina><Posta>xxx</Posta><Ulica>xxx</Ulica><Naselje>xxx</Naselje></Naslov></Imetnik></Tr>
This is scratch from my java program that I used for writing in mySQL table.
if (myWorkLine.substring(0,4).equals(Tr)) {
uprs.afterLast();
uprs.moveToInsertRow();
if (myWorkLine.contains(Tr)) {
myWorkLine = myWorkLine.substring(myWorkLine.indexOf(Tr)+4);
while (!myWorkLine.substring(0,1).equals("<")) {
myTag = myWorkLine.substring(0,myWorkLine.indexOf("="));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("=")+2);
myValue = myWorkLine.substring(0,myWorkLine.indexOf("\""));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("\"")+2);
uprs.updateString("Tr",myTag + " " + myValue);
if (myWorkLine.substring(0,myWorkLine.indexOf("\">")).indexOf(">") > 0)
break;
}
}
So once again, I need that in MySQL table column Tr contains attributes rn value, vr value, sSpre value,...
Thanks in advance.
P.S.: Please don't ask why I'm parsing XML file by this method, I had to do it that way. :)
Your code will repeatedly replace the "Tr" column with your concatenation of tag + " " + value so it'll only be the last one that goes in. Don't you perhaps want the different tags to go in different columns? Or maybe you need to continue concatenating and only call updateString at the end.
Could you post the desired table row for the given XML? That should help in determining what you are trying to achieve.
For example, if you just want to append them:
StringBuffer tr = new StringBuffer();
while (!myWorkLine.substring(0,1).equals("<")) {
myTag = myWorkLine.substring(0,myWorkLine.indexOf("="));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("=")+2);
myValue = myWorkLine.substring(0,myWorkLine.indexOf("\""));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("\"")+2);
tr.append(myTag + " " + myValue).append(",");
if (myWorkLine.substring(0,myWorkLine.indexOf("\">")).indexOf(">") > 0)
break;
}
if (tr.length() > 0) {
tr.deleteCharAt(tr.length()-1); // get rid of last comma
}
uprs.updateString("Tr",tr.toString());

Categories