Cannot put DesignDocuments back - java

I am trying to delete all documents from a database but i want to preserve the views. So i tried
//First, get all DesignDocument for the current database
List<DesignDocument> dbDesigns = cloudant.getDesignDocumentManager().list();
//Now, we delete the database
cloudantClient.deleteDB(_DatabaseName);
//now we create the database again
cloudant = cloudantClient.database(_DatabaseName, true);
//finally, try to add the DesignDocuments back
if (dbDesigns != null && dbDesigns.size() > 0) {
for (DesignDocument dDoc : dbDesigns) {
Response response = cloudant.getDesignDocumentManager().put(dDoc);
System.out.println(response);
}
}
but i get error at
Response response = cloudant.getDesignDocumentManager().put(dDoc);
java.lang.IllegalArgumentException: rev should be null
at com.cloudant.client.org.lightcouch.internal.CouchDbUtil.assertNull(CouchDbUtil.java:72)
at com.cloudant.client.org.lightcouch.CouchDbClient.put(CouchDbClient.java:410)
at com.cloudant.client.org.lightcouch.CouchDbClient.put(CouchDbClient.java:394)
at com.cloudant.client.org.lightcouch.CouchDatabaseBase.save(CouchDatabaseBase.java:196)
at com.cloudant.client.api.Database.save(Database.java:710)
at com.cloudant.client.api.DesignDocumentManager.put(DesignDocumentManager.java:122)
is there any other way to preserve the views?

I'm suspecting the error is raised because the document revision property (_rev) is set in dDoc. However, since a document with a matching id is not found in the database the put method raises an error. Try setting the revision to null using the setRevision method prior to invoking put
dDoc.setRevision(null);
Response response = cloudant.getDesignDocumentManager().put(dDoc);

Related

Neo4J CYPHER in C# or Java: Return JSON output from “call db.schema.nodeTypeProperties()”?

When calling db.schema.nodeTypeProperties() from within the Neo4J Broswer, the Code side tab returns the complete JSON schema in the Response drop-down. Is it possible to retrieve this JSON result in C# or Java using the Neo4J.Driver? I would like to deserialize the JSON text into C# classes.
Screen-cap of Response drop-down from db.schema.nodeTypeProperties()
I have explored the Neo4J.Driver IDriver, IAsyncSession and IResultCursor calls and cannot find a way to retrieve the JSON dataset.
I was able to get what I wanted by using apoc.export.json.all to stream in a JSON dataset of the entire database. I leveraged the examples at https://neo4j.com/docs/labs/apoc/current/export/json/#export-database-json. I apologize for what turned out to be the misdirection of my question. db.schema.nodeTypeProperties() was not going to get me what I really needed.
using Newtonsoft.Json.Linq;
public async void TestNeo4j()
{
// Set up the graph database driver and connect the session to the Neo4J database.
IDriver driver = GraphDatabase.Driver(Neo4JBoltURI, AuthTokens.Basic(Neo4JUser, Neo4JPassword));
IAsyncSession session = driver.AsyncSession();
IResultCursor cursor;
try
{
// Bring the JSON text in as a stream
string query = "CALL apoc.export.json.all(null,{stream:true,useTypes:true}) " +
"YIELD file, nodes, relationships, properties, data " +
"RETURN file, nodes, relationships, properties, data";
cursor = await session.RunAsync(query);
string sJsonData = await cursor.SingleAsync(record => record["data"].As<string>());
//Debug.Log(sJsonData);
//// Save the JSON to a file.
//string path = #"C:\Users\Public\Documents\Neo4JExportAll.json";
//if (File.Exists(path)) File.Delete(path);
//File.WriteAllText(path, sJsonData);
// Each line is a separate JSON statement describing a node or a relationship
// Iterate all statements
using (StringReader reader = new StringReader(sJsonData))
{
string line = string.Empty;
do
{
line = reader.ReadLine();
if (line != null)
{
// Deserialize the JSON line into JObject jo.
JObject jo = JObject.Parse(line);
// Dig into the JObject to get the data from the stream.
}
} while (line != null);
}
}
finally
{
await session.CloseAsync();
}
}

Downloading attachments from unseen messages

