mongo morphia howto Safely remove a string from a String array - arrays

ok I have this (beginner again)
.
// ADD FRIEND TO FRIEND LIST
Query<FriendList> query1 = mongo.createQuery(FriendList.class);
query1.field("lowerCaseUserName").equal(on.lowerCaseUserName);
query1.field("passwordHash").equal(on.passwordHash);
query1.field("uuid").equal(on.uuid);
UpdateOperations<FriendList>up1=mongo.createUpdateOperations(FriendList.class).add("friendList",buddyUuid,false);
Im inserting a friend into the Array. The "friendList" is a String Array.
Would like to be able to implement removal now.
Can i just write the same code and replace the ".add" with removexxx...something?
Im thinking it's a good ide but maybe not :)
#Entity
public class FriendList {
#Id private ObjectId id;
public Date lastAccessedDate;
#Indexed(name="uuid", unique=true,dropDups=true)
private String uuid;
#Indexed(value=IndexDirection.ASC, name="lowerCaseUserName", unique=true,dropDups=true)
public String lowerCaseUserName;
public String passwordHash = "";
List<String> friendList;
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<String> getFriendList() {
return friendList;
}
public void insertFriend(String friend) {
this.friendList.add(friend);
}
// #PrePersist void prePersist() {
// lastAccessedDate = new Date();
// }
}

Query<FriendList> query1 = mongo.createQuery(FriendList.class);
query1.field("lowerCaseUserName").equal(on.lowerCaseUserName);
query1.field("passwordHash").equal(on.passwordHash);
query1.field("uuid").equal(on.uuid);
UpdateOperations<FriendList>up1=mongo.createUpdateOperations(FriendList.class).removeAll("friendList",buddyUuid);
This should remove the buddyUuid from the list.
If you could guarantee that the friendList contains unique UUID's then you could use removeFirst || removeLast method.
removeFirst/Last/All
Hope this helps!

Related

Salesforce apex class Unexpected token error

