I'm new at java beanutils and i'm getting a really hard time to figure out how can i accomplish this.
I can get all fields from Html FORM, an populate with beanutils.populate(Object, request.getParamterMap());
All works, even fields mapped as "CustomClass someobj", i had a little trouble but with form input field nominate as "someobj.field" i can get its right.
Now i need to do a map as List listobj but i dont know how.
Tried in form name as "listobj[].field", "listobj.[].field", "listobj.[]field", "listobj[][field]", but none of this work. I can do it manually via setProperty("listobj",List<CustomClass>);
I got it.
For anyone with the same problem, what i did was:
In Html form
name="indexedListobj[listobj.id].field"
I'm using hibernate so my object are now Set<CustomClass> listobj instead of List<CustomClass> listobj to prevent collection exception.
What i did was to create another method for check an index against objects in Set, then, update object if exists, or append a new if not. like this:
public CustomClass getindexedListobj(int index) {
CustomClass tmp = null;
for(CustomClass o : this.listobj)
if(o.getId() == index) {
tmp = o;
break;
}
if(tmp == null) {
tmp = new CustomClass();
this.listobj.add(tmp);
}
return tmp;
}
Related
See String uuids My CODE :
if (uuidExtra != null) {
for (Parcelable p : uuidExtra) {
String uuids = ""+p;
}
}
I'm not programmer. I just learning about it.
Can you underline you question here?
Do you want to know what is the result of your uuids variable?
If so, the result will be the latest data of your uuidExtra. Because in line 3, you make new variable of uuids.
To make it more clear, let me give some example :
You have a List of string. Let's say a,b,c,d,e. Then you access every index of that List using for. Inside that for, you make a new variable called uuids. The problem is, you make new variable everytime doing a loop. So the result is uuids = e.
If you want to have result like this uuids = a,b,c,d,e. You need to modify your code like this.
String uuids;
if (uuidExtra != null) {
for (Parcelable p : uuidExtra) {
uuids = ""+p;
}
}
In FileNet P8, I need to get the datatype of the property of a custom class using JAVA API. Is there any way to do the same?
This should give you an idea of what you need to do:
//SymbolicName of the property we will search for.
String strSearchName = PropertyNames.DATE_LAST_MODIFIED;
//Document (or other object) that we will use to get classDescription.
Document document = (Document) arg0;
PropertyDescription objPropDesc = null;
PropertyDescriptionList pdl = document.get_ClassDescription().get_PropertyDescriptions();
Iterator<?> iter = pdl.iterator();
while (iter.hasNext())
{
objPropDesc = (PropertyDescription) iter.next();
// Get SymbolicName property from the property cache
String strPropDescSymbolicName = objPropDesc.get_SymbolicName();
if (strPropDescSymbolicName.equalsIgnoreCase(strSearchName))
{
// PropertyDescription object found
System.out.println("Property description selected: " + strPropDescSymbolicName);
System.out.println(objPropDesc);
TypeID type = objPropDesc.get_DataType();
System.out.println(type.toString());
break;
}
}
The idea is to:
Take an object (Document in this case).
Get its Class Description.
Get the list of Property Descriptions from the Class Description.
Loop through the Property Descritpions until you locate the Description you are trying to find.
Get the TypeId from the Property Description.
The TypeId contains the information you need to know what the Type is of the Property.
I borrowed code from here : Working with Properties
You should also familiarize yourself with this : Properties
Edit to add a different method:
In the case of creating documents, we need to be able to obtain the Class Description object. This means we will need to perform additional round trips.
// Get the ClassDescription
String strSymbolicName = "myClassName";
ClassDescription objClassDesc = Factory.ClassDescription.fetchInstance(myObjStore, strSymbolicName, null);
// find the PropertyDescription
PropertyDescription pds = null;
PropertyDescriptionList pdl = objClassDesc.get_PropertyDescriptions();
Iterator<?> itr = pdl.iterator();
while(itr.hasNext()){
pds = (PropertyDescription) itr.next();
System.out.println("Symbolic Name is "+pds.get_SymbolicName()+" DataType is "+pds.get_DataType().toString());
}
// You can now use it in a loop of several documents if you wish.
...
Take a look here as well : Working With Classes
Christopher Powell's answer is correct, there is one thing it does not cover, though (depending on the definition of the custom class in question). Consider this as a "best practice" or just an extension of the code borrowed from the URL that Christopher mentioned.
The FileNet P8 class hierarchy allows for inheritance of property definitions. Simple example: one can search through the 'Document' class - which is the root class of the class hierarchy - of an object store, and use some property of a subclass in the search sql. Imagine Subclass1 as an immediate subclass of Document. Subclass1 has a property Property1. Even if Document does not have this property in its class description, a search in Document with Property1='somevalue' will return objects of Subclass1 (if there is a match with 'somevalue').
However,
objClassDesc.get_PropertyDescriptions();
won't return property descriptions of subclasses, thus you might end up with API_PROPERTY_NOT_IN_CACHE errors.
To give you a good starting point if you are facing this case, look at below code:
PropertyDescriptionList ownProps = objClassDesc.get_PropertyDescriptions();
PropertyDescriptionList subclassProps = null;
if (objClassDesc.get_HasProperSubclassProperties()) {
logger.debug("Document class '"+documentClassname+"' supports 'include descendant properties' queries, including descendant properties.");
subclassProps = objClassDesc.get_ProperSubclassPropertyDescriptions();
}
List<PropertyDescription> result = mergePropertyDescriptionLists(ownProps, subclassProps);
If you need to merge those two lists, you are better off using a List of PropertyDescription objects instead of PropertyDescriptionList: the ones returned by the server are read-only.
#SuppressWarnings("unchecked")
protected List<PropertyDescription> mergePropertyDescriptionLists(PropertyDescriptionList list1, PropertyDescriptionList list2) throws Exception {
try {
#SuppressWarnings("unchecked")
List<PropertyDescription> mergedList = new ArrayList<PropertyDescription>();
if (list1 != null && (list1.size() > 0)) {
mergedList.addAll(list1);
}
if (list2 != null && (list2.size() > 0)) {
mergedList.addAll(list2);
}
return mergedList;
} catch (Throwable t) {
throw new Exception("Failed to merge property description lists.", t);
}
}
I have just wrote a code to cach a table in the memory (simple java hashmap). Now one of the code that i am trying to replace is the find the objects based on criteria. it receives multiple field parameters and if those fields are not empty and not null, they were being added as part of hibernate query criteria.
To replace this, what i am thinking to do is
For each valid param (not null and no empty) I will create a HashSet which will satisfy this criteria.
Once i am done making hashsets for all valid criteria, I will call Set.retainAll(second_set) on all sets. So that at the end, I will have only that set which is intersection of all valid criteria.
Does it sound like the best approach or is there any better way to implement this ?
EDIT
Though, My original post is still valid and I am looking for that answer. I ended up implementing it in the following way. The reason is that it was kind a cumbersome with sets since after creating all sets, I had to first figure out which set is non empty so that the retainAll could be called. it was resulting in lots of if-else statements. My current implementation is like this
private List<MyObj> getCachedObjs(Long criteria1, String criteria2, String criteria3) {
List<MyObj> results = new ArrayList<>();
int totalActiveFilters = 0;
if (criteria1 != null){
totalActiveFilters++;
}
if (!StringUtil.isBlank(criteria2)){
totalActiveFilters++;
}
if (!StringUtil.isBlank(criteria3)){
totalActiveFilters++;
}
for (Map.Entry<Long, MyObj> objEntry : objCache.entrySet()){
MyObj obj = objEntry.getValue();
int matchedFilters = 0;
if (criteria1 != null) {
if (obj.getCriteria1().equals(criteria1)) {
matchedFilters++;
}
}
if (!StringUtil.isBlank(criteria2)){
if (obj.getCriteria2().equals(criteria2)){
matchedFilters++;
}
}
if (!StringUtil.isBlank(criteria3)){
if (game.getCriteria3().equals(criteria3)){
matchedFilters++;
}
}
if (matchedFilters == totalActiveFilters){
results.add(obj);
}
}
return results;
}
im currently working on a multiple class assignment where i have to add a course based on whether the prerequisites exist within the program.
im storing my courses within the program class using a hashmap. (thought i would come in handy) however, im having a bit of trouble ensuring that these preReqs exist.
here is some code ive currently got going
public boolean checkForCourseFeasiblity(AbstractCourse c) throws ProgramException
{
AbstractCourse[] tempArray = new AbstractCourse[0];
tempArray= courses.keySet().toArray(tempArray);
String[] preReqsArray = new String[1];
preReqsArray = c.getPreReqs();
//gets all course values and stores them in tempArray
for(int i = 0; i < preReqsArray.length; i++)
{
if(courses.containsKey(preReqsArray[i]))
{
continue;
}
else if (!courses.containsKey(preReqsArray[i]))
{
throw new ProgramException("preReqs do not exist"); //?
}
}
return true;
}
ok so basically, tempArray is storing all the keySets inside the courses hashmap and i need to compare all of them with the preReqs (which is an array of Strings). if the preReqs exist within the keyset then add the course, if they dont do not add the course. return true if the course adds otherwise through me an exception. keep in mind my keysets are Strings e.g. a keyset value could be "Programming1" and the required prerquisite for a course could be "programming1". if this is the case add then add the course as the prereq course exists in the keyset.
i believe my error to be when i initialize mypreReqsArray with c.getPreReqs (note: getPreReqs is a getter with a return type String[]).
it would be really great if someone could aid me with my dilemma. ive tried to provide as much as possible, i feel like ive been going around in circles for the past 3 hours :(
-Thank you.
Try something like this, you don't need tempArray. The "for each" loop looks lots nicer too. If you want to throw an Exception I would put that logic in the place that calls this method.
public boolean checkForCourseFeasiblity(AbstractCourse c)
{
for(String each : c.getPreReqs())
{
if(! courses.containsKey(each))
{
return false;
}
}
return true;
}
Here's the situation :
I have 3 objects all named **List and I have a method with a String parameter;
gameList = new StringBuffer();
appsList = new StringBuffer();
movieList = new StringBuffer();
public void fetchData(String category) {
URL url = null;
BufferedReader input;
gameList.delete(0, gameList.length());
Is there a way to do something like the following :
public void fetchData(String category) {
URL url = null;
BufferedReader input;
"category"List.delete(0, gameList.length());
, so I can choose which of the lists to be used based on the String parameter?
I suggest you create a HashMap<String, StringBuffer> and use that:
map = new HashMap<String, StringBuffer>();
map.put("game", new StringBuffer());
map.put("apps", new StringBuffer());
map.put("movie", new StringBuffer());
...
public void fetchData(String category) {
StringBuffer buffer = map.get(category);
if (buffer == null) {
// No such category. Throw an exception?
} else {
// Do whatever you need to
}
}
If the lists are fields of your object - yes, using reflection:
Field field = getClass().getDeclaredField(category + "List");
List result = field.get();
But generally you should avoid reflection. And if your objects are fixed - i.e. they don't change, simply use an if-clause.
The logically simplest way taking your question as given would just be:
StringBuffer which;
if (category.equals("game"))
which=gameList;
else if (category.equals("apps"))
which=appList;
else if (category.equals("movie"))
which=movieList;
else
... some kind of error handling ...
which.delete();
As Jon Skeet noted, if the list is big or dynamic you probably want to use a map rather than an if/else/if.
That said, I'd encourage you to use integer constant or an enum rather than a String. Like:
enum ListType {GAME, APP, MOVIE};
void deleteList(ListType category)
{
if (category==GAME)
... etc ...
In this simple example, if this is all you'd ever do with it, it wouldn't matter much. But I'm working on a system now that uses String tokens for this sort of thing all over the place, and it creates a lot of problems.
Suppose you call the function and by mistake you pass in "app" instead of "apps", or "Game" instead of "game". Or maybe you're thinking you added handling for "song" yesterday but in fact you went to lunch instead. This will successfully compile, and you won't have any clue that there's a problem until run-time. If the program does not throw an error on an invalid value but instead takes some default action, you could have a bug that's difficult to track down. But with an enum, if you mis-spell the name or try to use one that isn't defined, the compiler will immediately alert you to the error.
Suppose that some functions take special action for some of these options but not others. Like you find yourself writing
if (category.equals("app"))
getSpaceRequirements();
and that sort of thing. Then someone reading the program sees a reference to "app" here, a reference to "game" 20 lines later, etc. It could be difficult to determine what all the possible values are. Any given function might not explicitly reference them all. But with an enum, they're all neatly in one place.
You could use a switch statement
StringBuffer buffer = null;
switch (category) {
case "game": buffer = gameList;
case "apps": buffer = appsList;
case "movie": buffer = movieList;
default: return;
}