I want to update a document with a User object that I have, but I do not want the document to be created if it does not exist, and therefore I cannot use "DocumentReference.set" with "SetOptions.Merge()" (to my understanding).
However, according to this post (Difference between set with {merge: true} and update), "update" is actually the command I need. My problem is, it doesn't seem like update accepts a Java object.
I do not want to check whether or not the document exists myself, as this will result in an unnecessary read.
Is there any way around this?
Here is my code (I have removed success and failure listeners for simplicity):
public void saveUser(User user)
{
CollectionReference collection = db.collection("users");
String id = user.getId();
if (id.equals(""))
{
collection.add(user);
}
else
{
// I need to ensure that the ID variable for my user corresponds
// with an existing ID, as I do not want a new ID to be generated by
// my Java code (all IDs should be generated by Firestore auto-ID)
collection.document(ID).set(user);
}
}
It sounds like you:
Want to update an existing document
Are unsure if it already exists
Are unwilling to read the document to see if it exists
If this is the case, simply call update() and let it fail if the document doesn't exist. It won't crash your app. Simply attach an error listener to the task it returns, and decide what you want to do if it fails.
However you will need to construct a Map of fields and values to update using the source object you have. There are no workarounds for that.
Related
The question may sound weird. I have the following custom Object that I named ItemUser:
private UserInfo user_info;
private List<UserAchievement> user_achievements;
Both fields have getters and setters. My Firestore's database looks like this:
I would like to get the List size instead of re-calling the database and getting the size of the collection from a separated call that would consume much resources and take a lot of time (3-4s).
Firstly I'm getting the data using this:
mDB.collection("COLLECTION_NAME").document("USER_ID").get()
Inside the onCompletedListener I'm getting the custom object as the following:
ItemUser mUser = task.getResult().toObject(ItemUser.class);
Now, when I'm trying to get the size of the user_achievements, a NullPointerException popups saying I can't get the size of a null reference.
Therefore the user_achievements is null. I think the way I'm defining user_achievements in my custom Object is the reason for this exception.
The question is: How could this be possible done without recalling the database to count only the size?
I have the main custom Object ItemUser and its children are 'healthy' except user_achievements because of the way it's defined - List<UserAchievement>.
So, any suggestions to overpass this issue?
How could this be possible done without recalling the database to count only the size?
No, because Cloud Firestore is a real-time database and items can be added or deleted, so to get the size of a list you need to query the database and use a get() call.
If you want to count the number of documents beneath a collection (which can be added to a list), please see my answer from this post in which I have explained that task.getResult().size() can help you solve the problem.
Edit:
mDB.collection("COLLECTION_NAME").document("USER_ID").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
int size = task.getResult().size();
Log.d(TAG, String.valueOf(size));
}
}
});
I've written a program to aid the user in configuring 'mechs for a game. I'm dealing with loading the user's saved data. This data can (and some times does) become partially corrupt (either due to bugs on my side or due to changes in the game data/rules from upstream).
I need to be able to handle this corruption and load as much as possible. To be more specific, the contents of the save file are syntactically correct but semantically corrupt. I can safely parse the file and drop whatever entries that are not semantically OK.
Currently my data parser will just show a modal dialog with an appropriate warning message. However displaying the warning is not the job of the parser and I'm looking for a way of passing this information to the caller.
Some code to show approximately what is going on (in reality there is a bit more going on than this, but this highlights the problem):
class Parser{
public void parse(XMLNode aNode){
...
if(corrupted) {
JOptionPane.showMessageDialog(null, "Corrupted data found",
"error!", JOptionPane.WARNING_MESSAGE);
// Keep calm and carry on
}
}
}
class UserData{
static UserData loadFromFile(File aFile){
UserData data = new UserData();
Parser parser = new Parser();
XMLDoc doc = fromXml(aFile);
for(XMLNode entry : doc.allEntries()){
data.append(parser.parse(entry));
}
return data;
}
}
The thing here is that bar an IOException or a syntax error in the XML, loadFromFile will always succeed in loading something and this is the wanted behavior. Somehow I just need to pass the information of what (if anything) went wrong to the caller. I could return a Pair<UserData,String> but this doesn't look very pretty. Throwing an exception will not work in this case obviously.
Does any one have any ideas on how to solve this?
Depending on what you are trying to represent, you can use a class, like SQLWarning from the java.sql package. When you have a java.sql.Statement and call executeQuery you get a java.sql.ResultSet and you can then call getWarnings on the result set directly, or even on the statement itself.
You can use an enum, like RefUpdate.Result, from the JGit project. When you have a org.eclipse.jgit.api.Git you can create a FetchCommand, which will provide you with a FetchResult, which will provide you with a collection of TrackingRefUpdates, which will each contain a RefUpdate.Result enum, which can be one of:
FAST_FORWARD
FORCED
IO_FAILURE
LOCK_FAILURE
NEW
NO_CHANGE
NOT_ATTEMPTED
REJECTED
REJECTED_CURRENT_BRANCH
RENAMED
In your case, you could even use a boolean flag:
class UserData {
public boolean isCorrupt();
}
But since you mentioned there is a bit more than that going on in reality, it really depends on your model of "corrupt". However, you will probably have more options if you have a UserDataReader that you can instantiate, instead of a static utility method.
This one seems like it should be simple enough. I'm writing a Notes Agent in Java; it calculates a fairly large amount of numeric data (a 6400-entry array of doubles) that I want to store in an existing document, updating a field. Because of Notes' field limitations, I figured I needed to use a RichText field to do that. (My initial attempt to write to a multi-value Number field resulted in it failing to save somewhere between an array of size 4000 and 5000.) It's not clear to me how one stores that value in a RichTextItem, though. All my attempts have failed. In one case, using doc.replaceItemValue(), it seemed to convert the item to a Text List. Getting the item, casting it to a RichTextItem, and calling setValues() or setValueString() doesn't seem to do anything. This shouldn't be this hard! Any pointers?
(Alternately: Any better suggestion for how to store my array in a document in the database?)
Thanks,
Reid
You'll need to create a RichTextItem and use the methods on that object to populate it:
import lotus.domino.*;
import java.util.Vector;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext =
session.getAgentContext();
// (Your code goes here)
Database db = agentContext.getCurrentDatabase();
Document doc = db.createDocument();
Item subject = doc.replaceItemValue("Subject",
"Project description");
RichTextItem body = doc.createRichTextItem("Body");
body.appendText("Cartoon book for children
ages 9-12");
// Print text of subject and body
System.out.println(subject.getText());
System.out.println(body.getText());
// Save the document
doc.save(true, true);
} catch(Exception e) {
e.printStackTrace();
}
}
}
UPDATE:
If you need to edit an existing document, instead of creating a new rich text item, you would get the existing one.
RichTextItem body = doc.GetFirstItem("Body"); // instead of createRichTextItem
You can bypass the Notes' field limitations. You can flag your item as «contains non-summary data» by using the NotesItem.IsSummary property. You need to set this property to false. But remember, you cannot use this item in views and folders.
Here is example:
Vector vector = new Vector();
for (int index = 0; index<6400;index++)
vector.addElement(new Double(Math.random()*100));
Item item = document.replaceItemValue("YourFieldName", vector);
item.setSummary(false);
document.save(true,true);
As for the question of "better" solution. I've recently written some code where I serialize/deserialize Java objects as JSON strings. This way they are well readable and easily restorable. I guess for the plain array it's a little problem. Especially if you do not want to restore it and have not interest to look at it (well, but probably it should be one or other :-)
And yes, you have to store it in the rich text anyway. Alternative you might write a text document and attach it in the RT field (again RT :-). Pretty usual scenario and easy to do.
Finally you could store data as database objects, but I guess from Java you do not really have access to do it. And it does not seem to be in any way better.
I am using a local database in my version of Lotus notes(8.5.2), and I am trying to get the data for two things:
The highlighted document/item in a NotesUIView
The document selected in a NotesUIDocument
However, all I get are the Notes URLs and I don't know what I should do with those. Can anyone help me out/throw me a breadcrumb?
P.S. Yes I am using the Java API for Eclipse.
Here is a code sample of what I do:
NotesUIWorkspace workSpace = new NotesUIWorkspace();
NotesUIElement currentElement = workSpace.getCurrentElement();
if (currentElement instanceof NotesUIView) {
NotesUIView currentView = (NotesUIView) currentElement;
NotesUIViewEntryCollection collection = currentView
.getActionableEntries();
Iterator docIterator = collection.documentIterator();
while (docIterator.hasNext()) {
NotesUIDocumentEntry entry = (NotesUIDocumentEntry) docIterator.next();
//I can't seem to get to the NoesUIDocument case like I can below... I want fields!
}
}
if(currentElement instanceof NotesUIDocument){
NotesUIDocument document = (NotesUIDocument) currentElement;
//Seem to be able to get the correct data fields only in this case!
document.getFields();
}
Fetching the "current" document is usually done via the NotesAgentContext.UnprocessedDocuments. In a view, that might return a collection of documents if the user as ticked several.
If you already have an NotesUIView, NotesUIView.getActionableEntries will give you the selected document(s).
When you have a NotesDocumentData instance, NotesUIWorkspace.openDocument can be used to open it up in edit mode. Then NotesUIWorkspace.getCurrentDocument can be used to get hold of the UI Document.
Notice that if you only want to read values from the document, it is more convenient to use the back-end classes like Document.
Have you got a URL as an example? If it includes the UUID of the document in question then you should be able to reference it directly with a getDocument(). Otherwise, the URL should include a view reference and a lookup key for that view in question.
I'm evaluating MongoDB and Morphia right now. How would I model something like 'settings', where there is only one 'record' (I'm not sure of the proper Mongo term to use). Must I override the save method in my entity class? An example of how to do this and how to use it would be awesome.
For example, I'd like to store the home page configuration:
home page settings
show friends list: false
marketing text: "You'll love it here"
main image: main.jpg
If you basically only want a single copy of settings for your application (like a singleton) then I would suggest something like this:
#Entity
class Settings {
#Id int id = 0;
boolean showFriendsList = false;
String marketingText = "You'll love it";
byte[] mainImage = ...;
}
Since the id is set to a single value then when you call save it will always update the single entity. If you call insert, and there is already one there, you will get an error (if you are checking for errors).
You can update the entity using get/change/save or update semantics.
Datastore ds = ...;
//get/change/save
Settings s = ds.find(Settings.class).get(); //like findOne in the shell/driver
s.showFriendsList = true;
ds.save(s);
//or update
ds.updateFirst(ds.find(Settings.class), ds.creatUpdateOperations(Settings.class).set("showFiendsList", true));