this is my actual class I am writing test class below.
public class ReadFile {
private Scanner rx, tx;
public void openFile() {
try {
rx = new Scanner(new File("/sys/class/net/eth0/statistics/rx_bytes"));
tx = new Scanner(new File("/sys/class/net/eth0/statistics/tx_bytes"));
} catch (Exception e) {
e.printStackTrace();
}
}
public String readRxFile() {
String rxData = "";
while (rx.hasNext()) {
rxData = rx.next();
}
return rxData;
}
public String readTxFile() {
String txData = "";
while (tx.hasNext()) {
txData = tx.next();
}
return txData;
}
public void closeFile() {
rx.close();
tx.close();
}
}
this is test class. to test the read data.
public class Testreadrxfile extends TestCase {
public Testreadrxfile() {
super();
}
protected void setUp() throws Exception {
try {
super.setUp();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ReadFile rf;
public void testappdata() {
String str1 = rf.readRxFile();
Assert.assertEquals("14081",str1 );
}
}
this is the error I am getting.
java.lang.NullPointerException
atcom.android.deviceintelligence1. test.Testreadrxfile.testappdata(Testreadrxfile.java:26)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)
this is not activity or service test to use getactivity() or getservice() so what I should do to get out of this error . thanks for help in advance.
see your code.. rf is not initialised..
ReadFile rf; // not intialisd
public void testappdata() {
String str1 = rf.readRxFile(); // equivalent to null.readRxFile();
Assert.assertEquals("14081",str1 );
}
yeah, rf is not initialised. In this kind of situation first thing to do is attach the debugger on the line you are getting error, and in most cases answer becomes obvious.
UPDATE
first your code didn't work because you didn't initialised rx, now your code doesn't work becasue you never called following function. In the function you are initialising your scanner objects. call this function from your readRxFile function and you should be good to go.
public void openFile() {
try {
rx = new Scanner(new File("/sys/class/net/eth0/statistics/rx_bytes"));
tx = new Scanner(new File("/sys/class/net/eth0/statistics/tx_bytes"));
} catch (Exception e) {
e.printStackTrace();
}
}
public String readRxFile() {
String rxData = "";
while (rx.hasNext()) { //eq. to null.haxNext()
rxData = rx.next();
}
return rxData;
}
Related
public void getTerms(boolean showDialog) {
service.getTermsFromServer().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SingleSubscriber<String>() {
#Override
public void onSuccess(String value) {
try {
JSONObject jsonObject = new JSONObject(value);
JSONObject data = jsonObject.getJSONObject("data");
String content = data.getString("content");
String id = data.getString("id");
if (showDialog) {
***signUpView.showDialog(content, id)***;
} else {
agreeTerms(id);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(Throwable error) {
Log.e(getClass().getName(), "Error : " + new Gson().toJson(error.getStackTrace()));
ErrorCheck.processError(error, gson, signUpView);
}
});
}
Please help me in testing this code. I have attached the method which i want to test. Here I want to verify that showDialog method gets called
Attaching the Unit test code also
#Test
public void testGetTermsCalled(){
String terms= "{\"data\":{\"id\":\"67f07c7a482542\",\"content\":\"<h3>Part of the test</h3>\",\"timestamp\":1484768675815,\"timestampFormatted\":\"2017-01-18T19:44:35\"},\"metadata\":null,\"version\":{\"id\":\"v1\",\"versionStatus\":\"candidate\",\"message\":null}}";
TestSubscriber<String> testSubscriber = new TestSubscriber<>();
signUpService.getTermsFromServer().just(terms).subscribe(testSubscriber);
signUpPresenter.getTerms(true);
Mockito.verify(signUpView).showDialog("<h3>Part of the test</h3>","67f07c71-1707-4b7a-a168-d7d05a482542");
}
Thanks!!!
Use RxJavaPlugins.setInitIoSchedulerHandler and RxAndroidPlugins.registerSchedulersHook to specify your own TestScheduler, then use its advanceTimeBy method to make some time pass, then verify that the expected calls happened.
I throw a exception with some message like:
public static ILSResponseEmailLookUPBO getILSUserAccounts(Resources res,
String email) throws TripLoggerCustomException,
TripLoggerUnexpectedErrorException {
String resp = null;
String lookupURL;
try {
lookupURL = TripLoggerConstants.ServerConstants.ILS_LOOKUP_URL
+ URLEncoder.encode(email, "UTF-8");
} catch (UnsupportedEncodingException e1) {
throw new TripLoggerCustomException(
res.getString(R.string.error_try_again));
}
try {
resp = ConnectionManager.getInstance().httpRequest(lookupURL,
TripLoggerConstants.RequestMethods.GET);
} catch (IOException e) {
if (e.getMessage().equals(
res.getString(R.string.network_unreachable))
|| e.getMessage().equals(
res.getString(R.string.host_unresolved))) {
throw new TripLoggerCustomException(
res.getString(R.string.network_not_reachable));
} else {
throw new TripLoggerCustomException(
res.getString(R.string.email_notfound_ils));
}
}
here my else part execute.
And my exception class is:
public class TripLoggerCustomException extends Exception {
private String customMessage;
private static final long serialVersionUID = 1L;
public TripLoggerCustomException() {
super();
}
public TripLoggerCustomException(String message) {
super(message);
this.customMessage = (message == null ? "" : message);
}
public String getCustomMessage() {
return this.customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
}
And here i catch this exception:
private void manageLookUpActions(final String emailID) {
new Thread() {
public void run() {
try {
listILSAccounts = ILSLookupEmailBL.getILSUserAccounts(
getResources(), emailID);
} catch (TripLoggerCustomException e) {
dismissProgressBar();
handleException(e.getMessage());
return;
} catch (TripLoggerUnexpectedErrorException e) {
dismissProgressBar();
handleException(e.getMessage());
return;
}
}
}.start();
}
but here in catch of TripLoggerCustomException e is null.why?Can anyone help me?
After looking into multiple reports on StackOverflow, it seems like this is not an actual issue. Multiple people have been saying that it is a problem in the combination of the Eclipse debugger and the Android Emulator. That is why you don't get a NullPointerException, which you would definitely get if e was null.
So this is probably not an issue you have to worry about.
I tried this library, suggested in one of the posts on stack overflow,
I've added the lib's jar to my build-path, but I'm not able to initialize DetectorFactory class with the languages' profiles.
this is the class handling the detection, as suggested in one of their samples:
class LanguageDetector {
public void init(String profileDirectory) throws LangDetectException {
DetectorFactory.loadProfile(profileDirectory);
}
public String detect(String text) throws LangDetectException {
Detector detector = DetectorFactory.create();
detector.append(text);
return detector.detect();
}
public ArrayList<Language> detectLangs(String text) throws LangDetectException {
Detector detector = DetectorFactory.create();
detector.append(text);
return detector.getProbabilities();
}
}
all languages profiles are stored under myProject/profiles.
trying to instantiate the class crashes my app without any useful message to logcat
calling the class ():
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
context = this.getActivity().getApplicationContext();
/* LanguageDetector detector = null;
try {
detector.init("/waggle/profiles");
} catch (LangDetectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
new GetDataTask().execute(context);
}
Change the methods in LanguageDetector to static:
class LanguageDetector {
public static void init(String profileDirectory) throws LangDetectException {
DetectorFactory.loadProfile(profileDirectory);
}
public static String detect(String text) throws LangDetectException {
Detector detector = DetectorFactory.create();
detector.append(text);
return detector.detect();
}
public static ArrayList<Language> detectLangs(String text) throws LangDetectException {
Detector detector = DetectorFactory.create();
detector.append(text);
return detector.getProbabilities();
}
}
And use as follows:
try {
LanguageDetector.init("/waggle/profiles"); // <-- Are you sure the profiles are at this location???
} catch (LangDetectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String detectedLanguage = null;
try {
detectedLanguage = LanguageDetector.detect("Dies ist ein Beispiel in Deutsch.");
} catch (LangDetectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (detectedLanguage != null) {
// Implement your logic here
}
I am trying to implement using XPUB and XSUB as provided in this below figure. I have gone through their examples provided but could not get one for XPUB and XSUB in Java. Here they have given an example in C which is little complex as I am new to ZeroMQ.
I am trying to use it in android using jni wrapped version. Please help me to find an example, how to implement this Pub-Sub Network with a Proxy in ZeroMQ using java.
Currently I am referring http://zguide.zeromq.org/page:all
I have tried to port it as follows.
Subscriber.java
public class Subscriber extends Thread implements Runnable {
private static final String TAG = "Subscriber";
private Context ctx;
public Subscriber(ZMQ.Context z_context) {
this.ctx = z_context;
}
#Override
public void run() {
super.run();
ZMQ.Socket mulServiceSubscriber = ctx.socket(ZMQ.SUB);
mulServiceSubscriber.connect("tcp://localhost:6001");
mulServiceSubscriber.subscribe("A".getBytes());
mulServiceSubscriber.subscribe("B".getBytes());
while (true) {
Log.d(TAG, "Subscriber loop started..");
String content = new String(mulServiceSubscriber.recv(0));
Log.d(TAG, "Subscriber Received : "+content);
}
}
}
Publisher.java
public class Publisher extends Thread implements Runnable {
private static final String TAG = "Publisher";
private Context ctx;
public Publisher(ZMQ.Context z_context) {
this.ctx = z_context;
}
#Override
public void run() {
super.run();
ZMQ.Socket publisher = ctx.socket(ZMQ.PUB);
publisher.connect("tcp://localhost:6000");
while (true) {
Log.d(TAG, "Publisher loop started..");
publisher.send(("A Hello " + new Random(100).nextInt()).getBytes() , 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
XListener.java (For now a simple Forwarder)
public class XListener extends Thread implements Runnable {
private static final String TAG = null;
private Socket publisherX;
private Context ctx;
private Socket subscriberX;
public XListener(ZMQ.Context ctx, ZMQ.Socket subscriberX,
ZMQ.Socket publisherX) {
this.ctx = ctx;
this.subscriberX = subscriberX;
this.publisherX = publisherX;
}
#Override
public void run() {
super.run();
while (true) {
Log.d(TAG, "XListener loop started..");
String msg = new String(subscriberX.recvStr());
Log.v(TAG, "Listener Received: " +"MSG :"+msg);
publisherX.send(msg.getBytes(), 0);
}
}
}
in application main()
private void main() {
ZMQ.Context ctx = ZMQ.context(1);
ZMQ.Socket subscriberX = ctx.socket(ZMQ.XSUB);
subscriberX.bind("tcp://*:6000");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ZMQ.Socket publisherX = ctx.socket(ZMQ.XPUB);
publisherX.bind("tcp://*:6001");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new XListener(ctx, subscriberX, publisherX).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new XSender(ctx, subscriberX, publisherX).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Subscriber(ctx).start();
new Publisher(ctx).start();
}
With the code I am not able to listen XSUB. While porting espresso.c, I was not able to find any wrapper in java bindings of ZMQ. How to implement a simple proxy or am I missing something??
Wow I'm answering my own question. I missed to add a forwarder from publisherX to subscriberX. Here is the missing code. Now XSUB and XPUB are able to send and get data.
public class XSender extends Thread implements Runnable {
private static final String TAG = null;
private Socket publisherX;
private Context ctx;
private Socket subscriberX;
public XSender(ZMQ.Context ctx, ZMQ.Socket subscriberX,
ZMQ.Socket publisherX) {
this.ctx = ctx;
this.subscriberX = subscriberX;
this.publisherX = publisherX;
}
#Override
public void run() {
super.run();
while (true) {
// Read envelope with address
Log.d(TAG, "XListener loop started..");
String msg = new String(subscriberX.recv(0));
Log.v(TAG, "Listener Received: " +"MSG :"+msg);
publisherX.send(msg.getBytes(), 0);
}
}
}
I've seen a bunch of posts related to this, but none seem to have the same issue I'm getting. GetBusinessRulesTask extends AsyncTask. When I execute this in a unit test case the onPostExecute() never gets called. However, if I use the real client code then onPostExecute() is called everytime. Not sure what I'm doing wrong here.
Test Case:
package com.x.android.test.api;
import java.util.concurrent.CountDownLatch;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.widget.Button;
import com.x.android.api.domain.businessrule.BusinessRules;
import com.x.android.api.exception.NetworkConnectionException;
import com.x.android.api.tasks.GetBusinessRulesTask;
import com.x.android.test.activity.SimpleActivity;
public class GetBusinessRulesTaskTest
extends
ActivityInstrumentationTestCase2<SimpleActivity> {
SimpleActivity mActivity;
Button mButton;
public GetBusinessRulesTaskTest() {
super("com.x.android.test.activity", SimpleActivity.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
mActivity = this.getActivity();
mButton = (Button) mActivity
.findViewById(com.x.android.test.activity.R.id.b1);
}
public void testPreconditions() {
assertNotNull(mButton);
}
#UiThreadTest
public void testCallBack() throws Throwable {
final CountDownLatch signal = new CountDownLatch(1);
final GetBusinessRulesTask task = (GetBusinessRulesTask) new GetBusinessRulesTask(
new GetBusinessRulesTask.Receiver<BusinessRules>() {
#Override
public void onReceiveResult(BusinessRules rules, Exception e) {
assertNotNull(rules);
assertNull(e);
signal.countDown();// notify the count down latch
}
});
task.start(mActivity.getApplicationContext());
try {
signal.await();// wait for callback
} catch (InterruptedException e1) {
fail();
e1.printStackTrace();
}
}
}
OnPostExecute:
#Override
protected void onPostExecute(AsyncTaskResponse<O> response) {
Log.d(TAG, "onPostExecuted");
if (mReceiver != null) {
mReceiver.onReceiveResult(response.getResponse(), response.getException());
}
}
DoInBackground:
#Override
protected AsyncTaskResponse<O> doInBackground(I... params) {
Log.d(TAG, "doInBackgroundr");
try {
Uri uri = createUri(params);
mBaseRequest = new GetLegacyRequest(uri);
String json = mBaseRequest.executeRequest();
O response = deserializeJson(json);
Log.d(TAG, "Returning AsyncTaskResponse");
return new AsyncTaskResponse<O>(response, null);
} catch (Exception e) {
Log.e(TAG, "Error", e);
/*
AsyncTaskResponse<O> maintenance = ReadBusinessControlledPropertiesTask.blockingCall(mServiceLocatorUrl);
if(maintenance.getException() == null) {
MaintenanceException mExcep = new MaintenanceException( maintenance.getResponse());
if (mExcep.isUnderMaintenance())
return new AsyncTaskResponse(null,mExcep);
}*/
return new AsyncTaskResponse<O>(null, e);
}
}
Start method()
public AsyncTask<Void, Void, AsyncTaskResponse<BusinessRules>> start(
Context context) throws NetworkConnectionException {
super.start(context);
Log.d(TAG, "start");
return execute();
}
FOUND THE ISSUE. Don't make your AsyncTask final and put it inside the runnable.
The fix:
public void testCallBack() throws Throwable {
final CountDownLatch signal = new CountDownLatch(1);
// Execute the async task on the UI thread! THIS IS KEY!
runTestOnUiThread(new Runnable() {
#Override
public void run() {
try {
GetBusinessRulesTask task = (GetBusinessRulesTask)new GetBusinessRulesTask(new GetBusinessRulesTask.Receiver<BusinessRules>() {
#Override
public void onReceiveResult(
BusinessRules rules, Exception e) {
assertNotNull(rules);
assertNull(e);
signal.countDown();// notify the count downlatch
}
});
task.start(mActivity.getApplicationContext());
} catch (Exception e) {
Log.e(TAG, "ERROR", e);
fail();
}
}
});
try {
signal.await();// wait for callback
} catch (InterruptedException e1) {
fail();
e1.printStackTrace();
}
}
FOUND THE ISSUE. Don't make your AsyncTask final and put it inside the runnable.
The fix:
public void testCallBack() throws Throwable {
final CountDownLatch signal = new CountDownLatch(1);
// Execute the async task on the UI thread! THIS IS KEY!
runTestOnUiThread(new Runnable() {
#Override
public void run() {
try {
GetBusinessRulesTask task = (GetBusinessRulesTask)new GetBusinessRulesTask(new GetBusinessRulesTask.Receiver<BusinessRules>() {
#Override
public void onReceiveResult(
BusinessRules rules, Exception e) {
assertNotNull(rules);
assertNull(e);
signal.countDown();// notify the count downlatch
}
});
task.start(mActivity.getApplicationContext());
} catch (Exception e) {
Log.e(TAG, "ERROR", e);
fail();
}
}
});
try {
signal.await();// wait for callback
} catch (InterruptedException e1) {
fail();
e1.printStackTrace();
}
}