I work on university project in java. I have to download attachments from new emails using GMAIL API.
I successfully connected to gmail account using OAuth 2.0 authorization.
private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_READONLY);
I tried to get unseen mails using
ListMessagesResponse listMessageResponse = service.users().messages().list(user).setQ("is:unseen").execute();
listMessageResponse is not null but when I call method .getResultSizeEstimate() it returns 0
also I tried to convert listMessageResponse to List < Message > (I guess this is more usable) using
List<Message> list = listMessageResponse.getMessages();
But list launches NullPointerException
Then tried to get each attachment with
for(Message m : list) {
List<MessagePart> part = m.getPayload().getParts();
for(MessagePart p: part) {
if(p.getFilename()!=null && p.getFilename().length()>0) {
System.out.println(p.getFilename()); // Just to check attachment filename
}
}
}
Is my approach correct (if not how to fix it) and how should I download those attachments.
EDIT 1:
Fixed q parameter, I mistakenly wrote is:unseen instead of is:unread.
Now app reaches unread mails successfully.
(For example there was two unread mails and both successfully reached, I can get theirs IDs easy).
Now this part trows NullPointerException
List<MessagePart> part = m.getPayload().getParts();
Both messages have attachments and m is not null (I get ID with .getID())
Any ideas how to overcome this and download attachment?
EDIT 2:
Attachments Downloading part
for(MessagePart p : parts) {
if ((p.getFilename() != null && p.getFilename().length() > 0)) {
String filename = p.getFilename();
String attId = p.getBody().getAttachmentId();
MessagePartBody attachPart;
FileOutputStream fileOutFile = null;
try {
attachPart = service.users().messages().attachments().get("me", p.getPartId(), attId).execute();
byte[] fileByteArray = Base64.decodeBase64(attachPart.getData());
fileOutFile = new FileOutputStream(filename); // Or any other dir
fileOutFile.write(fileByteArray);
fileOutFile.close();
}catch (IOException e) {
System.out.println("IO Exception processing attachment: " + filename);
} finally {
if (fileOutFile != null) {
try {
fileOutFile.close();
} catch (IOException e) {
// probably doesn't matter
}
}
}
}
}
Downloading working like charm, tested app with different type of emails.
Only thing left is to change label of unread message (that was reached by app) to read. Any tips how to do it?
And one tiny question:
I want this app to fetch mails on every 10 minutes using TimerTask abstract class. Is there need for manual "closing" of connection with gmail or that's done automatically after run() method iteration ends?
#Override
public void run(){
// Some fancy code
service.close(); // Something like that if even exists
}
I don't think ListMessagesResponse ever becomes null. Even if there are no messages that match your query, at least resultSizeEstimate will get populated in the resulting response: see Users.messages: list > Response.
I think you are using the correct approach, just that there is no message that matches your query. Actually, I never saw is:unseen before. Did you mean is:unread instead?
Update:
When using Users.messages: list only the id and the threadId of each message is populated, so you cannot access the message payload. In order to get the full message resource, you have to use Users.messages: get instead, as you can see in the referenced link:
Note that each message resource contains only an id and a threadId. Additional message details can be fetched using the messages.get method.
So in this case, after getting the list of messages, you have to iterate through the list, and do the following for each message in the list:
Get the message id via m.getId().
Once you have retrieved the message id, use it to call Gmail.Users.Messages.Get and get the full message resource. The retrieved message should have all fields populated, including payload, and you should be able to access the corresponding attachments.
Code sample:
List<Message> list = listMessageResponse.getMessages();
for(Message m : list) {
Message message = service.users().messages().get(user, m.getId()).execute();
List<MessagePart> part = message.getPayload().getParts();
// Rest of code
}
Reference:
Class ListMessagesResponse
Users.messages: list > Response

How ignore hibernate error and continue insert data?

