I need help creating a predicate to use with Spring data and querydsl. I'm in the process of converting Daos to Repositorys. And I came across one that has a dynamic query in it. I can create a predicate from a list, but I'm lost at how to create a a dynamic predicate from a map. Here is the code from the DaoImpl that I'm converting from:
public Set<String> getDocumentsByDocumentAssociation(Map.Entry<String,String>[] associations) {
String queryStr = "SELECT da FROM DocumentExternalAssocEntity as da WHERE";
StringBuilder sb = new StringBuilder(queryStr);
//loop through inputs. for first loop, skip appending the OR statements. Append OR for all others
for ( int i = 0; i < associations.length; i++ ){
if ( i > 0 ) {
sb.append(" OR");
}
String whereString = " (da.associationtype = :docAssocType" + i + " AND da.associationvalue = :docAssocValue" + i + ")";
sb.append(whereString);
}
//query when previous loop is done appending
final Query query = em.createQuery(sb.toString());
for( int i = 0; i < associations.length; i++ ) {
query.setParameter("docAssocType" + i, associations[i].getKey());
query.setParameter("docAssocValue" + i, associations[i].getValue());
}
And here is the relevant generated class:
private static final long serialVersionUID = 1971644089L;
public static final QDocumentExternalAssocEntity documentExternalAssocEntity = new QDocumentExternalAssocEntity("documentExternalAssocEntity");
public final StringPath associationtype = createString("associationtype");
public final StringPath associationvalue = createString("associationvalue");
Thanks, and let me know if you need any additional info
This should do it:
BooleanExpression expr = null;
for ( int i = 0; i < associations.length; i++ ){
BooleanExpression innerExpr =
documentExternalAssocEntity.associationtype.eq(associations[i].getKey())
.and(documentExternalAssocEntity.associationvalue.eq(associations[i].getValue()))
if (expr == null) {
expr = innerExpr;
} else {
expr = expr.or(innerExpr);
}
}
Related
I try to print a query through the java console but nothing comes out. this is my code someone could help me.
I'm new to OrientDB and I'm just learning.
The query I need is to know the shortest path between two nodes and print this query on the Java console. It does not give me any errors but nothing comes out.
public class Graph {
private static final String DB_PATH = "C:/OrientDataBase/shortest_path";
static OrientGraphNoTx DBGraph;
static OrientGraphFactory factory;
public static void main(String[] args) {
factory = new OrientGraphFactory("plocal:"+DB_PATH);
DBGraph = factory.getNoTx();
HashMap<String, Vertex> nodes = new HashMap<String, Vertex>();
for(int i = 0; i <= 1000; i++)
{
Vertex v = DBGraph.addVertex("class:V");
v.setProperty("vertexID", i+"");
nodes.put(i+"", v);
}
try(BufferedReader br = new BufferedReader(new FileReader("C:/OrientDataBase/sp1.csv"))) {
int i=0;
for(String line; (line = br.readLine()) !=null ; ) {
if(i==0){
i++;
}
else{
String[] vertices = line.split(",");
String vertex1 = vertices[0];
String vertex2 = vertices[1];
String weight= vertices[2];
vertex2 = vertex2.replaceAll(" ", "");
Vertex v1 = nodes.get(vertex1);
Vertex v2 = nodes.get(vertex2);
Edge eLives = DBGraph.addEdge(null, v1, v2, "belongs");
eLives.setProperty("weight", weight);
System.out.println(v1+","+v2+","+weight);
String query = "select expand(shortestPath) from (select shortestPath(#10:0,#10:2,BOTH))";
Iterable<OrientVertex> res = DBGraph.command(new OCommandSQL(query)).execute();
while(res.iterator().hasNext()){
OrientVertex v = res.iterator().next();
System.out.println("rid: "+v.getId().toString()+"\tn:"+v.getProperty("n"));
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
I tried your code and you have to put the ticks when you do the query so, it becomes:
String query = "select expand(shortestPath) from (select shortestPath(#10:0,#10:2,'BOTH'))";
I used this csv file.
Hope it helps.
Regards
How I can do this in Entity Framework?
sSQL = "SELECT CategoryName FROM CategorySetup";
if (Conn.State == ConnectionState.Closed) { Conn.Open(); }
cmd = new SqlCommand(sSQL, Conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
btn_Chicken.Text = dt.Rows[0]["CategoryName"].ToString();
btn_Beef.Text = dt.Rows[1]["CategoryName"].ToString();
btn_Rice.Text = dt.Rows[2]["CategoryName"].ToString();
btn_Drink.Text = dt.Rows[3]["CategoryName"].ToString();
How I can do same thing in Entity Framework 5.0? If anybody knows, please tell me I'm searching it on google but cant find it, I'm new to ASP.NET MVC and Entity Framework
Once you have your EF context set up, fetching the data per se is simple:
List<CategorySetup> listOfCat = yourDbContext.CategorySetup;
But the main question is: how do you know which of those objects you got back from the database table corresponds to the button in your GUI?? Do you have a column in your database table to order your data by? So that you always now row #0 is for btn_Chicken, row #1 is for btn_Beef ? Or is there a column on the CategorySetup table to allows you to find out which CategorySetup object to use for which button?
POS_EF_Project.DataBase_Create.POS_Context db = new POS_EF_Project.DataBase_Create.POS_Context();
Button[] buttonArray = new Button[9];
public frmTesting()
{
InitializeComponent();
}
// Display Function
public void Display(int i)
{
string index = buttonArray[i].Tag.ToString();
var itm = db.ItemSetups.Where(c => c.CatagoryCode == index).OrderBy(c => c.ItemName);
int iCounter = 0;
foreach (ItemSetup t in itm)
{
fp_Items.Sheets[0].Rows.Count = iCounter + 1;
fp_Items.Sheets[0].Cells[iCounter, 0].Text = t.ItemCode;
fp_Items.Sheets[0].Cells[iCounter, 1].Text = t.ItemName;
fp_Items.Sheets[0].Cells[iCounter, 2].Text = t.Price.ToString();
iCounter++;
}
}
private void btn_Start_Click(object sender, EventArgs e)
{
var cat = db.Categorys.ToList();
int horizotal = 6;
int vertical = 96;
for (int i = 0; i < buttonArray.Length; i++)
{
int index = i;
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(168, 40);
buttonArray[i].Location = new Point(horizotal, vertical);
buttonArray[i].TextAlign = ContentAlignment.MiddleLeft;
buttonArray[i].Text = cat[i].CatagoryName;
buttonArray[i].Tag = cat[i].CategoryCode;
buttonArray[i].ImageAlign = ContentAlignment.MiddleRight;
buttonArray[i].Image = (Image)Properties.Resources.ResourceManager.GetObject("Basket");
if ((i + 1) % 9 == 0) horizotal = 6;
else vertical += 42;
buttonArray[i].Click += (sender1, ex) => this.Display(index);
this.Controls.Add(buttonArray[i]);
}
}
}
}
I have a JPopUpMenu with several JCheckBoxMenuItem's on it.
I also have a properties files (config.properties) where I put a parameter which save every JCheckBoxMenuItem the user has checked on this JPopUpMenu , when i close the application.
So this file is like :
config.properties :
listeFiltres =Autres,Afrique du sud,Algérie
What I would like to do is , on the start of my application, to setSelected every item that is saved in my properties parameter.
For exemple, if "Afrique,Algérie,Allemagne" are stored in my parameter listeFiltres in config.properties, I want these 3 JCheckBoxMenuItem to be checked at the start of my application.
The problem is that I only know the setSelected method which allows to select an item with a specific index(like 2), but here I need to select an item with a specific name (like "Afrique"), so this method isn't appropriate for me.
Here's the code of my JPopUpMenu :
MainVue.java:
public class MainVue extends JFrame implements ActionListener {
private static final JScrollPopupMenu menuProduit = new JScrollPopupMenu();
private static final JScrollPopupMenu menuPays = new JScrollPopupMenu();
private static List<String> listeFiltres = new ArrayList<String>();
private String listeDeFiltres;
private String[] tableauFiltrePermanent;
private String listeFiltrePermanent;
private String[] tableauPays = { "Autres", "Afrique du sud", "Algérie", "Allemagne", "Arabie Saoudite", "Argentine",
"Australie", "Bangladesh", "Belgique", "Brésil", "Bulgarie", "Canada", "Chine", "Corée du sud", "Egypte",
"Emirats-Arabes Unis", "Espagne", "Etats-Unis", "Ethiopie", "Europe", "France", "Hongrie", "Inde",
"Indonésie", "Irak", "Iran", "Israél", "Italie", "Japon", "Jordanie", "Kazakhstan", "Koweit", "Liban",
"Libye", "Malaisie", "Maroc", "Mexique", "Monde", "Oman", "Pakistan", "Pays-Bas", "Philippines", "Poligne",
"Portugal", "Qatar", "République tchéque", "Roumanie", "Russie", "Taïwan", "Tunisie", "Turquie",
"Ukraine" };
private String[] tableauProduit = { "Blé", "Colza", "Mais", "Orge", "Orge de Brasserie", "Palme", "Soja",
"Tournesol", "Tourteaux De Colza", "Tourteaux de Soja", "Huile de Soja", "Huile De Colza" };
private List<JCheckBoxMenuItem> listJCBProduit = new ArrayList<JCheckBoxMenuItem>();
private List<JCheckBoxMenuItem> listJCBPays = new ArrayList<JCheckBoxMenuItem>();
public static PropertiesConfiguration prop;
public MainVue(Modele modele, Controleur controleur) throws ClassNotFoundException, SQLException, IOException {
prop = new PropertiesConfiguration("config.properties");
for (int i = 0; i < tableauProduit.length; i++) {
listJCBProduit.add(new JCheckBoxMenuItem(tableauProduit[i]));
}
for (int j = 0; j < listJCBProduit.size(); j++) {
JCheckBoxMenuItem produitActuel = listJCBProduit.get(j);
menuProduit.add(produitActuel);
produitActuel.addActionListener(new OpenAction(menuProduit, boutonProduit));
}
for (int i = 0; i < tableauPays.length; i++) {
listJCBPays.add(new JCheckBoxMenuItem(tableauPays[i]));
}
for (int j = 0; j < listJCBPays.size(); j++) {
JCheckBoxMenuItem paysActuel = listJCBPays.get(j);
menuPays.add(paysActuel);
paysActuel.addActionListener(new OpenAction(menuPays, boutonPays));
}
listeDeFiltres = "";
for (int p = 0; p < listeFiltres.size(); p++) {
String filtreActuel = listeFiltres.get(p);
if (listeDeFiltres == "") {
listeDeFiltres += filtreActuel;
} else {
listeDeFiltres += "," + filtreActuel;
}
}
prop.setProperty("listeFiltres", listeDeFiltres);
}
}
You can get the index of name from tableauPays array as follows and can pass it to the setSelected() method
public int getIndex(String name){
int index = 0;
for(String p : tableauPays){
if(p.equals(name)){
return index;
}
index++;
}
}
I'm working on an editor plugin for a custom language and I've managed to set it up so all the necessary keywords highlight. The problem is the words become highlighted even if they are part of another word.
For example: let's say public is a keyword and I initialize a variable called publicVar so it looks like this public int publicVar. public highlights as expected but the 'public' part of publicVar is also highlighted which is not what I want.
public WFSPartitionScanner()
{
int index = 0;
int numOfRules = 5 + reversedWords.length + commonFunctions.length+directives.length +
BIFs.length + operators.length + strongOperators.length;
IToken string = new Token(WFS_STRING);
IToken comment = new Token(WFS_COMMENT);
IToken reversedWord = new Token(WFS_REVERSED_WORD);
IToken commonFunction = new Token(WFS_COMMON_FUNCTION);
IToken directive = new Token(WFS_DIRECTIVE);
IToken bif = new Token(WFS_BIF);
IToken operator = new Token(WFS_OPERATOR);
IToken strongOperator = new Token(WFS_STRONG_OPERATOR);
IToken numberToken = new Token(WFS_NUMBER);
IPredicateRule[] rules= new IPredicateRule[numOfRules];
rules[index] = new MultiLineRule("\"","\"", string, '\\');
rules[++index] = new MultiLineRule("\'", "\'", string, '\\');
rules[++index] = new SingleLineRule("//","\n", comment);
rules[++index] = new MultiLineRule("/*", "*/", comment);
rules[++index] = new WFSNumberRule(numberToken);
for(int i = 0; i < reversedWords.length; i++)
{
rules[++index] = new WordPatternRule(new WordDetector(reversedWords[i]), reversedWords[i], "",reversedWord);
}
for(int i = 0; i < commonFunctions.length; i++)
{
rules[++index] = new WordPatternRule(new WordDetector(commonFunctions[i]), commonFunctions[i], "",commonFunction);
}
for(int i = 0; i < BIFs.length;i++)
{
rules[++index] = new WordPatternRule(new WordDetector(BIFs[i]), BIFs[i], "",bif);
}
for(int i = 0; i < directives.length;i++)
{
rules[++index] = new WordPatternRule(new WordDetector(directives[i]), directives[i], "",directive);
}
for(int i=0; i < operators.length; i++)
{
rules[++index]= new WordPatternRule(new WordDetector(operators[i]), operators[i], "", operator);
}
for(int i=0; i < strongOperators.length; i++)
{
rules[++index]= new WordPatternRule(new WordDetector(strongOperators[i]), strongOperators[i], "", strongOperator);
}
setPredicateRules(rules);
}
public class WordDetector implements IWordDetector{
private char start;
private char[] part;
public WordDetector(String word)
{
this.start = word.charAt(0);
this.part = new char[word.length() - 1];
for(int i = 1; i < word.length(); i++)
{
part[i-1] = word.charAt(i);
}
}
#Override
public boolean isWordPart(char c) {
for(int i = 0; i < part.length; i++)
{
if(c == part[i])
{
return true;
}
}
return false;
}
#Override
public boolean isWordStart(char c) {
return (c == start);
}
}
I've also tried changing the WordPatternRule from
WordPatternRule(new WordDetector('KEYWORD'), 'KEYWORD', "",reversedWord);
to
WordPatternRule(new WordDetector('KEYWORD'), 'FIRST LETTER OF KEYWORD', 'LAST LETTER OF KEYWORD,reversedWord);
but I got the same results.
Ok I figured out part of the problem. To fix it i made my own WORDRULE
public class WFSWordRule extends WordRule implements IPredicateRule{
private IToken successToken;
public WFSWordRule(IWordDetector detector, String[] keywords, IToken token ) {
super(detector);
this.successToken= token;
for (String word : keywords) {
addWord(word, token);
}
}
#Override
public IToken evaluate(ICharacterScanner scanner, boolean arg1) {
return super.evaluate(scanner);
}
#Override
public IToken getSuccessToken() {
return successToken;
}
}
this doesn't completely solve the problem though. Now if there is a keyword at the end of a word the keyword is still highlighted. Using the same example as before, if i have a keyword 'Public' and i have a variable called 'varPublic' public is highlighted in both cases. But if i have a variable called 'PublicVar' public is not highlighted. any tips?
If you're trying to highlight words, not parts of words, I think you should use WordRule instead of WordPatternRule, as you have. From what I understand, WordPatternRule is used for finding patterns within a word, whereas WordRule is used for finding individual words.
I've used WordRules in an Eclipse plug in which I've been working on, and I don't have the problem of words being highlighted within other words. You can look at its code and use it as an example. Basically, it takes an IWordDetector implementation and you use its addWord method to add all the words you want it to detect.
Unlike CombinedWordRule, which greg-449 mentioned, it's a public part of the JFace framework which you are already using.
Not sure, if this is still useful, but I fixed this issue by overriding the method nextToken in my Scanner:
public IToken nextToken() {
if (this.fContentType == null || this.fRules == null) {
// don't try to resume
this.fTokenOffset = this.fOffset;
this.fColumn = RuleBasedScanner.UNDEFINED;
if (this.fRules != null) {
for (IRule fRule : this.fRules) {
IToken token = fRule.evaluate(this);
try {
if (!token.isUndefined()) {
if (this.fTokenOffset > 0 && (isWordEnd(this.fDocument.getChar(this.fTokenOffset - 1))
|| isSpecialKey(this.fDocument.getChar(this.fTokenOffset)))) {
this.fContentType = null;
return token;
}
}
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
}
if (this.read() == ICharacterScanner.EOF) {
return Token.EOF;
}
return this.fDefaultReturnToken;
}
}
isWordEnd checks for:
c == (char) 0 || c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '(' || c == ')' || c == ',' || c == ';'
isSpecialKey checks for:
c == '%'
For the other Issue, you've already fixed, I reimplemented the endSequenceDetected method in my rule:
#Override
protected boolean endSequenceDetected(ICharacterScanner scanner) {
int c = scanner.read();
scanner.unread();
return isWordEnd((char) c);
}
I'm trying to do a simple query of my database, where a unique Identification number is stored for a PendingIntent. To allow me to cancel a notification set by AlarmManager if needed.
The insertion of a value works fine, but I am unable to overcome the error:
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
Database structure:
public class DBAdapter {
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final String TASK = "task";
public static final String NOTIFICATION = "notification";
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_NOTIFICATION = 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, TASK, NOTIFICATION};
// DB info: it's name, and the table.
public static final String DATABASE_NAME = "TaskDB";
public static final String DATABASE_TABLE = "CurrentTasks";
public static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key, "
+ TASK + " text not null, "
+ NOTIFICATION + " integer"
+ ");";
Now I have created a method to extract the notification ID from the database as needed, using the following code:
public int getNotifID(long notifID){
String[] x = {ALL_KEYS[2]};
String[]args = new String[]{NOTIFICATION};
String where = NOTIFICATION + "=" + notifID;
int y = 0;
//String select = "SELECT "+NOTIFICATION+" FROM "+DATABASE_TABLE+" WHERE "+notifID+"="+NOTIFICATION;
//Cursor c = db.rawQuery(select,new String[]{});
Cursor c = db.query(true,DATABASE_TABLE,x,Long.toString(notifID),args,null,null,null,null,null);
if (c!= null && c.moveToFirst()){
y = c.getInt(COL_NOTIFICATION);
}
return y;
}
As you can see I have attempted to do this both with a rawQuery and a regular query, but with no success.
Rewrite your raw query to:
String select = "SELECT "+NOTIFICATION+" FROM "+DATABASE_TABLE+" WHERE "+NOTIFICATION+"=?";
Cursor c = db.rawQuery(select,new String[]{""+notifId});
if(c!=null && c.getCount()>0) {
c.moveToFirst();
}
c.close();