Get hashmap using reflection Java, code error - java

I am attempting to load the corresponding hashmap using reflection. However I get a field not found exception. Please let me know what you think the issue is. Thanks
//Find the map
HashMap<String, Matches> map = null;
//Reflection to find the appropriate map
try {
Field field = Field.class.getField(mapName); //exception (mapname = lookupHashmap) this class has a lookupHashmap declared)
try {
//Set the map
map = (HashMap<String, Matches>)field.get(this); //Not sure if this is correct
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Stack trace
java.lang.NoSuchFieldException: majorFieldLookup
at java.lang.Class.getField(Class.java:1522)
at MatchingGraph.getResultsForMap(MatchingGraph.java:245)
at MatchingGraph.getmajorFieldMatches(MatchingGraph.java:196)
at Matcher.findMatches(Matcher.java:95)
at Tester.main(Tester.java:27)

You do not want Field.class.getField(mapName);
You want to use whatever class it is you have the map on, call it 'MyClass'
Field field = MyClass.class.getDeclaredField(mapName);
Edit: changed to getDeclaredField(...) from getField(..) because the field was private.

#Rolfl solved your problem i guess.
And I'm suggesting Apache Commons BeanUtils.
And use the method
BeanUtils.copyProperties(source, target);
http://commons.apache.org/proper/commons-beanutils/

Related

Error accessing Cassandra MBeans from Java

I'm trying to access the messaging metrics provided by Cassandra from Java using JMX. I get the correct results when I use the following query with swiss java knife
java -jar sjk-plus-0.4.2.jar mx -s localhost:7100 -mg -all -b org.apache.cassandra.metrics:type=Messaging,name=* -f Mean
org.apache.cassandra.metrics:type=Messaging,name=CrossNodeLatency
1331.0469921040174
org.apache.cassandra.metrics:type=Messaging,name=datacenter1-Latency
1331.1071897694487
However, with the following Java code I get a javax.management.InstanceNotFoundException: org.apache.cassandra.metrics:type=Messaging exception.
JMXServiceURL url = null;
try {
url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://127.0.0.1:7100/jmxrmi");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JMXConnector mConnector = null;
try {
mConnector = JMXConnectorFactory.connect(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MBeanServerConnection mMBSC = null;
try {
mMBSC = mConnector.getMBeanServerConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ObjectName mObjectName = null;
try {
mObjectName = new ObjectName("org.apache.cassandra.metrics:type=Messaging");
} catch (MalformedObjectNameException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Set<ObjectName> myMbean = null;
try {
myMbean = mMBSC.queryNames(mObjectName, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println((mMBSC.getAttribute(mObjectName, "*")).toString());
} catch (AttributeNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstanceNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MBeanException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ReflectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Could someone please explain where am I making a mistake?
Swiss Java Knife seems to accept an ObjectName wildcard (or pattern) as:
org.apache.cassandra.metrics:type=Messaging,name=*
but your code is simply looking up a non-pattern MBean as:
org.apache.cassandra.metrics:type=Messaging
Change your code to:
Use the pattern
queryNames will return a Set of matching ObjectNames, so iterate through the set and query each one.
You need to specify a string array of actual MBean attribute names, not "*" as in your code. (It would be nice if that was supported)
Something like:
mObjectName = new ObjectName("org.apache.cassandra.metrics:type=Messaging,name=*");
Set<ObjectName> names = mMBSC.queryNames(mObjectName, null);
for(ObjectName on: names) {
System.out.println(on + "\n" + mMBSC.getAttribute(on, "Mean").toString());
}

How to set nested mapping for elastic search index using Java API?

I would like to leverage nested object indexing in Elastic Search. I know how to do that with PUT requests through curl (https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-mapping.html) but I would like to do that through Java API instead.
Here is how I create dynamically my index
public void index(AnObject obj){
Client client = elasticService.getES();
// generate json
if (client != null){
try {
byte[] json = JSON.serializeAsBytes(obj);
IndexResponse response = client.prepareIndex("titan", "objIndex", obj.getUuid())
.setSource(json)
.get();
} catch (ElasticsearchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and here is how I update it
public void updateIndex(AnObject obj){
Client client = elasticService.getES();
// generate json
if (client != null){
try {
byte[] json = JSON.serializeAsBytes(obj);
UpdateResponse response = client.prepareUpdate("titan", "objIndex", obj.getUuid())
.setDoc(json)
.get();
} catch (ElasticsearchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I wonder if there is a way to set my index through Java so that specific or all of the embedded objects are mapped as nested
If that is not possible is it possible to configure Elastic search default mapping to index everything as datatype nested?
Any help is appreciated! Thanks!

Java Advanced Reflection

So I have class Foo in package com.one.
//package com.one
class Foo{
protected static void a(){
//...
}
}
and class Bar in package com.two extending Foo
//package com.two
class Bar extends Foo{
//...
}
Can I use reflection, if I'm inside com.two, to make a() not protected, and then call it?
Yes you can. Just grab this method and use setAccessible with true.
To grab this method you can't use setDeclaredMethod nor getMethod from subclass, because it wasn't declared there or is not public. Easiest way to get it is to do it via superclass like
Method method = Foo.class.getDeclaredMethod("a");
or
Method method = Bar.class.getSuperclass().getDeclaredMethod("a");
// ^^^^^^^^^^^^^ assuming that `a` is declared in superclass,
// it is possible that you may want to use
// `getSuperclass` few more times
then you can just call
method.setAccessible(true);
to change its accessibility and use it
method.invoke(null);//static methods require no instance.
Yes, you should be able to use reflection for it. Write below code:
try {
Method method = Foo.class.getDeclaredMethod("a");
method.setAccessible(true);
try {
method.invoke(null);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Adding components via reflection in swing?

This is probably a very silly way to go about things, but say we had a class with lots of Fields that were components, how would one go about adding them in a for each loop with reflection?
Here is what I've tried so far (though it is obviously doomed to fail):
for(Field bits: this.getClass().getDeclaredFields()){
try {
this.add((Component)Class.forName(bits.getName()).newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Each of the fields is not a class so doing the above will not work, but I have defined what they are, and they should exist at runtime.
How should I be doing this?
You try to create a class from a field name, so it won't work.
bits.getName() returns something like "myHelloWorldLabel" and not javax.swing.JLabel.
You can either add the value of the field bits.get(this) or create a new object from the class bits.getDeclaringClass().newInstance().
I would also add a check that the class extends JComponent.

Android - Facebook: an active access token must be used to query information about the current user

i'm using this code:
if(!facebook.isSessionValid()) {
try {
String jsonUser = facebook.request("me");
obj = Util.parseJson(jsonUser);
String id = obj.optString("id");
String name = obj.optString("name");
tv1.setText("sodfnsdf");
} catch (MalformedURLException e) {
tv1.setText("1");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
tv1.setText("2");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
tv1.setText("3");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
tv1.setText("4");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
tv1.setText("Error");
}
i've searched online and in stackoverflow, but cannot find the answer to my question, i only found very similiar questions but different in some ways..
Hey you need to call facebook.authorize method
if(!facebook.isSessionValid()) {
facebook.authorize() }
For more information you can refer this link. I think it will help you.
Visit http://www.techrepublic.com/blog/app-builder/integrate-facebook-logins-in-your-android-app/296

Categories

Resources