NoSuchMethodException loading Build.getRadioVersion() using reflection - java

I'm trying to load the radio version of the Android device using reflection. I need to do this because my SDK supports back to API 7, but Build.RADIO was added in API 8, and Build.getRadioVersion() was added in API 14.
// This line executes fine, but is deprecated in API 14
String radioVersion = Build.RADIO;
// This line executes fine, but is deprecated in API 14
String radioVersion = (String) Build.class.getField("RADIO").get(null);
// This line executes fine.
String radioVersion = Build.getRadioVersion();
// This line throws a MethodNotFoundException.
Method method = Build.class.getMethod("getRadioVersion", String.class);
// The rest of the attempt to call getRadioVersion().
String radioVersion = method.invoke(null).toString();
I'm probably doing something wrong here. Any ideas?

Try this:
try {
Method getRadioVersion = Build.class.getMethod("getRadioVersion");
if (getRadioVersion != null) {
try {
String version = (String) getRadioVersion.invoke(Build.class);
// Add your implementation here
} 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();
}
} else {
Log.wtf(TAG, "getMethod returned null");
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

What Build.getRadioVersion() actually does is return the value of gsm.version.baseband system property. Check Build and TelephonyProperties sources:
static final String PROPERTY_BASEBAND_VERSION = "gsm.version.baseband";
public static String getRadioVersion() {
return SystemProperties.get(TelephonyProperties.PROPERTY_BASEBAND_VERSION, null);
}
According to AndroidXref this property is available even in API 4. Thus you may get it on any version of Android through SystemProperties using the reflection:
public static String getRadioVersion() {
return getSystemProperty("gsm.version.baseband");
}
// reflection helper methods
static String getSystemProperty(String propName) {
Class<?> clsSystemProperties = tryClassForName("android.os.SystemProperties");
Method mtdGet = tryGetMethod(clsSystemProperties, "get", String.class);
return tryInvoke(mtdGet, null, propName);
}
static Class<?> tryClassForName(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
return null;
}
}
static Method tryGetMethod(Class<?> cls, String name, Class<?>... parameterTypes) {
try {
return cls.getDeclaredMethod(name, parameterTypes);
} catch (Exception e) {
return null;
}
}
static <T> T tryInvoke(Method m, Object object, Object... args) {
try {
return (T) m.invoke(object, args);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
return null;
}
}

Related

How to mock internal called methods?

