I'm using Dynamicloud and something is wrong in my code.
This is my code:
DynamicProvider<ContactForm> provider = new DynamicProviderImpl<ContactForm>(new RecordCredential(csk, aci));
contactFormModel.setBoundClass(ContactForm.class);
Query<ContactForm> query = provider.createQuery(contactFormModel);
try {
RecordResults<ContactForm> list = query.add(Conditions.like("contact.namef", "ProBusiness%")).list();
System.out.println("list = " + list.getFastReturnedSize());
if (list.getFastReturnedSize() > 0) {
System.out.println("Contact Name = " + list.getRecords().get(0).getName());
System.out.println("Contact Comments = " + list.getRecords().get(0).getComments());
}
} catch (DynamicloudProviderException e) {
e.printStackTrace();
}
This code throws the following Exception:
org.dynamicloud.exception.DynamicloudProviderException: Invalid statement. Please check aliases, field identifiers, projections and query conditions.
What's wrong?
Thanks!
Hi
The problems is the contact word right before namef in your like condition.
Dynamicloud API provides a method to set the alias of a model. For example, the aliases are used in situations where you need to execute JOINS
The problem is solved by calling the method setAlias from the query object query.setAlias("contact")
query.setAlias("contact");
Dynamicloud resources about Query class
Hope this helps
Related
I looked at all related posts but I couldn't find what I am looking for.
Verified the query syntax by using https://codebeautify.org/jsonpath-tester and https://jsonpath.com/. In below code, I get correct response if I print just id. I am looking for title, based on specific userID and id.
Getting "Invalid JSON expression" as o/p. Can anyone pls help here!
public void restPost2(){
RestAssured.baseURI = "https://jsonplaceholder.typicode.com/posts";
RequestSpecification req = RestAssured.given().log().all();
String res1 = req.given().when().get().then().extract().asString();
JsonPath js = new JsonPath(res1);
System.out.println("list of Ids : " + js.get("id"));
System.out.println("specific title : " + js.get("(?(#.userId == '3') && (#.id == '23')).title"));
}
Following changes will solve your issue.
Use JsonPath.read to set json string to be queries
Syntax of jsonPath queries need to be corrected.
suggest you to refer jsonPath documentation again.
Please find a working example
json = <data fetched for the api>
Object x = JsonPath.read(json,"$..id");
Object y = JsonPath.read(json,"$[?(#.userId == 3 && #.id == 23)]");
I have a collection with some documents in it. And in my application I am creating this collection first and then inserting documents. Also, based on the requirement I need to truncate (delete all documents) the collection as well. Using document db java api I have written the following code for my this purpose-
DocumentClient documentClient = getConnection(masterkey, server, portNo);
List<Database> databaseList = documentClient.queryDatabases("SELECT * FROM root r WHERE r.id='" + schemaName + "'", null).getQueryIterable().toList();
DocumentCollection collection = null;
Database databaseCache = (Database)databaseList.get(0);
List<DocumentCollection> collectionList = documentClient.queryCollections(databaseCache.getSelfLink(), "SELECT * FROM root r WHERE r.id='" + collectionName + "'", null).getQueryIterable().toList();
// truncate logic
if (collectionList.size() > 0) {
collection = ((DocumentCollection) collectionList.get(0));
if (truncate) {
try {
documentClient.deleteDocument(collection.getSelfLink(), null);
} catch (DocumentClientException e) {
e.printStackTrace();
}
}
} else { // create logic
RequestOptions requestOptions = new RequestOptions();
requestOptions.setOfferType("S1");
collection = new DocumentCollection();
collection.setId(collectionName);
try {
collection = documentClient.createCollection(databaseCache.getSelfLink(), collection, requestOptions).getResource();
} catch (DocumentClientException e) {
e.printStackTrace();
}
With the above code I am able to create a new collection successfully. Also, I am able to insert documents as well in this collection. But while truncating the collection I am getting below error-
com.microsoft.azure.documentdb.DocumentClientException: The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'delete
colls
eyckqjnw0ae=
I am using Azure Document DB Java API version 1.9.5.
It will be of great help if you can point out the error in my code or if there is any other better way of truncating collection. I would really appreciate any kind of help here.
According to your description & code, I think the issue was caused by the code below.
try {
documentClient.deleteDocument(collection.getSelfLink(), null);
} catch (DocumentClientException e) {
e.printStackTrace();
}
It seems that you want to delete a document via the code above, but pass the argument documentLink with a collection link.
So if your real intention is to delete a collection, please using the method DocumentClient.deleteCollection(collectionLink, options).
I am trying to grab reply to certain comment from facebook using the help from the comment library of restfb and the function getcomments().
After executing my code, it returns me a null rather than a reply to the comment.
Below is my snapshot of my code.
Connection<Comment> allComments = fbClient.fetchConnection(myArr1.get(xy)+"/comments", Comment.class);
for(List<Comment> postcomments : allComments){
for (Comment comment : postcomments){
String commentTemp = comment.getId() +" "+ comment.getFrom().getId() +" "+ comment.getCreatedTime() +" "+ comment.getMessage() +" "+ comment.getLikeCount() +" "+ comment.getComments()+" "+myArr1.get(xy);
}
}
All the function returns me the correct value except for the comment.getcomments()
You should use the fetchConnection on the comment-id/comments. This is perhaps a bit expensive, but so you can fetch really all replies.
Hi I am using restfb and found similar problem; the issue is that the connection.getData() returns only the first page of data. I used the iterator and was able to get all the comments.
Please note you would have to do the same thing even for replies of comments; you will need to create a separate connection using comment id, instead of post id and then iterate out the comments in the same way shown below.
Connection<Comment> commentsConnection= fbClient.fetchConnection(post.getId()+"/comments",com.restfb.types.Comment.class);
if(commentsConnection!=null)
{
Iterator<List<Comment>> commentsIterator=commentsConnection.iterator();
while(commentsIterator.hasNext())
{
List<Comment> comments= commentsIterator.next();
for(Comment comment:comments)
{
String message=comment.getMessage();
}
}
}
I am using Apache Jackrabbit as a database.
In my case, root node has numbers of child nodes(only at depth 1).
All child node has unique name, i.e., some Integer.
Each child Node have some properties that I have used further.
My task
I have to take top 10 nodes whose keys(integer values) are minimum.
My thinking
To achieve above goal, I make a query that sorts the keys of all child nodes, and pick top 10. Then by using that keys, I get all corresponding nodes, and after working, delete all that key/value pairs.
For that I searched a lot on the internet how to run the query. Can you please tell me how to run query on apache jackrabit. It is good, if you explain with example.
Edit no. 1
public class JackRabbit {
public static void main(String[] args) throws Exception {
try {
Repository repository = JcrUtils.getRepository("http://localhost:4502/crx/server");
javax.jcr.Session session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
Node root = session.getRootNode();
// Obtain the query manager for the session via the workspace ...
javax.jcr.query.QueryManager queryManager = session.getWorkspace().getQueryManager();
// Create a query object ...
String expression = "select * from nt:base where name= '12345' ";
javax.jcr.query.Query query = queryManager.createQuery(expression, javax.jcr.query.Query.JCR_SQL2);
// Execute the query and get the results ...
javax.jcr.query.QueryResult result = query.execute();
session.logout();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Exception
javax.jcr.query.InvalidQueryException: Query:
select * from nt:(*)base where name= '12345'; expected: <end>
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.apache.jackrabbit.spi2dav.ExceptionConverter.generate(ExceptionConverter.java:69)
at org.apache.jackrabbit.spi2dav.ExceptionConverter.generate(ExceptionConverter.java:51)
at org.apache.jackrabbit.spi2dav.ExceptionConverter.generate(ExceptionConverter.java:45)
at org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.executeQuery(RepositoryServiceImpl.java:2004)
at org.apache.jackrabbit.jcr2spi.WorkspaceManager.executeQuery(WorkspaceManager.java:349)
at org.apache.jackrabbit.jcr2spi.query.QueryImpl.execute(QueryImpl.java:149)
at jackrabbit.JackRabbit.main(JackRabbit.java:36)
I want to write a query of below scenereo
Here nodes having integer value have some properties. I want to sort these nodes by their integer values, and extract top 50 nodes for further processing.
Help me in that.
You should quote your node type name in JCR-SQL2:
select * from [nt:base]
This is one of the main differences between JCR-SQL and JCR-SQL2. Besides, name is a dynamic operand taking a selector argument. So a better way to write your query would be this:
select * from [nt:base] as b where name(b) = '12345'
You have different ways of executing your queries depending on the query language you want to use.
Take a look at this code for some simple query using only the API and not SQL like string queries.
You can take a look at JBoss Modeshape documentation for examples too since it is another JCR 2.0 implementation.
I hope this will help you to execute the query:
public FolderListReturn listFolder(String parentNode, String userid,String password) {
System.out.println("getting folders and files from = "+parentNode+" of user : "+userid);
SessionWrapper sessions =JcrRepositoryUtils.login(userid, password);
Session jcrsession = sessions.getSession();
Assert.notNull(name);
FolderListReturn folderList1 = new FolderListReturn();
ArrayOfFolders folders = new ArrayOfFolders();
try {
javax.jcr.query.QueryManager queryManager;
queryManager = jcrsession.getWorkspace().getQueryManager();
String expression = "select * from [nt:folder] AS s WHERE ISCHILDNODE(s,'"+name+"')and CONTAINS(s.[edms:owner],'*"+userid+"*') ORDER BY s.["+Config.EDMS_Sorting_Parameter+"] ASC";
javax.jcr.query.Query query = queryManager.createQuery(expression, javax.jcr.query.Query.JCR_SQL2);
javax.jcr.query.QueryResult result = query.execute();
for (NodeIterator nit = result.getNodes(); nit.hasNext();) {
Node node = nit.nextNode();
Folder folder = new Folder();
folder=setProperties(node,folder,userid,password,jcrsession,name);
folders.getFolderList().add(folder);
}
folderList1.setFolderListResult(folders);
folderList1.setSuccess(true);
} catch (Exception e) {
e.printStackTrace();
}finally{
//JcrRepositoryUtils.logout(sessionId);
}
return folderList1;
}
I'm familiar with the java.sql.DatabaseMetaData interface, but I find it quite clunky to use. For example, in order to find out the table names, you have to call getTables and loop through the returned ResultSet, using well-known literals as the column names.
Is there an easier way to obtain database metadata?
It's easily done using DdlUtils:
import javax.sql.DataSource;
import org.apache.ddlutils.Platform;
import org.apache.ddlutils.PlatformFactory;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.platform.hsqldb.HsqlDbPlatform;
public void readMetaData(final DataSource dataSource) {
final Platform platform = PlatformFactory.createNewPlatformInstance(dataSource);
final Database database = platform.readModelFromDatabase("someName");
// Inspect the database as required; has objects like Table/Column/etc.
}
Take a look at SchemaCrawler (free and open source), which is another API designed for this purpose. Some sample SchemaCrawler code:
// Create the options
final SchemaCrawlerOptions options = new SchemaCrawlerOptions();
// Set what details are required in the schema - this affects the
// time taken to crawl the schema
options.setSchemaInfoLevel(SchemaInfoLevel.standard());
options.setShowStoredProcedures(false);
// Sorting options
options.setAlphabeticalSortForTableColumns(true);
// Get the schema definition
// (the database connection is managed outside of this code snippet)
final Database database = SchemaCrawlerUtility.getDatabase(connection, options);
for (final Catalog catalog: database.getCatalogs())
{
for (final Schema schema: catalog.getSchemas())
{
System.out.println(schema);
for (final Table table: schema.getTables())
{
System.out.print("o--> " + table);
if (table instanceof View)
{
System.out.println(" (VIEW)");
}
else
{
System.out.println();
}
for (final Column column: table.getColumns())
{
System.out.println(" o--> " + column + " (" + column.getType()
+ ")");
}
}
}
}
http://schemacrawler.sourceforge.net/