Emma instrumenting classes incorrectly - java

From working with EMMA I have noticed that it fails to instrument correctly causing the class to become mangled. Below is a simple example highlighting this issue.
public void showProblem() {
try {
for (int i = 0; i > 10; i++) {
System.out.println(i);
}
} catch (final Throwable e) {
System.err.println(e);
}
}
Instrumented class
public void showProblem()
{
boolean[][] tmp3_0 = $VRc; if (tmp3_0 == null) tmp3_0; boolean[] arrayOfBoolean = $VRi()[1]; int i = 0; arrayOfBoolean[0] = true; tmpTernaryOp = tmp3_0;
try
{
do
{
Throwable e;
System.out.println(e);
e++; arrayOfBoolean[1] = true; arrayOfBoolean[2] = true; } while (e > 10); arrayOfBoolean[3] = true;
}
catch (Throwable localThrowable1)
{
System.err.println(localThrowable1); arrayOfBoolean[4] = true;
}
arrayOfBoolean[5] = true;
}
Notice that it is attempting to increment e of type Throwable and using this within the while loop.
I have found that by moving the try catch logic within the for loop it resolves this. As highlighted in the below code.
public void showProblem() {
for (int i = 0; i > 10; i++) {
try {
System.out.println(i);
} catch (final Throwable e) {
System.err.println(e);
}
}
}
Instrumented class
public void showProblem()
{
boolean[][] tmp3_0 = $VRc; if (tmp3_0 == null) tmp3_0; boolean[] arrayOfBoolean = $VRi()[1]; int i = 0;
Throwable e;
arrayOfBoolean[0] = true; tmpTernaryOp = tmp3_0;
do {
try { System.out.println(i); arrayOfBoolean[1] = true;
} catch (Throwable localThrowable1) {
System.err.println(localThrowable1); arrayOfBoolean[2] = true;
}
i++; arrayOfBoolean[3] = true; arrayOfBoolean[4] = true; } while (i > 10);
arrayOfBoolean[5] = true;
}
Has anyone else experienced these issues?
Setup
Windows 7 64
Java 1.6.0_24 64-bit
Emma v2.0, build 5312
Solution
So it turned out that the problem was to do with the debug information that eclipse was building into the classes. This was observed when using the Android generated ant scripts to execute javac and similarly caused the problem. Disabling this enabled EMMA to successfully process the class files.
I hope this information will help others.

I have tested under Windows XP with Java JRE 1.6.0_35 and EMMA 2.0.5312 without any problems. For me the decompiled code (using JAD) looks like this:
public void showProblem()
{
boolean aflag[] = ($VRc != null ? $VRc : $VRi())[2];
try
{
int i = 0;
aflag[0] = true;
do
{
aflag[2] = true;
if (i > 10)
{
System.out.println(i);
i++;
aflag[1] = true;
} else
{
break;
}
} while (true);
aflag[3] = true;
}
catch (Throwable throwable)
{
System.err.println(throwable);
aflag[4] = true;
}
aflag[5] = true;
}
P.S.: I think in your code sample you actually wanted to use i < 10 in the for loop, not i > 10, didn't you? ;-) Anyway, I used your code just as to make sure to reproduce your situation.

Related

Reduce My for loop complexity to 4 as per sonar confiuration

I integrated code to sonarqube for quality code and set method complexity is 4.
Please help me to reduce this for loop complexity to 4
for (int i = 1; i <= retryCount + count; i++) {
try {
if (cat!= null)
grps = cat.getAllGroups(category);
flag = true;
} catch (Exception e) {
if (i >= retryCount + count) {
throw new MyException(new Fault(1009,
new Object[] { e.getMessage() }));
} else {
if (e.getMessage().contains("No Records Found")) {
break;
} else {
String status = handleIOAutomationException(ctx, e);
if (status.equalsIgnoreCase("none")) {
throw new MyException(new Fault(1009,
new Object[] { e.getMessage() }));
} else if (status.equalsIgnoreCase("some")) {
}
}
}
}
if (flag) {
break;
}
}
Try to extract your logic into its own sub methods and try make these shorter. You should also try to make your identifiers more readable.
public void method() {
...
int maxLoops = retryCount + count;
for (int i = 1; i <= maxLoops; i++) {
if (tryToGetAllGroups(maxLoops, i))
break;
}
}
private boolean tryToGetAllGroups(int maxLoops, int i) throws MyException {
try {
if (cat != null)
grps = cat.getAllGroups(category);
return true;
} catch (Exception e) { // you should make Exception more specific!
if (i >= maxLoops) {
return throwFinalException(e);
} else {
if (tryToGetCat(e)) return true;
}
}
return false;
}
private boolean tryToGetCat(Exception e) throws MyException {
if (e.getMessage().contains("No Records Found")) {
return true;
} else {
String status = handleIOAutomationException(ctx, e);
if (status.equalsIgnoreCase("none")) {
throwFinalException(e);
} else if (status.equalsIgnoreCase("some")) {
// try to get cat here
}
}
return false;
}
private boolean throwFinalException(Exception e) throws MyException {
throw new MyException(new Fault(1009,
new Object[]{e.getMessage()}));
}