I have some method in my DAO class:
public void insertAVAYAcmCDRs(List<AvayaCmCdr> cdrList) {
AvayaCmCdr aCdrList1 = null;
try {
em.getTransaction().begin();
for (AvayaCmCdr aCdrList : cdrList) {
aCdrList1 = aCdrList;
em.persist(aCdrList);
}
em.getTransaction().commit();
em.clear();
} catch (Exception e) {
logger.log(Level.INFO, "Exception in task time={0}. Exception message = {1}.", new Object[]{aCdrList1.getDate(), e.getMessage()});
}
}
I tried save all array entities to DB. But in DB i have uniqe index - it does not allow to insert duplicate rows. It work normaly on DB side but i have some error in java.
a different object with the same identifier value was already associated with the session:
I get this error on 2 step of cycle. I print this object and found dublicate in DB.
I want ignore this error and continue insert data or somehow handle the error.
if this row already in the database i want ignore and skip it and continue insert
Why are you assigning this aCdrList1 = aCdrList ? Is there any specific reason?
you can save aCdrList object. Use below one
em.saveOrUpdate(aCdrList);
or
em.merge(aCdrList);

Using Arraylist in Mule to query Salesforce

We are trying to query Salesforce with an ArrayList in the where statement.
Below is is the error we ran into when we tried using the ArrayList in the where clause.
Query we used against Salesforce:
Select Id,Billing_Number__c from Call_Log__c where Id in #[flowVars.successlist]
successlist contains the values ['a1o90000001msXwAAI', 'a1o90000001msXxAAI'].
Error Message:
Message: Failed to invoke query. Message payload is of type: ArrayList
How do I resolve this error?
Unfortunately, you can't use ArrayLists as parameters in Salesforce (or Database) queries. You'll have to create the query dynamically with a script component.
Try this:
<scripting:script engine="Groovy">
<![CDATA[def sb = new StringBuilder()
sb.append('Select Id,Billing_Number__c from Call_Log__c')
if (flowVars.successlist != null && !flowVars.successlist.empty) {
sb.append(' where Id in (\'')
for (i in 0 .. flowVars.size()) {
if (i > 0) sb.append('\',\'')
sb.append(flowVars.successlist[i])
}
sb.append('\')')
}
flowVars.query = sb.toString()]]>
</scripting:script>
<sfdc:query query="#[flowVars.query]" doc:name="Salesforce - Query"/>
If you were using a Database, you would have to set the query type as dynamic:
<db:select doc:name="Database">
<db:dynamic-query><![CDATA[#[flowVars.query]]]></db:dynamic-query>
</db:select>
We have used a Java function string.join to convert the list as shown below:
SELECT id FROM User where Id in (#["'" + String.join("','", flowVars.fvCreatedbyIdList) + "'"])

How to fetch WorkItem links with the TFS Java API

We use the TFS Java API to fetch WorkItems from a TFS server:
TFSTeamProjectCollection collection = TFSTeamProjectCollectionUtils
.openTeamProjectCollection(serverUrl, credentials,
new DefaultConnectionAdvisor(Locale.getDefault(),
TimeZone.getDefault()));
WorkItemClient client = collection.getWorkItemClient();
List<WorkItem> result = new ArrayList<>();
try {
WorkItemCollection workItems = client.query(wiqlQuery, null, false);
for (int i = 0; i < workItems.size(); i++) {
WorkItem item = workItems.getWorkItem(i);
result.add(item);
}
return result;
} catch (TECoreException e) {
throw new ConQATException("Failed to fetch work items from TFS", e);
}
If I run the query select * from workitems I get all workitems on the server with all fields and all links. Since I'm only interested in some of the fields, I would like to restrict the query to only those and save some bandwidth/time: select ID, Title from workitems
This works fine, but now the links of the items are missing (i.e. item.getLinks() always returns an empty collection).
Is there a way to select the links other than select * from workitems?
After some more digging around, I found that you can create a link query and run it like this:
WorkItemLinkInfo[] infos = client.createQuery("select * from workitemlinks").runLinkQuery()
With this, you can get the links as WorkItemLinkInfo objects that contain the IDs of the target and source node and the link type.
The solution using WorkItemLinkInfo is correct.
Just as remark: Using a WIQL Query you only receive the attributes you were querying - which cannot be the set of links of a work item (therefore always empty). If you query a single workitem using
WorkItemClient client = TFSConnection.getClient();
WorkItem firstWorkItem = client.getWorkItemByID(id);
then you also get the LinkCollection using (containing RelatedLinks, ExternalLinks or HyperLinks)
LinkCollection linkcoll = firstWorkItem.getLinks()

Categories