I am trying to loop through request body keys and set values of an object when the key and an object field correlate like so:
User user = new User((String) super.session.get("id"));
Class<?> c = user.getClass();
for(String key : super.body.keySet()){
Field f = c.getField(key);
if(f != null){
if(key.equals("avatar")){
uploadFile();
}
f.set(user, super.body.get(key));
}
}
user.update();
However, I keep getting the NoSuchFieldException and my code stops working. How can I deal with the possibility of a field not existing?
Related
I have an arraylist i.e.
ArrayList<Integer> getStoresId = [1845, 1846, 1847]
Now I have to execute an end point everytime on each of these id's,
e.g. End point is like this:
https://endpoint/stores/1845/timeEntries,
and i have use this on every storeID.
for which I am using following logic:
public static JSONObject getAllTimeClocks() throws IOException, UnirestException {
ArrayList<Integer> getStoresId = [1845, 1846, 1847]
HttpResponse<JsonNode> bodyResponse = null;
for (Integer id : getStoresId) {
bodyResponse = Unirest.get(url + id + "/TimeClockEntries").header("x-access-token", token).asJson();
}
assert bodyResponse != null;
return bodyResponse.getBody().getObject();
}
and everytime, it is returning me 'null', I need to know, what I am doing wrong.
NOTE: Many of things here are not shared, i.e. token, url etc.
I need to batch elements that have similar client id (String type, but at the moment only numeric values, like "12345", "235134", etc.)
Map<String, List<Client>> _batched = new HashMap<String, List<Client>>();
for (Client c : _Clients)
{
String id = c.getIdClient();
List<Client> clients = _batched.get(id);
if(_clients == null){
clients = new ArrayList<Client>();
_batched.put(id, clients);
}
clients.add(c);
}
The problem is that when I compare this function with the results of Excel (=SUM(IF(FREQUENCY(C2:C618,C2:C618)>0,1))), then I get different results, i.e. 526 and 519.
Is something wrong with my code?
Your problem is here:
String id = c.getIdClient();
List<Client> _clients = _batched.get(id);
if(_clients == null){
pois = new ArrayList<Client>();
_batched.put(id, _clients);
}
_clients.add(c);
You create a new array into a variable called pois but then put the contents of the variable _clients into _batched. What happens with the value put into pois?
I don't understand how that doesn't null pointer exception actually.
I have a properties file with all the fields. dynamically I need to draw the text box with fields as read from the properties file and enter values and post it to controller in spring - java !
Example Properties File
name=String
age=int
address=string
How can I do this from java code..
For my idea, I will do it as below:
Using ajax to get fields from property file on server and return a list of field and type of field in a json format (key, value).
Now we have the data of those fields, then we generate them to your form using jquery or javascript.
Submit the form to server to get value.
Step 1 and 2 are quite easy, so I do not post the code; for step 3, you can try the method below to parse the params in query string to a map.
public static Map getMapFromQueryString(String queryString) {
Map returnMap = new HashMap();
StringTokenizer stringTokenizer = new StringTokenizer(queryString, "&");
while (stringTokenizer.hasMoreTokens()) {
String key, value;
String keyAndValue = stringTokenizer.nextToken();
int indexOfEqual = keyAndValue.indexOf("=");
if (indexOfEqual >= 0) {
key = keyAndValue.substring(0, indexOfEqual);
if ((indexOfEqual + 1) < keyAndValue.length()) {
value = keyAndValue.substring(indexOfEqual + 1);
} else {
value = "";
}
} else {
key = keyAndValue;
value = "";
}
if (key.length() > 0) returnMap.put(key, value);
}
return returnMap;
}
Now you can get all the value of dynamic fields on the form.
Hope this solution is helpful for you.
I am trying to obtain a field's value via reflection. The problem is I don't know the field's type and have to decide it while getting the value.
This code results with this exception:
Can not set java.lang.String field com....fieldName to java.lang.String
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Class<?> targetType = field.getType();
Object objectValue = targetType.newInstance();
Object value = field.get(objectValue);
I tried to cast, but I get compilation errors:
field.get((targetType)objectValue)
or
targetType objectValue = targetType.newInstance();
How can I do this?
Like answered before, you should use:
Object value = field.get(objectInstance);
Another way, which is sometimes prefered, is calling the getter dynamically. example code:
public static Object runGetter(Field field, BaseValidationObject o)
{
// MZ: Find the correct method
for (Method method : o.getMethods())
{
if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3)))
{
if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase()))
{
// MZ: Method found, run it
try
{
return method.invoke(o);
}
catch (IllegalAccessException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
catch (InvocationTargetException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
}
}
}
return null;
}
Also be aware that when your class inherits from another class, you need to recursively determine the Field. for instance, to fetch all Fields of a given class;
for (Class<?> c = someClass; c != null; c = c.getSuperclass())
{
Field[] fields = c.getDeclaredFields();
for (Field classField : fields)
{
result.add(classField);
}
}
You should pass the object to get method of the field, so
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Object value = field.get(object);
I use the reflections in the toString() implementation of my preference class to see the class members and values (simple and quick debugging).
The simplified code I'm using:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
Class<?> thisClass = null;
try {
thisClass = Class.forName(this.getClass().getName());
Field[] aClassFields = thisClass.getDeclaredFields();
sb.append(this.getClass().getSimpleName() + " [ ");
for(Field f : aClassFields){
String fName = f.getName();
sb.append("(" + f.getType() + ") " + fName + " = " + f.get(this) + ", ");
}
sb.append("]");
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
I hope that it will help someone, because I also have searched.
Although it's not really clear to me what you're trying to achieve, I spotted an obvious error in your code:
Field.get() expects the object which contains the field as argument, not some (possible) value of that field. So you should have field.get(object).
Since you appear to be looking for the field value, you can obtain that as:
Object objectValue = field.get(object);
No need to instantiate the field type and create some empty/default value; or maybe there's something I missed.
Integer typeValue = 0;
try {
Class<Types> types = Types.class;
java.lang.reflect.Field field = types.getDeclaredField("Type");
field.setAccessible(true);
Object value = field.get(types);
typeValue = (Integer) value;
} catch (Exception e) {
e.printStackTrace();
}
`
//Here is the example I used for get the field name also the field value
//Hope This will help to someone
TestModel model = new TestModel ("MyDate", "MyTime", "OUT");
//Get All the fields of the class
Field[] fields = model.getClass().getDeclaredFields();
//If the field is private make the field to accessible true
fields[0].setAccessible(true);
//Get the field name
System.out.println(fields[0].getName());
//Get the field value
System.out.println(fields[0].get(model));
`
I post my solution in Kotlin, but it can work with java objects as well.
I create a function extension so any object can use this function.
fun Any.iterateOverComponents() {
val fields = this.javaClass.declaredFields
fields.forEachIndexed { i, field ->
fields[i].isAccessible = true
// get value of the fields
val value = fields[i].get(this)
// print result
Log.w("Msg", "Value of Field "
+ fields[i].name
+ " is " + value)
}}
Take a look at this webpage: https://www.geeksforgeeks.org/field-get-method-in-java-with-examples/
Was able to access private fields in a class using following method
Beneficiary ben = new Beneficiary();//class with multiple fields
ben.setName("Ashok");//is set by a setter
//then to get that value following was the code which worked for me
Field[] fields = ben.getClass().getDeclaredFields();
for(Field field: fields) {
field.setAccessible(true);//to access private fields
System.out.println(field.get(ben));//to get value
//assign value for the same field.set(ben, "Y");//to set value
}
You are calling get with the wrong argument.
It should be:
Object value = field.get(object);
I have two emf models A and B where B only differs from A because it has an extra child node.
Now I would like to use emf compare from code to do:
1) Read model A and B and create model C which is a merged model from A and B. Basically this corresponds to A + the extra nodes from B.
I have looked at:
http://dev.eclipse.org/viewcvs/viewvc.cgi/org.eclipse.emf/org.eclipse.emf.compare/examples/org.eclipse.emf.compare.examples.standalone/src/org/eclipse/emf/compare/examples/standalone/ExampleLauncher.java?view=co&root=Modeling_Project
But I don't see how I can compute the final merged model using the code:
DiffModel diff = CompareUtils.compare(model1, model2, Collections.<String, Object> emptyMap());
CompareUtils.merge(diff);
Any examples that shows how to compute the merged model??
I have now tried:
private void bob() {
ResourceSet resourceSet = new ResourceSetImpl();
Map extensionMap = (Map) resourceSet.getResourceFactoryRegistry()
.getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl());
try {
Region region01 = StatemachineFactoryImpl.eINSTANCE.createRegion();
addResourceToModel(resourceSet, region01, "st1.xmi");
State state01 = StatemachineFactoryImpl.eINSTANCE.createState();
state01.setName("aaaa");
region01.getState().add(state01);
if (state01.eResource() == null) {
System.out.println("state01 NOT contained in resource!");
return;
}
Region region02 = StatemachineFactoryImpl.eINSTANCE.createRegion();
addResourceToModel(resourceSet, region02, "st2.xmi");
State state02 = StatemachineFactoryImpl.eINSTANCE.createState();
state02.setName("bbbb");
region02.getState().add(state02);
if (state02.eResource() == null) {
System.out.println("state02 NOT contained in resource!");
return;
}
final MatchModel match = MatchService.doMatch(region01, region02,
Collections.<String, Object> emptyMap());
final DiffModel diff = DiffService.doDiff(match, false);
final List<DiffElement> differences = new ArrayList<DiffElement>(
diff.getOwnedElements());
MergeService.merge(differences, true);
// Prints the results
addResourceToModel(resourceSet, match, "match.xmi");
addResourceToModel(resourceSet, diff, "diff.xmi");
if (match.eResource() != null)
System.out.println(ModelUtils.serialize(match)); // Throws an
// exception!
if (diff.eResource() != null)
System.out.println(ModelUtils.serialize(diff));
} catch (final InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void addResourceToModel(ResourceSet resourceSet, EObject obj,
String path) {
Resource res = resourceSet.createResource(URI.createURI(path));
res.getContents().add(obj);
}
But the line:
if (match.eResource() != null)
System.out.println(ModelUtils.serialize(match)); // Throws an
// exception!
even though match.eResource() != null
I get this error:
org.eclipse.emf.ecore.resource.Resource$IOWrappedException: The object 'statemachine.impl.StateImpl#11ce012 (name: bbbb)' is not contained in a resource.
at org.eclipse.emf.ecore.xmi.impl.XMLSaveImpl.endSave(XMLSaveImpl.java:306)
at org.eclipse.emf.ecore.xmi.impl.XMLSaveImpl.save(XMLSaveImpl.java:235)
at org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl.doSave(XMLResourceImpl.java:254)
at org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl.save(XMLResourceImpl.java:229)
at org.eclipse.emf.compare.util.ModelUtils.serialize(ModelUtils.java:429)
I have added Region to a resource based on the documentation here:
http://wiki.eclipse.org/index.php/EMF-FAQ#I_get_a_DanglingHREFException:e.g..2C.22org.eclipse.emf.ecore.xmi.DanglingHREFException:_The_object_.27com.example.Foo.402f5dda_.28.29.27_is_not_contained_in_a_resource..22_What_do_I_need_to_do.3F
and the State is contained in the Region so I don't understand why I get the exception...any ideas?
Tul,
The stack trace you get means that one of the 'merged' objects is not contained into a resource : when merging, we copy an object that references a statemachine (which name is 'bbbb'), we then need to reference this state machine from the copied object ... and that statemachine we reference (is it copied or directly referenced from your other model? You should debug to see this) isn't itself contained in any resource.
State state02 = StatemachineFactoryImpl.eINSTANCE.createState();
state02.setName("bbbb");
region02.getState().add(state02);
if (state02.eResource() == null) {
System.out.println("state02 NOT contained in resource!");
return;
}
This should ensures that "bbbb" is indeed contained in a resource.
After this line :
MergeService.merge(differences, true);
Could you try to check once more if "state02.eResource() == null" ? If it is, then that is your issue. Otherwise, you'll have to make sure that this doesn't return :
for (State state : region01.getState()) {
if (state.eResource() == null) {
System.err.println(state.getName() + " is not contained in a resource);
return;
}
}
What about this?
Model1 targetModel = EcoreUtil.copy(model1);
addResourceToModel(targetModel) // assign the copied model to a resource
MatchModel match = MatchService.doMatch(targetModel, model2,
Collections.<String, Object> emptyMap());
DiffModel diff = DiffService.doDiff(match, false);
EList<DiffElement> differences = diff.getDifferences();
for (DiffElement diffElement : differences) {
MergeService.merge(diffElement, true);
}
Your exception:" org.eclipse.emf.ecore.resource.Resource$IOWrappedException: The object 'statemachine.impl.StateImpl#11ce012 (name: bbbb)' is not contained in a resource.". The StateImpl#11ce012 (name: bbbb) is in one resource named st2.xmi,but the match elememt is in another resource named "match.xml". The two resources are different and they do not refer each other. So the match element can NOT refer StateImpl. To solve this problem, all elements(state01, state02, match, diff) must be saved in ONE resource. The code is:
res.getContents().add(stat01);
res.getContents().add(stat02);
res.getContents().add(match);
res.getContents().add(diff);
By the way, the condition "state02.eResource() == null" is not nessary.