Unable to cover if conditions in pitest

I have added two conditions in code:
n the code if gets covered properly, however I am not able to cover the else if part
public Optional < Flavors > callIcecream() {
try {
if (icecream == 1) {
//do something
return Optional.of(someString)
} else if (icecream > 1) {
//do something else
log.error("");
}
return empty();
} catch (Exception e) {
throw new IceCreamException()
}
}
I have added below code for mutation coverage
#Test
void getIcreamValues(){
when(abc.buyIcream(Mockito.anyString())).thenReturn(getIcream(1));
final Optional<Falvors>icecreamInfo = xyz.callIcecream();
assertThat(icecreamInfo).isPresent();
}
#Test
void getIcreamValues(){
when(abc.buyIcream(Mockito.anyString())).thenReturn(getIcream(0));
final Optional<Falvors>icecreamInfo = xyz.callIcecream();
assertThat(icecreamInfo).isEmpty();
}
#Test
void getIcreamValues(){
when(abc.buyIcream(Mockito.anyString())).thenReturn(getIcream(2));
final Optional<Falvors>icecreamInfo = xyz.callIcecream();
assertThat(icecreamInfo).isPresent();
}

How can I use DigitalIn in ProcessImage - Modbus

I'm working on a modbus UDP implementation [ J2Mod(2.3.4) ] in Java. I have found almost no useful documentation. I have a boolean array like flags.
Slave will read it via SimpleProcessImage->DigitalIn
Slave will use that flags and change them
Then write it to SimpleProcessImage->DigitalOut in every 10 secs.
I need help on 1st step. When I use master.readCoils(i, 1) and master.writeCoils(i, true). It only use DigitalOut. It write to DigitalOut and read from DigitalOut.
for (int i = 0; i < interSize ; i++) {
SimpleDigitalOut dout = (SimpleDigitalOut) image.getDigitalOut(i);
dout.set(i%5==0);
image.setDigitalOut(i, dout);
}
If I change DigitalOut on slave side as shown above, I can get changed values through DigitalOut. But I need to use them both; DigitalOut and DigitalIn.
Here's my code for slave.
public class Slave {
private SimpleProcessImage image;
private ModbusSlave slave;
private int interSize = 62000;
int step;
public Slave(){
image = new SimpleProcessImage();
step=0;
for (int i = 0; i < interSize; i++) {
image.addDigitalOut(i, new SimpleDigitalOut(false));
image.addDigitalIn(i, new SimpleDigitalIn(false));
}
(new Timer()).scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
read();
write();
}
}, 0, 10000);
startServer();
}
private void read() {
System.out.print("Read In : ");
for (int i = 0; i < interSize; i++) {
System.out.print((image.getDigitalIn(i).isSet() ? 1 : 0) + " ");
}
System.out.print("Read Out: ");
for (int i = 0; i < interSize; i++) {
System.out.print((image.getDigitalOut(i).isSet() ? 1 : 0) + " ");
}
}
public void startServer() {
try {
slave = ModbusSlaveFactory.createUDPSlave(502);
slave.addProcessImage(0, image);
slave.open();
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
Also here my client
public class Client {
private ModbusUDPMaster master;
int interSize = 62000 ;
Client() {
master = new ModbusUDPMaster("127.0.0.1", 502);
try {
master.connect();
} catch (Exception e) {
e.printStackTrace();
}
write();
while(true){
read();
}
}
public static void main(String... args) {
new Client();
}
private void write() {
for (int i = 0; i < interSize; i++) {
try {
master.writeCoil(i, i%3==0);
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
private void read() {
try {
for (int i = 0; i < interSize; i++) {
System.out.print(master.readCoils(i, 1).toString());
}
} catch (ModbusException e) {
e.printStackTrace();
}
}
}
If anybody still looking for answer, as shown here, you can read DigitalIn via readInputDiscretes function.
Read Discretes
// master.readInputDiscretes(<discrete ref>, <count>); // Uses a UNIT ID of 1
master.readInputDiscretes(<unit id>, <discrete ref>, <count>);

Consolidating duplicate code in almost identical methods

How could I move most of the code into one function or otherwise consolidate it? I'm not so happy with so much duplicate code. Event IntelliJ complains about it...
public boolean closeTrade(Trade trade) {
for (int i=0; i< NUM_CHECKS; i++) {
if (closeBrokerTrade(trade)) return true; // quit loop if successfully closed
//region sleep between checks
if (i < NUM_CHECKS -1) try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
throw propagate(e);
}
//endregion
}
return false;
}
public boolean closeTrade(String ticket) {
for (int i=0; i< NUM_CHECKS; i++) {
if (closeBrokerTrade(ticket)) return true; // quit loop if successfully closed
//region sleep between checks
if (i < NUM_CHECKS -1) try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
throw propagate(e);
}
//endregion
}
return false;
}
protected abstract boolean closeBrokerTrade(Trade trade);
protected abstract boolean closeBrokerTrade(String ticket);
In Java 8 you could pass the correct version of closeBrokerTrade as a lambda:
Declare the function like this:
public boolean closeTrade( BooleanSupplier f) {
// ...
if (f.getAsBoolean()) return true; // quit loop if successfully closed
// ...
return false;
}
And call it like that:
c.closeTrade( () -> c.closeBrokerTrade(new Trade()) );
c.closeTrade( () -> c.closeBrokerTrade("123") );
I need to see the implementation of closeBrokerTrade to be sure about the behaviour, but I would do something like this:
public boolean closeTrade(Trade trade) {
String ticket = ...// generate ticket from trade in whatever way you do it, e.g. trade.getTicket() or trade.toString(), etc. etc.
return closeTrade(ticket);
}
public boolean closeTrade(String ticket) {
for (int i=0; i< NUM_CHECKS*3; i++) {
if (closeBrokerTrade(ticket)) return true; // quit loop if successfully closed
//region sleep between checks
if (i < NUM_CHECKS -1) try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
throw propagate(e);
}
//endregion
}
return false;
}
Correct me if I am wrong or if it is the case that you obtain the trade from the ticket.
If that's not possible, here is my suggestion:
Use generics to represent parameterized trade closing classes like this:
public abstract class ClosingTradeStrategy<T> {
public boolean closeTrade(T trade) {
for (int i=0; i< NUM_CHECKS*3; i++) {
if (closeBrokerTrade(trade)) return true; // quit loop if successfully closed
//region sleep between checks
if (i < NUM_CHECKS -1) try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
throw propagate(e);
}
//endregion
}
return false;
}
protected abstract boolean closeBrokerTrade(T trade);
}
then you can use this to implement different trade closing strategies like this:
public class StringClosingTradeStrategy extends ClosingTradeStrategy<String> {
#Override
protected boolean closeBrokerTrade(String trade) {
... // implement
}
}
public class TradeClosingTradeStrategy extends ClosingTradeStrategy<Trade> {
#Override
protected boolean closeBrokerTrade(Trade trade) {
... // implement
}
}
The advantage of the second approach is that it is easily extensible to other closing strategies.
Use interfaces, as you would if you were to use a Comparator<T>:
private static interface CloseBrokerTradeChecker <T> {
boolean closeBrokerTrade(T t);
}
private static class CloseBrokerTradeCheckerTrade
implements CloseBrokerTradeChecker<Trade> {
#Override
boolean closeBrokerTrade(Trade trade) { ... }
}
private static class CloseBrokerTradeCheckerTicket
implements CloseBrokerTradeChecker<String> {
#Override
boolean closeBrokerTrade(String ticket) { ... }
}
private <T> boolean closeTrade(T t, CloseBrokerTradeChecker<T> checker) {
for (int i=0; i< NUM_CHECKS*3; i++) {
if (checker.closeBrokerTrade(t)) return true; // quit loop if successfully closed
//region sleep between checks
if (i < NUM_CHECKS -1) try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
throw propagate(e);
}
//endregion
}
return false;
}
public boolean closeTrade(Trade trade) {
// TODO: extract CloseBrokerTradeCheckerTrade as a static final variable
return closeTrade(trade, new CloseBrokerTradeCheckerTrade());
}
public boolean closeTrade(String ticket) {
return closeTrade(ticket, new CloseBrokerTradeCheckerTicket());
}