Below is code for which i'm trying to write text case and added what i did but getting null pointer exp
public boolean doVersionLimitCheck(Long mneId) throws DMMException {
CALogUtil.getInstance().logMethodEntry("doVersionLimitCheck",
ConfigArchiveManagerImpl.class.getName());
boolean status = false;
status = validateArchivedVersions(mneId);
CALogUtil.getInstance().logDebug("Version Roll over status::" + status);
CALogUtil.getInstance().logMethodExit("doVersionLimitCheck",
ConfigArchiveManagerImpl.class.getName());
return status;
}
for this i did like below.
#Test
public void testDoVersionLimitCheck() {
Long mneId=Long.valueOf("123");
ConfigArchiveManagerImpl impl = new ConfigArchiveManagerImpl();
try {
Mockito.doReturn(true).when(Mockito.mock(ConfigArchiveManagerImpl.class)).validateArchivedVersions(Mockito.anyLong());
} catch (DMMException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
impl.doVersionLimitCheck(mneId);
} catch (DMMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to spy on the SUT in order to test one method and mock the other:
#Test
public void testDoVersionLimitCheck() {
Long mneId=Long.valueOf("123");
ConfigArchiveManagerImpl impl = Mockito.spy(new ConfigArchiveManagerImpl());
try {
Mockito.doReturn(true).when(impl ).validateArchivedVersions(Mockito.anyLong());
} catch (DMMException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

I can't mock static method using Mockito and PowerMockito

I'm having trouble mocking a static method in a third-party library. I keep receiving a null-pointer exception when running the test, but I'm not sure why that is.
Here is the class and the void method that invokes the static method I'm trying to mock "MRClientFactory.createConsumer(props)":
public class Dmaap {
Properties props = new Properties();
public Dmaap() {
}
public MRConsumerResponse createDmaapConsumer() {
System.out.println("at least made it here");
MRConsumerResponse mrConsumerResponse = null;
try {
MRConsumer mrConsumer = MRClientFactory.createConsumer(props);
System.out.println("made it here.");
mrConsumerResponse = mrConsumer.fetchWithReturnConsumerResponse();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mrConsumerResponse;
}
}
Below is the test that keeps returning a null-pointer exception. The specific line where the null-pointer is being generated is: MRClientFactory.createConsumer(Mockito.any(Properties.class));
#RunWith(PowerMockRunner.class)
#PrepareForTest(fullyQualifiedNames = "com.vismark.PowerMock.*")
public class DmaapTest {
#Test
public void testCreateDmaapConsumer() {
try {
Properties props = new Properties();
PowerMockito.mockStatic(MRClientFactory.class);
PowerMockito.doNothing().when(MRClientFactory.class);
MRClientFactory.createConsumer(Mockito.any(Properties.class));
//MRClientFactory.createConsumer(props);
Dmaap serverMatchCtrl = new Dmaap();
Dmaap serverMatchCtrlSpy = spy(serverMatchCtrl);
serverMatchCtrlSpy.createDmaapConsumer();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please follow this example carefully: https://github.com/powermock/powermock/wiki/MockStatic
Especially you are missing a
#PrepareForTest(Dmaap.class)
…to denote the class which does the static call.

How to check if an object has at least one field that is not null?

I have a set of beans that are generated by a third-party library.
How can I check if each bean has at least one field that is not null?
The problem is easily solved using reflection. Just add this method to your bean:
public boolean hasAtLeastOneNonEmpty() {
Class<? extends QueryBean> class1 = this.getClass();
Field[] fields = class1.getDeclaredFields();
for (Field field : fields) {
try {
if (field.get(this) != null) {
return true;
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}

Mismatch of return datatype

i am facing a problem regrading specifying the return data type. I have the FOComp class which implements callabale, the call() method of the 'FOComp' returns data type List<ArrayList<Mat>> as shown in the code of 'FOComp' class below.
and the method 'getResults()' returns data of type ArrayList<Mat> as shown in the code below. and currently, at run time, when I execute the code, I receive the folowing error:
Multiple markers at this line
The return type is incompatible with Callable<ArrayList<Mat>>.call()
The return type is incompatible with Callable<List<Mat>>.call()
kindly please let me know how to fix it.
'FOComp' class:
static class FOComp implements Callable<List<Mat>> {//should return list contains 4 mats(0,45,90,135)
private ArrayList<Mat> gaussianMatList = null;
private List<ArrayList<Mat>> results_4OrientAngles_List = null;
public FOComp(ArrayList<Mat> gaussianMatList) {
// TODO Auto-generated constructor stub
this.gaussianMatList = gaussianMatList;
this.results_4OrientAngles_List = new ArrayList<ArrayList<Mat>>();
}
public List<ArrayList<Mat>> call() throws Exception {
// TODO Auto-generated method stub
try {
featOrient = new FeatOrientation(this.gaussianMatList);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
featOrient.start();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.results_4OrientAngles_List.add(featOrient.getResults());
return results_4OrientAngles_List;
}
}
'getResults':
public ArrayList<Mat> getResults() {
if (this.crossAddOrientMapsList != null) {
if (!this.crossAddOrientMapsList.isEmpty()) {
if (this.crossAddOrientMapsList.size() == 4) {
double[] theta = new double[4];
theta[0] = 0;
theta[1] = 45;
theta[2] = 90;
theta[3] = 135;
for (int i = 0; i < this.crossAddOrientMapsList.size(); i++) {
MatFactory.writeMat(FilePathUtils.newOutputPath("FinalCrossAdd_" + theta[i]+"_degs"), this.crossAddOrientMapsList.get(i));
//ImageUtils.showMat(this.crossAddOrientMapsList.get(i), "OrientMap_" + theta[i] + " degs");
}
return this.crossAddOrientMapsList;
} else {
Log.WTF(TAG, "getResults", "crossAddOrientMapsList != 4 !!");
return null;
}
} else {
Log.E(TAG, "getResults", "crossAddOrientMapsList is empty.");
return null;
}
} else {
Log.E(TAG, "getResults", "crossAddOrientMapsList is null");
return null;
}
}
class FOComp implements Callable<List<Mat>>
and
public List<ArrayList<Mat>> call()
aren't really compatible... Your call() method should be
#Override public List<Mat> call()
Also, it is good practice to avoid implementation classes in method signatures, use the interfaces instead (in this case, use List rather than ArrayList). That will also fix your problem with one of the "multiple markers" :-)
Cheers,
You class declaration says that you are going to return a List of Mat (FOComp implements Callable<List<Mat>>), but your call method signature says you are going to return a List of ArrayList of Mat (List<ArrayList<Mat>>).
You will need to make them consistent.

Databinding in AXIS2

I have created a web service for the following method using AXIS 1.4
public class SoapTest {
public String test(String param) {
System.out.println("soap activity check "+param);
return param+" return from soap";
}
}
I am calling it using AXIS2 Wsdl2java utility. The client i am using is:
public static void main(String argv[]) {
try {
SoapTestServiceStub obj = new SoapTestServiceStub();
SoapTestServiceStub.Test obj2 = new SoapTestServiceStub.Test();
obj2.setParam("hello");
try {
SoapTestServiceStub.TestResponse res = obj.test(obj2);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (AxisFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
On running the client SOP is working fine but then Getting the following error:
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement testReturn
at org.apache.axis2.AxisFault.makeFault

Categories

Resources