I want to create a keyword search referring to "UserName__c" api on Salesforce Apex class.
compile error Unexpected token 'UserName__c'.
public with sharing class AccountListCon {
static List<String> TARGET_FIELDS = new List<String>{
'Name'
,'UserName__c'
,'CompanyName__c'
};
public SearchCondition condition{ get;set; }
public String UserName__c results { get;set; }
public String sortingField { get;set; }
public void init(){
this.condition = new SearchCondition();
this.results = new String UserName__c();
}
public PageReference clear(){
init();
return null;
}
There is no such type String UserName__c. It's not entirely clear what you want to do here, but I suspect you intend just to declare a String variable. The fact that you're looking for values in some field whose API name is UserName__c is not relevant to the type system
public String UserName__c results { get;set; } is wrong. Is this supposed to be just
public String results { get;set; } ?

Exception when trying to use DynamoDBMapper: no mapping for HASH key

I have a DynamoDB table with a primary key (id : integer) and secondary key (dateTo : String). I've made a Class that utilizes DynamoDBMapper:
#DynamoDBTable(tableName="MyItems"
public class MyItemsMapper {
private int id;
private String dateTo;
private String name;
#DynamoDBHashKey(attributeName="id")
public void setId(int id) { this.id = id; }
public int getId() { return id; }
#DynamoDBAttribute(attributeName="dateTo")
public void setDateTo(String dateTo) { this.dateTo = dateTo; }
public String getDateTo() { return dateTo; }
#DynamoDBAttribute(attributeName="name")
public void setName(String name { this.name = name; }
public String getName() { return name; }
public boolean saveItem(MyItemsMapper item) {
try {
DynamoDBMapper mapper = new DynamoDBMapper(client); //<-- This connects to the DB. This works fine.
item.setId(generateUniqueNumber()); //<-- This generates a unique integer. Also seems to work fine.
mapper.save(item);
logger.info("Successfully saved item. See info below.");
logger.info(item.toString());
return true;
} catch (Exception e) {
logger.error("Exception while trying to save item: " + e.getMessage());
e.printStackTrace();
return false;
}
}
}
I then have a manager class that uses the bean above, like so:
public class MyManager {
public boolean recordItem(
int id,
String dateTo,
String name,
) {
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
myItemsMapper.saveItem(myItemsMapper);
}
}
I am running the manager class in a JUnit test:
public class MyManagerTest {
#Test
public void saveNewItemTest() {
MyManager myManager = new MyManager();
myManager.recordItem(1234567, "2018-01-01", "Anthony");
}
}
When I use the saveItem method above via my manager by running my JUnit test, I get the following error:
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: MyItemsMapper; no mapping for HASH key
Not really sure what it's pertaining to, as I definitely have a primary key for my table and my secondary key always has a value as well.
How do I get this to work?
More Info:
It's worth noting that I can record data into my DynamoDB table via the Item object. If I do the below, my data gets recorded into the database:
DynamoDB dynamoDB = new DynamoDBClient().connectToDynamoDB(); //<--
Connection. Works fine.
Table table = dynamoDB.getTable("MyItems");
item.withPrimaryKey("id", 1234567);
item.withString("dateTo", "2018-01-01");
item.withString("name", "Anthony");
PutItemOutcome outcome = table.putItem(item);
However, I'm trying to use DynamoDBMapper because I'm reading that it is a more organized, better way to access data.
Im not sure if this is causing the problem, but you are creating the myItemsMapper object, then passing a reference to this object to itself.
I would suggest removing your saveItem method. The MyItemsMapper class should be a plain old java object. Then make MyManager like this
public class MyManager {
public boolean recordItem(
int id,
String dateTo,
String name,
) {
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
DynamoDBMapper mapper = new DynamoDBMapper(client);
mapper.save(myItemsMapper);
}
}
If you particularly want to keep the saveItem method make it like this
public boolean saveItem() {
try {
DynamoDBMapper mapper = new DynamoDBMapper(client);
mapper.save(this);
logger.info("Successfully saved item. See info below.");
logger.info(this.toString());
return true;
} catch (Exception e) {
logger.error("Exception while trying to save item: " + e.getMessage());
e.printStackTrace();
return false;
}
}
And then in MyManager do
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
myItemsMapper.saveItem();

GWT: creating associated jsarray

I want to create a js array of type
Name(
{title : "Mr.",firstname : "Bill",lastname : "Gates"},
{title : "Mr.",firstname : "Bill",lastname : "Gates"},
{title : "Mr.",firstname : "Bill",lastname : "Gates"}
)
So basically i want to create associated array.
All the examples are like converting javascript array to java but in my case i want the other way round. I will be filling this array from java.
JSArray and JsMixedArray seems to be doing this but i could figure out how to add to them.
One approach could be to use a JSNI method to create the items/entries of your Array/Map as follows:
JsArray arr = JavaScriptObject.createArray().cast();
arr.push(newEntry("Mr.", "Bill", "Gates"));
....
private final native JavaScriptObject newEntry(String title,
String firstname, String lastname)/*-{
return {title: title, firstname: firstname, lastname: lastname};
}-*/;
You could also try to create the data structure you have in mind using the JSON utility methods: Put JSONObjects inside a JSONArray.
Variable $wnd.v will contain an array of objects.
Note: you will need to find a way how to convert your Java objects to a JSON (i used restygwt).
class PersonList {
List<Person> list;
}
class Person {
String title;
String firstName;
String lastName;
public Person () {}
public Person(String title, String firstName, String lastName) {
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
}
}
public class Main implements EntryPoint {
public interface PersonCodec extends JsonEncoderDecoder<PersonList> {
}
PersonCodec personCodec = GWT.create(PersonCodec.class);
public void onModuleLoad() {
List<Person> list = new ArrayList<Person>();
list.add(new Person("Mr.", "Bill", "Gates"));
list.add(new Person("Mr.", "Andrey", "Mormysh"));
PersonList personList = new PersonList();
personList.list = list;
String json = personCodec.encode(personList).toString();
setPersonList(json);
}
public static native void setPersonList(String personListJson)/*-{
$wnd.v = eval("(" + personListJson + ")").list;
alert($wnd.v[0].firstName); // Output: 'Bill'
}-*/;
}
You can create empty JavaScriptObject from Java but you cannot populate them from there, so use the dark side of the force:
private native JavaScriptObject putString(JavaScriptObject jso, String key, String value)/*-{
jso[key] = value;
return jso;
}-*/;
private native JavaScriptObject putObject(JavaScriptObject jso, String key, JavaScriptObject value)/*-{
jso[key] = value;
return jso;
}-*/;
void someJavaFunction() {
JavaScriptObject fromJava = JavaScriptObject.createObject();
fromJava = putString(fromJava, "foo", "bar");
fromJava = putObject(fromJava, "baz", fromJava);
}

How to show list data into datagridview?

I'm trying to bind a list of data to a data grid, but can't do it. I'm giving my code here.
I have made a class like this:
public class Book
{
int bookID;
string bookName;
string athourName;
public Book(int BookID, string BookName, string AuthorName)
{
bookID = BookID;
bookName = BookName;
athourName = AuthorName;
}
}
Under form load event, I wrote the following code:
private void Form1_Load(object sender, EventArgs e)
{
Book Book1 = new Book(001, "Java", "Harbart");
Book Book2 = new Book(002, "C", "Balaguru");
string[] BookArray = new string[10];
BookArray[0] = Book1.ToString();
BookArray[1] = Book2.ToString();
List<Book> Obj = new List<Book>();
Obj.Add(Book1);
Obj.Add(Book2);
dataGridView1.DataSource = Obj;
}
This doesn't give any error, but also not showing any data in the data grid. I have a feeling I'm missing something in between. A clarification on how to bind data to data grid would be very helpful.
The DataGridView requires public properties to autogenerate its columns. It will not work with fields, either public or private.
Change your class to this:
public class Book
{
public int bookID { get; set; }
public string bookName { get; set; }
public string athourName { get; set; }
public Book(int BookID, string BookName, string AuthorName)
{
bookID = BookID;
bookName = BookName;
athourName = AuthorName;
}
}
That uses auto-properties but you can of course use the longhand syntax as well.

Access Arrays inside Java Objects

How do I obtain values of an array that is located inside a java object in a jsp page?
I have set an object attribute so that in the jsp page I can call the object like so
${obj.property}
My question is how would I obtain property String [] example from Object obj?
<c:forEach var="prop" items="${obj.example}">
<td>${prop}</td>
</c:forEach>
I get Errors that tell me the class obj.Obj does not have the property property 'example'
and obviously I don't get the data out.
Actual errors:
org.apache.jasper.JasperException: javax.el.PropertyNotFoundException: The class 'roommate.Roommate' does not have the property 'favProfessors'.
javax.el.PropertyNotFoundException: The class 'roommate.Roommate' does not have the property 'favProfessors'
And my actual class:
package roommate;
public class Roommate{
public String firstname;
public String lastname;
public String gender;
public String place;
public String[] favProfessors;
public Roommate(String fname, String lname, String roommateGender, String hangout,String[] professors) {
firstname= fname;
lastname= lname;
gender= roommateGender;
place= hangout;
favProfessors= professors;
}
public String getFirstname()
{
return firstname;
}
public void setFirstname(String newFirstname)
{
this.firstname = newFirstname;
}
public String getLastname()
{
return lastname;
}
public void setLastname(String newLastname)
{
this.lastname = newLastname;
}
public String getGender()
{
return gender;
}
public void setGender(String newGender)
{
this.gender = newGender;
}
public String getHangout()
{
return place;
}
public void setHangout(String newPlace)
{
this.place = newPlace;
}
public String[] getProfessors()
{
return favProfessors;
}
public void setProfessors(final String[] newfavProfessors)
{
this.favProfessors = newfavProfessors;
}
public void addRoommate(String fname, String lname, String roommateGender, String hangout,String[] professors)
{
}
}
I create the object in my servlet as well ass the Atrribute
String [] profArray = request.getParameterValues("professor");
Roommate roommate= new Roommate(
session.getAttribute("fname").toString(),
session.getAttribute("lname").toString(),
session.getAttribute("gender").toString(),
session.getAttribute("hangout").toString(),
profArray);
session.setAttribute("roommate",roommate);
I asked this earlier but did not receive a clear answer. I think my issue is in pulling the data out in the jsp alone in my forEach that I mentioned at the top
javax.el.PropertyNotFoundException: The class 'roommate.Roommate' does not have the property 'favProfessors'
Java is right. You do not have a getFavProfessors() method in that class. It's instead the following:
public String[] getProfessors()
{
return favProfessors;
}
You have 2 options: use ${roommate.professors} instead, or fix the getter method name to be getFavProfessors().
In contrary to what most starters think, EL does not access private properties directly. EL just calls the public getter/setter methods according the Javabeans specification. The real private property behind it can have a completely different name or even not exist at all.

Resources