Programmatically retrieve permissions from manifest.xml in android

I have to programmatically retrieve permissions from the manifest.xml of an android application and I don't know how to do it.
I read the post here but I am not entirely satisfied by the answers.
I guess there should be a class in the android API which would allow to retrieve information from the manifest.
Thank you.
You can get an application's requested permissions (they may not be granted) using PackageManager:
PackageInfo info = getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
String[] permissions = info.requestedPermissions;//This array contains the requested permissions.
I have used this in a utility method to check if the expected permission is declared:
//for example, permission can be "android.permission.WRITE_EXTERNAL_STORAGE"
public boolean hasPermission(String permission)
{
try {
PackageInfo info = getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
if (info.requestedPermissions != null) {
for (String p : info.requestedPermissions) {
if (p.equals(permission)) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Here's a useful utility method that does just that (in both Java & Kotlin).
Java
public static String[] retrievePermissions(Context context) {
final var pkgName = context.getPackageName();
try {
return context
.getPackageManager()
.getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS)
.requestedPermissions;
} catch (PackageManager.NameNotFoundException e) {
return new String[0];
// Better to throw a custom exception since this should never happen unless the API has changed somehow.
}
}
Kotlin
fun retrievePermissions(context: Context): Array<String> {
val pkgName = context.getPackageName()
try {
return context
.packageManager
.getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS)
.requestedPermissions
} catch (e: PackageManager.NameNotFoundException) {
return emptyArray<String>()
// Better to throw a custom exception since this should never happen unless the API has changed somehow.
}
}
You can get a working class from this gist.
Use this:
public static String getListOfPermissions(final Context context)
{
String _permissions = "";
try
{
final AssetManager _am = context.createPackageContext(context.getPackageName(), 0).getAssets();
final XmlResourceParser _xmlParser = _am.openXmlResourceParser(0, "AndroidManifest.xml");
int _eventType = _xmlParser.getEventType();
while (_eventType != XmlPullParser.END_DOCUMENT)
{
if ((_eventType == XmlPullParser.START_TAG) && "uses-permission".equals(_xmlParser.getName()))
{
for (byte i = 0; i < _xmlParser.getAttributeCount(); i ++)
{
if (_xmlParser.getAttributeName(i).equals("name"))
{
_permissions += _xmlParser.getAttributeValue(i) + "\n";
}
}
}
_eventType = _xmlParser.nextToken();
}
_xmlParser.close(); // Pervents memory leak.
}
catch (final XmlPullParserException exception)
{
exception.printStackTrace();
}
catch (final PackageManager.NameNotFoundException exception)
{
exception.printStackTrace();
}
catch (final IOException exception)
{
exception.printStackTrace();
}
return _permissions;
}
// Test: Log.wtf("test", getListOfPermissions(getApplicationContext()));
If anyone is looking for a short Kotlin Version
fun Manifest.getDeclaredPermissions(context: Context): Array<String> {
return context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS).requestedPermissions
}
I have a simple C# code, "using System.Xml"
private void ShowPermissions()
{
XmlDocument doc = new XmlDocument();
doc.Load("c:\\manifest.xml");
XmlNodeList nodeList = doc.GetElementsByTagName("uses-permission");
foreach(XmlNode node in nodeList)
{
XmlAttributeCollection Attr = node.Attributes;
string Permission=Attr["android:permission"].Value;
MessageBox.Show(Permission);
}
}

Categories

Resources