public RefStaticMethod(Class<?> cls, Field field) {
try {
if (field.isAnnotationPresent(MethodParams.class)) {
Class<?>[] types = field.getAnnotation(MethodParams.class).value();
for (int i = 0; i < types.length; i++) {
Class<?> clazz = types[i];
if (clazz.getClassLoader() == getClass().getClassLoader()) {
try {
Class.forName(clazz.getName());
Class<?> realClass = (Class<?>) clazz.getField("TYPE").get(null);
types[i] = realClass;
} catch (Throwable e){
Log.e("hello", "RefStaticMethod: 1" );
throw new RuntimeException(e);
}
}
}
this.method = cls.getDeclaredMethod(field.getName(), types);
this.method.setAccessible(true);
} else if (field.isAnnotationPresent(MethodReflectParams.class)) {
boolean arrayset = false;
String[] typeNames = field.getAnnotation(MethodReflectParams.class).value();
Class<?>[] types = new Class<?>[typeNames.length];
Class<?>[] types2 = new Class<?>[typeNames.length];
for (int i = 0; i < typeNames.length; i++) {
Class<?> type = getProtoType(typeNames[i]);
if (type == null) {
try {
type = Class.forName(typeNames[i]);
} catch (ClassNotFoundException e) {
Log.e("hello", "RefStaticMethod: 2" );
e.printStackTrace();
}
}
types[i] = type;
if ("java.util.HashSet".equals(typeNames[i])) {
arrayset = true;
Class<?> type2 = type;
try {
type2 = Class.forName("android.util.ArraySet");
} catch (ClassNotFoundException e) {
Log.e("hello", "RefStaticMethod: 3" );
e.printStackTrace();
}
if (type2 != null) {
types2[i] = type2;
} else {
types2[i] = type;
}
} else {
types2[i] = type;
}
}
try {
this.method = cls.getDeclaredMethod(field.getName(), types);
} catch (Exception e) {
Log.e("hello", "RefStaticMethod: 4 "+e.toString() );
e.printStackTrace();
if (arrayset) {
this.method = cls.getDeclaredMethod(field.getName(), types2);
}
}
this.method.setAccessible(true);
} else {
for (Method method : cls.getDeclaredMethods()) {
if (method.getName().equals(field.getName())) {
this.method = method;
this.method.setAccessible(true);
break;
}
}
}
if (this.method == null) {
throw new NoSuchMethodException(field.getName());
}
}
catch(Exception e)
{
Log.e("hello", "RefStaticMethod: 5 "+e.toString());
}
}
Logcat error:
2019-07-02 03:01:01.893 29833-29861/io.virtualapp:x E/hello:
RefStaticMethod: 4 java.lang.NoSuchMethodException:
collectCertificates [class android.content.pm.PackageParser$Package,
int] 2019-07-02 03:01:01.896 29833-29861/io.virtualapp:x E/hello:
RefStaticMethod: 5 java.lang.NullPointerException: Attempt to invoke
virtual method 'void java.lang.reflect.Method.setAccessible(boolean)'
on a null object reference
have any solution for android 9(PIE) or any alternative way to resolve this issue of getDeclaredMethod. thanks in advance
Related
I want to know some of the reasons that can cause below exception. I am unable to find this message Cannot find message in jsch-0.1.54.jar. There exists some straight forward messages like file not found and others that make sense. But I need more information about this one so that I can reach to the root cause.
SftpException while running get ---> 2: Cannot find message [/destination/file.txt]
at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2289)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:1741)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:1758)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:786)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:750)
at com.iyi.ftp.SFTP.get(SFTP.java:99)
Here is my calling method.
public boolean get(final String remoteFile, final String localFile) throws JSchException {
Vector connection = null;
Session session = null;
ChannelSftp c = null;
boolean status = false;
try {
connection = this.connect();
session = connection.get(0);
c = connection.get(1);
c.get(remoteFile, localFile);
status = true;
}
catch (JSchException e) {
SFTP.LGR.warn((Object)("JSchException in SFTP::get() ---> " + FTPFactory.getStackTrace((Throwable)e)));
throw e;
}
catch (SftpException e2) {
SFTP.LGR.warn((Object)("SftpException while running get ---> " + FTPFactory.getStackTrace((Throwable)e2)));
throw new JSchException(e2.getMessage());
}
catch (CredentialDecryptionException e3) {
SFTP.LGR.error((Object)"##CredentialDecryptionException##", (Throwable)e3);
throw new JSchException(e3.getMessage(), (Throwable)e3);
}
finally {
if (c != null) {
c.quit();
}
if (session != null) {
session.disconnect();
}
}
if (c != null) {
c.quit();
}
if (session != null) {
session.disconnect();
}
return status;
}
These methods are fetched from jsch-0.1.54.jar which is an open source utility.
public void get(String src, String dst, final SftpProgressMonitor monitor, final int mode) throws SftpException {
boolean _dstExist = false;
String _dst = null;
try {
((MyPipedInputStream)this.io_in).updateReadSide();
src = this.remoteAbsolutePath(src);
dst = this.localAbsolutePath(dst);
final Vector v = this.glob_remote(src);
final int vsize = v.size();
if (vsize == 0) {
throw new SftpException(2, "No such file");
}
final File dstFile = new File(dst);
final boolean isDstDir = dstFile.isDirectory();
StringBuffer dstsb = null;
if (isDstDir) {
if (!dst.endsWith(ChannelSftp.file_separator)) {
dst += ChannelSftp.file_separator;
}
dstsb = new StringBuffer(dst);
}
else if (vsize > 1) {
throw new SftpException(4, "Copying multiple files, but destination is missing or a file.");
}
for (int j = 0; j < vsize; ++j) {
final String _src = v.elementAt(j);
final SftpATTRS attr = this._stat(_src);
if (attr.isDir()) {
throw new SftpException(4, "not supported to get directory " + _src);
}
_dst = null;
if (isDstDir) {
final int i = _src.lastIndexOf(47);
if (i == -1) {
dstsb.append(_src);
}
else {
dstsb.append(_src.substring(i + 1));
}
_dst = dstsb.toString();
if (_dst.indexOf("..") != -1) {
final String dstc = new File(dst).getCanonicalPath();
final String _dstc = new File(_dst).getCanonicalPath();
if (_dstc.length() <= dstc.length() || !_dstc.substring(0, dstc.length() + 1).equals(dstc + ChannelSftp.file_separator)) {
throw new SftpException(4, "writing to an unexpected file " + _src);
}
}
dstsb.delete(dst.length(), _dst.length());
}
else {
_dst = dst;
}
final File _dstFile = new File(_dst);
if (mode == 1) {
final long size_of_src = attr.getSize();
final long size_of_dst = _dstFile.length();
if (size_of_dst > size_of_src) {
throw new SftpException(4, "failed to resume for " + _dst);
}
if (size_of_dst == size_of_src) {
return;
}
}
if (monitor != null) {
monitor.init(1, _src, _dst, attr.getSize());
if (mode == 1) {
monitor.count(_dstFile.length());
}
}
FileOutputStream fos = null;
_dstExist = _dstFile.exists();
try {
if (mode == 0) {
fos = new FileOutputStream(_dst);
}
else {
fos = new FileOutputStream(_dst, true);
}
this._get(_src, fos, monitor, mode, new File(_dst).length());
}
finally {
if (fos != null) {
fos.close();
}
}
}
}
catch (Exception e) {
if (!_dstExist && _dst != null) {
final File _dstFile2 = new File(_dst);
if (_dstFile2.exists() && _dstFile2.length() == 0L) {
_dstFile2.delete();
}
}
if (e instanceof SftpException) {
throw (SftpException)e;
}
if (e instanceof Throwable) {
throw new SftpException(4, "", e);
}
throw new SftpException(4, "");
}
}
private SftpATTRS _stat(final byte[] path) throws SftpException {
try {
this.sendSTAT(path);
Header header = new Header();
header = this.header(this.buf, header);
final int length = header.length;
final int type = header.type;
this.fill(this.buf, length);
if (type != 105) {
if (type == 101) {
final int i = this.buf.getInt();
this.throwStatusError(this.buf, i);
}
throw new SftpException(4, "");
}
final SftpATTRS attr = SftpATTRS.getATTR(this.buf);
return attr;
}
catch (Exception e) {
if (e instanceof SftpException) {
throw (SftpException)e;
}
if (e instanceof Throwable) {
throw new SftpException(4, "", e);
}
throw new SftpException(4, "");
}
}
The error message comes from your server. It's indeed quite strange message, but I assume that it's some custom SFTP server that deals with some "messages" rather than plain files.
So the message basically translates to "Cannot find file" error of a traditional SFTP server. Even the error code 2 (SSH_FX_NO_SUCH_FILE) supports that.
Your path in remoteFile is probably wrong.
I am trying to reflect a json to class. But i have problem when i have JsonArray inside of JsonArray with object's. It seems that is trying to find a class like List<Step> but cannot found.
My output is :
W/System.err: Value ... at steps of type org.json.JSONArray cannot be converted to JSONObject
My class is like:
class Step {
private Consecutive consecutive;
private List<List<Steps>> steps = null;
}
a part of my Json :
{"step":{"consecutive":{"enabled":true,"period":"day"},"steps":[[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}],[{"points":100},{"points":200},{"points":300},{"points":400}]]}}
My Json Parser :
public static Object populateObjectFromJSON(Class<?> classname, JSONObject js) {
Object obj = null;
System.out.println("Populating " + classname.getSimpleName() + " -with- " + js.toString());
try {
obj = classname.newInstance();
} catch (InstantiationException e1) {
System.err.println(e1.getMessage());
return null;
} catch (IllegalAccessException e1) {
System.err.println(e1.getMessage());
return null;
}
Field[] fields;
if (privacy == 0) {
fields = classname.getFields();
} else {
fields = classname.getDeclaredFields();
}
for (Field f : fields) {
// System.out.println("Declared " + f.getName());
if ((privacy == 2) && (Modifier.isPrivate(f.getModifiers()))) {
f.setAccessible(true);
}
try {
if (js.has(f.getName())) {
String type = f.getType().getSimpleName();
if (type.equalsIgnoreCase("boolean")) {
f.setBoolean(obj, js.getBoolean(f.getName()));
} else if (type.equalsIgnoreCase("int")) {
f.setInt(obj, js.getInt(f.getName()));
} else if (type.equalsIgnoreCase("double")) {
f.setDouble(obj, js.getDouble(f.getName()));
} else if (type.equalsIgnoreCase("float")) {
f.setFloat(obj, (float) js.getDouble(f.getName()));
} else if (type.equalsIgnoreCase("string")) {
f.set(obj, js.getString(f.getName()));
} else if (f.getType().isArray()) {
f.set(obj, Array.newInstance(f.getType().getComponentType(), js.getJSONArray(f.getName()).length()));
insertArrayFromJSON(f.get(obj), js.getJSONArray(f.getName()));
}else{
f.set(obj, populateObjectFromJSON(f.getType(), js.getJSONObject(f.getName())));
}
}
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
} catch (IllegalAccessException e) {
System.err.println(e.getMessage());
} catch (JSONException e) {
System.err.println(e.getMessage());
}
if ((privacy == 2) && (Modifier.isPrivate(f.getModifiers()))) {
f.setAccessible(false);
}
}
return obj;
}
thanks
I'm trying to sort a JSONArray but I'm getting the following error:
Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(TimSort.java:895)
at java.util.TimSort.mergeAt(TimSort.java:512)
at java.util.TimSort.mergeForceCollapse(TimSort.java:453)
at java.util.TimSort.sort(TimSort.java:250)
at java.util.Arrays.sort(Arrays.java:1523)
at java.util.Collections.sort(Collections.java:238)
Here is my code:
private JSONArray SortJSONArray(String json) {
JSONArray sortedJsonArray = new JSONArray();
try {
JSONArray jsonArr = new JSONArray(json);
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
Collections.sort(jsonValues, new Comparator<JSONObject>() {
private static final String KEY_NAME = "EUR";
#Override
public int compare(JSONObject a, JSONObject b) {
Double valA = 0.0;
Double valB = 0.0;
try {
valA = a.getDouble(KEY_NAME);
valB = b.getDouble(KEY_NAME);
} catch (JSONException e) {
Log.e("MainActivity", e.getMessage());
}
if(valA < valB) {
return -1;
} else if( valB < valA) {
return 1;
} else {
return 0;
}
}
});
for (int i = 0; i < jsonArr.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
} catch (JSONException e) {
Log.e("MainActivity", e.getMessage());
}
return sortedJsonArray;
}
The issue is that either a.getDouble(KEY_NAME) or b.getDouble(KEY_NAME) can throw an exception.
If a.getDouble(KEY_NAME) throws an exception and b.getDouble(KEY_NAME) does not, b.getDouble(KEY_NAME) is never evaluated and both valA and valB remain 0.0.
On the other hand, if you compare a and b is reversed order (i.e. call compare(b,a) instead of compare(a,b), b.getDouble(KEY_NAME) will be evaluated before a.getDouble(KEY_NAME) throws an exception, so valA will be 0.0 and valB will have some other value.
In that case compare(a,b) will return 0 and compare(b,a) will return a non-zero value (assuming b.getDouble(KEY_NAME) doesn't return 0.0), which violates the contract of Comparator.
Evaluating a.getDouble(KEY_NAME) and b.getDouble(KEY_NAME) in separate try blocks will resolve the issue.
try {
valA = a.getDouble(KEY_NAME);
} catch (JSONException e) {
Log.e("MainActivity", e.getMessage());
}
try {
valB = b.getDouble(KEY_NAME);
} catch (JSONException e) {
Log.e("MainActivity", e.getMessage());
}
return Double.compare(valA,valB);
Workaround is to return a value in the catch statement:
try {
valA = a.getDouble(KEY_NAME);
valB = b.getDouble(KEY_NAME);
} catch (JSONException e) {
Log.e("MainActivity", e.getMessage());
return -10;
}
if(valA < valB) {
return -1;
} else if( valB < valA) {
return 1;
} else {
return 0;
}
my app uses another projects which contains references to classes as java.beans.propertydescriptor which is not contained by android libraries.
The situation is the next: my project contains the .jar files with this another projects as libraries. I read that the solution is use an opensource class. I found it, but i dont know how can i add this class to the android .jar file. So, how can i add this class to the android java.beans library?
This is the class i have found:
package java.beans;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Vector;
import org.apache.harmony.beans.internal.nls.Messages;
public class PropertyDescriptor extends FeatureDescriptor {
private Method getter;
private Method setter;
private Class<?> propertyEditorClass;
private boolean constrained;
private boolean bound;
public PropertyDescriptor(String propertyName, Class<?> beanClass,
String getterName, String setterName) throws IntrospectionException {
super();
if (beanClass == null) {
throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$
}
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
if (setterName != null) {
if (hasMethod(beanClass, setterName)) {
setWriteMethod(beanClass, setterName);
} else {
throw new IntrospectionException(Messages.getString("beans.20")); //$NON-NLS-1$
}
}
if (getterName != null) {
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
} else {
throw new IntrospectionException(Messages.getString("beans.1F")); //$NON-NLS-1$
}
}
}
public PropertyDescriptor(String propertyName, Method getter, Method setter)
throws IntrospectionException {
super();
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
setWriteMethod(setter);
setReadMethod(getter);
}
public PropertyDescriptor(String propertyName, Class<?> beanClass)
throws IntrospectionException {
String getterName;
String setterName;
if (beanClass == null) {
throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$
}
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
getterName = createDefaultMethodName(propertyName, "is"); //$NON-NLS-1$
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
} else {
getterName = createDefaultMethodName(propertyName, "get"); //$NON-NLS-1$
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
}
}
setterName = createDefaultMethodName(propertyName, "set"); //$NON-NLS-1$
if (hasMethod(beanClass, setterName)) {
setWriteMethod(beanClass, setterName);
}
if (getter == null && setter == null) {
throw new IntrospectionException(Messages.getString(
"beans.01", propertyName)); //$NON-NLS-1$
}
}
public void setWriteMethod(Method setter) throws IntrospectionException {
if (setter != null) {
int modifiers = setter.getModifiers();
if (!Modifier.isPublic(modifiers)) {
throw new IntrospectionException(Messages.getString("beans.05")); //$NON-NLS-1$
}
Class<?>[] parameterTypes = setter.getParameterTypes();
if (parameterTypes.length != 1) {
throw new IntrospectionException(Messages.getString("beans.06")); //$NON-NLS-1$
}
Class<?> parameterType = parameterTypes[0];
Class<?> propertyType = getPropertyType();
if (propertyType != null && !propertyType.equals(parameterType)) {
throw new IntrospectionException(Messages.getString("beans.07")); //$NON-NLS-1$
}
}
this.setter = setter;
}
public void setReadMethod(Method getter) throws IntrospectionException {
if (getter != null) {
int modifiers = getter.getModifiers();
if (!Modifier.isPublic(modifiers)) {
throw new IntrospectionException(Messages.getString("beans.0A")); //$NON-NLS-1$
}
Class<?>[] parameterTypes = getter.getParameterTypes();
if (parameterTypes.length != 0) {
throw new IntrospectionException(Messages.getString("beans.08")); //$NON-NLS-1$
}
Class<?> returnType = getter.getReturnType();
if (returnType.equals(Void.TYPE)) {
throw new IntrospectionException(Messages.getString("beans.33")); //$NON-NLS-1$
}
Class<?> propertyType = getPropertyType();
if ((propertyType != null) && !returnType.equals(propertyType)) {
throw new IntrospectionException(Messages.getString("beans.09")); //$NON-NLS-1$
}
}
this.getter = getter;
}
public Method getWriteMethod() {
return setter;
}
public Method getReadMethod() {
return getter;
}
#Override
public boolean equals(Object object) {
boolean result = (object != null && object instanceof PropertyDescriptor);
if (result) {
PropertyDescriptor pd = (PropertyDescriptor) object;
boolean gettersAreEqual = (this.getter == null)
&& (pd.getReadMethod() == null) || (this.getter != null)
&& (this.getter.equals(pd.getReadMethod()));
boolean settersAreEqual = (this.setter == null)
&& (pd.getWriteMethod() == null) || (this.setter != null)
&& (this.setter.equals(pd.getWriteMethod()));
boolean propertyTypesAreEqual = this.getPropertyType() == pd
.getPropertyType();
boolean propertyEditorClassesAreEqual = this
.getPropertyEditorClass() == pd.getPropertyEditorClass();
boolean boundPropertyAreEqual = this.isBound() == pd.isBound();
boolean constrainedPropertyAreEqual = this.isConstrained() == pd
.isConstrained();
result = gettersAreEqual && settersAreEqual
&& propertyTypesAreEqual && propertyEditorClassesAreEqual
&& boundPropertyAreEqual && constrainedPropertyAreEqual;
}
return result;
}
public void setPropertyEditorClass(Class<?> propertyEditorClass) {
this.propertyEditorClass = propertyEditorClass;
}
public Class<?> getPropertyType() {
Class<?> result = null;
if (getter != null) {
result = getter.getReturnType();
} else if (setter != null) {
Class<?>[] parameterTypes = setter.getParameterTypes();
result = parameterTypes[0];
}
return result;
}
public Class<?> getPropertyEditorClass() {
return propertyEditorClass;
}
public void setConstrained(boolean constrained) {
this.constrained = constrained;
}
public void setBound(boolean bound) {
this.bound = bound;
}
public boolean isConstrained() {
return constrained;
}
public boolean isBound() {
return bound;
}
boolean hasMethod(Class<?> beanClass, String methodName) {
Method[] methods = findMethods(beanClass, methodName);
return (methods.length > 0);
}
String createDefaultMethodName(String propertyName, String prefix) {
String result = null;
if (propertyName != null) {
String bos = propertyName.substring(0, 1).toUpperCase();
String eos = propertyName.substring(1, propertyName.length());
result = prefix + bos + eos;
}
return result;
}
Method[] findMethods(Class<?> aClass, String methodName) {
Method[] allMethods = aClass.getMethods();
Vector<Method> matchedMethods = new Vector<Method>();
Method[] result;
for (Method method : allMethods) {
if (method.getName().equals(methodName)) {
matchedMethods.add(method);
}
}
result = new Method[matchedMethods.size()];
for (int j = 0; j < matchedMethods.size(); ++j) {
result[j] = matchedMethods.elementAt(j);
}
return result;
}
void setReadMethod(Class<?> beanClass, String getterName) {
boolean result = false;
Method[] getters = findMethods(beanClass, getterName);
for (Method element : getters) {
try {
setReadMethod(element);
result = true;
} catch (IntrospectionException ie) {
}
if (result) {
break;
}
}
}
void setWriteMethod(Class<?> beanClass, String setterName)
throws IntrospectionException {
boolean result = false;
Method[] setters = findMethods(beanClass, setterName);
for (Method element : setters) {
try {
setWriteMethod(element);
result = true;
} catch (IntrospectionException ie) {
}
if (result) {
break;
}
}
}
public PropertyEditor createPropertyEditor(Object bean) {
PropertyEditor editor;
if (propertyEditorClass == null) {
return null;
}
if (!PropertyEditor.class.isAssignableFrom(propertyEditorClass)) {
// beans.48=Property editor is not assignable from the
// PropertyEditor interface
throw new ClassCastException(Messages.getString("beans.48")); //$NON-NLS-1$
}
try {
Constructor<?> constr;
try {
// try to look for the constructor with single Object argument
constr = propertyEditorClass.getConstructor(Object.class);
editor = (PropertyEditor) constr.newInstance(bean);
} catch (NoSuchMethodException e) {
// try no-argument constructor
constr = propertyEditorClass.getConstructor();
editor = (PropertyEditor) constr.newInstance();
}
} catch (Exception e) {
// beans.47=Unable to instantiate property editor
RuntimeException re = new RuntimeException(
Messages.getString("beans.47"), e); //$NON-NLS-1$
throw re;
}
return editor;
}
}
Thanks.
I downloaded from this page https://code.google.com/p/openbeans/downloads/detail?name=openbeans-1.0.jar the openbean.jar. Then, i imported this jar to the project and changed the references at imported library.
Then export again the project as .jar library and import in the android project.
Every time I called this method it always return null even if the value of userProfile.get("facebookId") is not null.
public String updateProfilePicture() {
String facebookId = null;
if (currentUser.get("profile") != null) {
JSONObject userProfile = currentUser.getJSONObject("profile");
try {
if (userProfile.getString("facebookId") != null) {
facebookId = userProfile.get("facebookId").toString();
} else {
facebookId = null;
}
} catch (JSONException e) {
// handle error
facebookId = null;
}
}
return facebookId;
}