Use Robolectric to test Activity with Loader - java

I have an Activity with a Spinner that uses a Loader to fetch data from the ContentProvider (as advised in several sources and as I've done before):
protected void onCreate(Bundle savedInstanceState) {
// ...
account = (Spinner) findViewById(R.id.account);
account.setAdapter(
new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
null,
new String[]{ Contract.Accounts.COL_NAME },
new int[]{ android.R.id.text1 },
0));
getLoaderManager().initLoader(LOADER_ID_ACCOUNT, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this,
Contract.Accounts.CONTENT_URI,
null,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
((SimpleCursorAdapter)account.getAdapter()).swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
((SimpleCursorAdapter)account.getAdapter()).swapCursor(null);
}
So far so good, the app works like a charm when I run it, but the unit tests I had for this Activity won't run now.
#Test
public void testAllElementsExist() {
Activity activity = setupActivity(AddTransactionActivity.class);
assertTrue(activity.findViewById(R.id.category) != null);
assertTrue(activity.findViewById(R.id.created_on_date) != null);
assertTrue(activity.findViewById(R.id.created_on_time) != null);
assertTrue(activity.findViewById(R.id.account) != null);
assertTrue(activity.findViewById(R.id.description) != null);
}
Even the most basic test fails:
java.lang.NullPointerException
at android.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:328)
at android.widget.SimpleCursorAdapter.swapCursor(SimpleCursorAdapter.java:345)
at pt.lemonade.AddTransactionActivity.onLoadFinished(AddTransactionActivity.java:185)
at pt.lemonade.AddTransactionActivity.onLoadFinished(AddTransactionActivity.java:28)
at android.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:482)
at android.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:450)
at android.content.Loader.deliverResult(Loader.java:143)
at android.content.CursorLoader.deliverResult(CursorLoader.java:113)
at android.content.CursorLoader.deliverResult(CursorLoader.java:43)
at android.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:254)
at android.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:91)
at android.os.ShadowAsyncTaskBridge.onPostExecute(ShadowAsyncTaskBridge.java:22)
at org.robolectric.shadows.ShadowAsyncTask$1$1.run(ShadowAsyncTask.java:40)
at org.robolectric.util.Scheduler$PostedRunnable.run(Scheduler.java:182)
at org.robolectric.util.Scheduler.runOneTask(Scheduler.java:125)
at org.robolectric.util.Scheduler.advanceTo(Scheduler.java:110)
at org.robolectric.util.Scheduler.advanceToLastPostedRunnable(Scheduler.java:86)
at org.robolectric.util.Scheduler.unPause(Scheduler.java:26)
at org.robolectric.shadows.ShadowLooper.unPause(ShadowLooper.java:231)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:270)
at org.robolectric.util.ActivityController.visible(ActivityController.java:166)
at org.robolectric.util.ActivityController.setup(ActivityController.java:202)
at org.robolectric.Robolectric.setupActivity(Robolectric.java:1388)
at pt.lemonade.AddTransactionActivityTest.testAllElementsExist(AddTransactionActivityTest.java:65)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:236)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Is this a known issue of Robolectric 2.4? Is there a workaround that doesn't translate into writing a bunch of shadow classes?
Tools of trade: Android Studio 1.1.0 with Unit Testing experimental feature activated, Gradle plugin 1.0.1, Robolectric 2.4
Also, some aside questions: I've recently heard that it's best to use RxJava Observables because it's easier to test. Can it be used as a substitute to the LoaderManager? How can I cache the results as the LoaderManager does? Can you give me a working example of a query to the ContentProvider and a unit test so I can evaluate?

In case anyone falls into the same issue: Robolectric lacked ShadowSimpleCursorAdapter#swapCursor implementation. I've added that method along with other modifications and created a pull request. You may find it in the master branch. As for anyone still using version 2.4, check this out: https://github.com/robolectric/robolectric/issues/1677

Related

Can anyone suggest a mockito Test for this code?

This function tries to retrieve the topic of the GitHub repository name using the GitHub API: https://api.github.com/repos/flutter/flutter/topics
public List<String> getTopics(SearchRepository searchRepository){
GitHubRequest request = new GitHubRequest();
List<String> topic_list = new ArrayList<>();
try {
String url = searchRepository.getUrl().split("//")[1].split("github.com")[1];
request.setUri("/repos"+ url + "/topics");
String result = new BufferedReader(new InputStreamReader(gitHubClient.getStream(request)))
.lines().collect(Collectors.joining("\n"));
JSONObject jsonObject = new JSONObject(result);
topic_list = Arrays.stream(jsonObject.get("names").toString().replace("[", "").replace("]", "").split(",")).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return topic_list;
}
The url returned before string to list conversion is :https://github.com/repouser/reponame
SearchRepository is the v2 model class of Repository from the package:
SearchRepositroy
As per the earlier suggestions from this wonderful community answers (though the question is now edited, it remains yet relevant) I created the mock test to test the above function as below:
#Test
public void getTopicsTest() throws IOException{
SearchRepository mocksearchRepository = mock(SearchRepository.class);
GitHubClient mockClient = mock(GitHubClient.class);
GitHubRequest mockRequest = mock(GitHubRequest.class);
when(mocksearchRepository.getUrl()).thenReturn("https://github.com/mockuser/mockrepo");
when(mocksearchRepository.getName()).thenReturn("mockrepo");
when(mocksearchRepository.getOwner()).thenReturn("mockuser");
//when(mockRequest.setUri((String) any())).thenReturn(mockRequest.setUri("/repo/mockuser/mockrepo/topics"));
//The format of the return form is: https://github.com/CyC2018/CS-Notes
when(mockClient.getStream(any())).thenReturn(topicInputStream());
//SearchRepository querySearch = new SearchRepository("mockuser","mockrepo");
List<String> topics = githubServiceMock.getTopics(mocksearchRepository);
System.out.println(topics);
}
private InputStream topicInputStream() {
String mockTopics = "{" +
"topic1\": [" +
"topic2\"," +
"topic3\"," +
"skia" +
"]" +
"}";
InputStream stream = new ByteArrayInputStream(mockTopics.getBytes(StandardCharsets.UTF_8));
System.out.println(stream);
return stream;
}
However, I get the 404 internal server error Exception due to the request.setUri(Uri(String)) in the function. Please suggest where I am going wrong.
Test services.GithubServiceTest.getTopicsTest started
java.io.ByteArrayInputStream#6ed99482
org.eclipse.egit.github.core.client.RequestException: Not Found (404)
| => rat org.eclipse.egit.github.core.client.GitHubClient.createException(GitHubClient.java:552)
at org.eclipse.egit.github.core.client.GitHubClient.getResponseStream(GitHubClient.java:701)
at org.eclipse.egit.github.core.client.GitHubClient.getStream(GitHubClient.java:667)
at services.GithubService.getTopics(GithubService.java:231)
at services.GithubServiceTest.getTopicsTest(GithubServiceTest.java:222)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at com.novocode.junit.JUnitRunner$1.execute(JUnitRunner.java:132)
at sbt.ForkMain$Run.lambda$runTest$1(ForkMain.java:413)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
[]
[info] Test services.GithubServiceTest.getIssueWordLevelStatisticsTest started
[info] Test services.GithubServiceTest.getRepositoriesByTopicTest started
[info] Test services.GithubServiceTest.getUserDetailsTest started
[info] Test services.GithubServiceTest.getRepositoryDetailsTest started
[info] Test run finished: 0 failed, 0 ignored, 5 total, 1.122s
[error] Failed: Total 10, Failed 1, Errors 0, Passed 9
[error] Failed tests:
[error] controllers.GithubControllerTest
[error] (Test / test) sbt.TestsFailedException: Tests unsuccessful
You can mock repositoryService and gitHubClient to test various scenarios.
You can provide a package-level setter for these fields. It is a great idea to annotate it with Guava VisibleForTesting annotation.
Then you need to set mocks before the actual test on the instance.
Pseudocode for mocking
// First, we mock repository so we can return it from service
Repository repositoryMock = mock(Repository.class);
when(repository.getUrl()).thenReturn("https://...."); // You can return a URL or String, according to the mocked method's return type
// Then, we mock RepositoryService as well
RepositoryService repositoryServiceMock = mock(RepositoryService.class);
when(repositoryServiceMock.getRepository(anyString(), anyString()).thenReturn(repositoryMock);
// We mock gitHubService similarly
...
// After setting mock on the instance, we call the method and see if the results are expected
List<String> topics = getTopics("...", "...");
assertEquals(topics, ...);
// You can also assert interaction related things
verify(repositoryService).getRepository("a", "b"); // This is OK only if the service is called with "a" and "b" arguments
First, you need to inject the mock object (repositoryService,gitHubClient) to your function.
If you use spring/spring boot, you can consider to use #Mock and #MockBean annotation.
to mock the necessary bean.
The below code to create mock object manually.
RepositoryService fakeRs = Mockito.mock(RepositoryService.class);
GitHubClient fakeGHC = Mockito.mock(GitHubClient.class);
You also can use setter method to set mock object.
setRepositoryService(fakeRs);
setGitHubClient(fakeGHC);
The other way is using reflection utility to set private object.
ReflectionTestUtils.setField(yourService, "repositoryService", fakeRs);
ReflectionTestUtils.setField(yourService, "gitHubClient", fakeGHC);
After finish ingesting the mock object, you can write an test with expected behavior/data from mock object.
#Test
public void testGetTopics(){
// init mock object code in case setter/getter/reflection utils
Repository expectedRepository = createExampleRepository();
Mockito.when(repositoryService.getRepository(Mockito.anyString(),Mockito.anyString())
.thenReturn(expectedRepository);
// continue to fake gitHubClient with your expected data/ exceptions...
//call your method
List<?> data = yourService.getTopic("user","data");
Assertions.assertTrue(data!=null);
// you can write few assertion base on your fake datas
}
PS: Don't copy/paste the code, you will get compile errors. I am not using editor tool.

[ERROR]TransactionBuilder. - The transaction currently built is missing an attachment for :classnet/corda/core/contracts/CommandData

When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.
MetalContract
import com.template.states.MetalState;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.CommandData;
import net.corda.core.contracts.Contract;
import net.corda.core.contracts.ContractState;
import net.corda.core.identity.Party;
import net.corda.core.transactions.LedgerTransaction;
import org.jetbrains.annotations.NotNull;
import java.security.PublicKey;
import java.util.List;
// ************
// * Contract *
// ************
public class MetalContract implements Contract {
// This is used to identify our contract when building a transaction.
public static final String CID = "com.template.contracts.MetalContract";
// A transaction is valid if the verify() function of the contract of all the transaction's input and output states
// does not throw an exception.
#Override
public void verify(#NotNull LedgerTransaction tx) throws IllegalArgumentException{
if (tx.getCommands().size() != 1)
throw new IllegalArgumentException("Transaction must have one Command.");
Command command = tx.getCommand(0);
CommandData commandType = command.getValue();
List<PublicKey> requiredSigners = command.getSigners();
// -------------------------------- Issue Command Contract Rules ------------------------------------------
if (commandType instanceof Issue) {
// Issue transaction logic
// Shape Rules
if (tx.getInputs().size() != 0)
throw new IllegalArgumentException("Issue cannot have inputs");
if (tx.getOutputs().size() != 1)
throw new IllegalArgumentException("Issue can only have one output");
// Content Rules
ContractState outputState = tx.getOutput(0);
if (!(outputState instanceof MetalState))
throw new IllegalArgumentException("Output must be a metal State");
MetalState metalState = (MetalState) outputState;
if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
throw new IllegalArgumentException("Metal is not Gold or Silver");
}
// Signer Rules
Party issuer = metalState.getIssuer();
PublicKey issuersKey = issuer.getOwningKey();
if (!(requiredSigners.contains(issuersKey)))
throw new IllegalArgumentException("Issuer has to sign the issuance");
}
// -------------------------------- Transfer Command Contract Rules ------------------------------------------
else if (commandType instanceof Transfer) {
// Transfer transaction logic
// Shape Rules
if (tx.getInputs().size() != 1)
throw new IllegalArgumentException("Transfer needs to have one input");
if (tx.getOutputs().size() != 1)
throw new IllegalArgumentException("Transfer can only have one output");
// Content Rules
ContractState inputState = tx.getInput(0);
ContractState outputState = tx.getOutput(0);
if (!(outputState instanceof MetalState))
throw new IllegalArgumentException("Output must be a metal State");
MetalState metalState = (MetalState) inputState;
if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
throw new IllegalArgumentException("Metal is not Gold or Silver");
}
// Signer Rules
Party owner = metalState.getOwner();
PublicKey ownersKey = owner.getOwningKey();
if (!(requiredSigners.contains(ownersKey)))
throw new IllegalArgumentException("Owner has to sign the transfer");
}
else throw new IllegalArgumentException("Unrecognised command.");
}
// Used to indicate the transaction's intent.
public static class Issue implements CommandData {}
public static class Transfer implements CommandData {}
}
package com.template.contracts;
import com.template.states.MetalState;
import com.template.contracts.MetalContract;
import net.corda.core.contracts.Contract;
import net.corda.core.identity.CordaX500Name;
import net.corda.testing.contracts.DummyState;
import net.corda.testing.core.DummyCommandData;
import net.corda.testing.core.TestIdentity;
import net.corda.testing.node.MockServices;
import org.junit.Test;
import static net.corda.testing.node.NodeTestUtils.transaction;
public class ContractTests {
private final TestIdentity Mint = new TestIdentity (new CordaX500Name ("mint", "", "GB"));
private final TestIdentity TraderA = new TestIdentity (new CordaX500Name ("traderA", "", "GB"));
private final TestIdentity TraderB = new TestIdentity (new CordaX500Name ("traderB", "", "GB"));
private final MockServices ledgerServices = new MockServices();
private MetalState metalState = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
private MetalState metalStateInput = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
private MetalState metalStateOutput = new MetalState("Gold", 10, Mint.getParty(), TraderB.getParty());
#Test
public void metalContractImplementsContract() {
assert (new MetalContract() instanceof Contract);
}
#Test
public void MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction() {
transaction(ledgerServices, tx -> {
// Issuer is not a required signer, will fail
tx.output(MetalContract.CID, metalState);
tx.command(TraderA.getPublicKey(), new MetalContract.Issue());
tx.fails();
return null;
});
transaction(ledgerServices, tx -> {
// Issuer is a required, will verify
tx.output(MetalContract.CID, metalState);
tx.command(Mint.getPublicKey(), new MetalContract.Issue());
tx.verifies();
return null;
});
}
}
The Error is as following .
[ERROR] 12:35:10,086 [main] transactions.TransactionBuilder. - The transaction currently built is missing an attachment for class: net/corda/core/contracts/CommandData.
Attempted to find a suitable attachment but could not find any in the storage.
Please contact the developer of the CorDapp for further instructions.
java.lang.NoClassDefFoundError: net/corda/core/contracts/CommandData
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:405)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at net.corda.serialization.internal.model.TypeIdentifier$Unparameterised.getLocalType(TypeIdentifier.kt:151)
at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:38)
at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:25)
at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660)
at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:38)
at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:25)
at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:149)
at kotlin.sequences.FilteringSequence$iterator$1.calcNext(Sequences.kt:109)
at kotlin.sequences.FilteringSequence$iterator$1.hasNext(Sequences.kt:133)
at kotlin.collections.MapsKt__MapsKt.putAll(Maps.kt:339)
at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:504)
at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:498)
at net.corda.serialization.internal.model.ClassCarpentingTypeLoader.load(TypeLoader.kt:45)
at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.reflect(RemoteSerializerFactory.kt:129)
at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.access$reflect(RemoteSerializerFactory.kt:47)
at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:71)
at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:47)
at net.corda.serialization.internal.amqp.DefaultDescriptorBasedSerializerRegistry.getOrBuild(DescriptorBasedSerializerRegistry.kt:28)
at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.get(RemoteSerializerFactory.kt:66)
at net.corda.serialization.internal.amqp.ComposedSerializerFactory.get(SerializerFactory.kt)
at net.corda.serialization.internal.amqp.DeserializationInput.readObject(DeserializationInput.kt:172)
at net.corda.serialization.internal.amqp.DeserializationInput.readObjectOrNull(DeserializationInput.kt:147)
at net.corda.serialization.internal.amqp.DeserializationInput$deserialize$1.invoke(DeserializationInput.kt:124)
at net.corda.serialization.internal.amqp.DeserializationInput.des(DeserializationInput.kt:99)
at net.corda.serialization.internal.amqp.DeserializationInput.deserialize(DeserializationInput.kt:119)
at net.corda.serialization.internal.amqp.AbstractAMQPSerializationScheme.deserialize(AMQPSerializationScheme.kt:145)
at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1$1.invoke(SerializationScheme.kt:105)
at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:105)
at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:73)
at net.corda.core.serialization.SerializationFactory.asCurrent(SerializationAPI.kt:85)
at net.corda.serialization.internal.SerializationFactoryImpl.deserialize(SerializationScheme.kt:105)
at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt:78)
at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt)
at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
at java.util.AbstractList$Itr.next(AbstractList.java:358)
at net.corda.core.transactions.LedgerTransaction.createLtxForVerification(LedgerTransaction.kt:668)
at net.corda.core.transactions.LedgerTransaction.access$createLtxForVerification(LedgerTransaction.kt:44)
at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:154)
at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:44)
at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder$withAttachmentsClassloaderContext$1.invoke(AttachmentsClassLoader.kt:345)
at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext(AttachmentsClassLoader.kt:344)
at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext$default(AttachmentsClassLoader.kt:319)
at net.corda.core.transactions.LedgerTransaction.internalPrepareVerify$core(LedgerTransaction.kt:146)
at net.corda.core.transactions.LedgerTransaction.verify(LedgerTransaction.kt:136)
at net.corda.core.transactions.TransactionBuilder.addMissingDependency(TransactionBuilder.kt:185)
at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core(TransactionBuilder.kt:165)
at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core$default(TransactionBuilder.kt:133)
at net.corda.core.transactions.TransactionBuilder.toWireTransaction(TransactionBuilder.kt:130)
at net.corda.testing.dsl.TestTransactionDSLInterpreter.toWireTransaction$test_utils(TestDSL.kt:131)
at net.corda.testing.dsl.TestTransactionDSLInterpreter.verifies(TestDSL.kt:175)
at net.corda.testing.dsl.Verifies$DefaultImpls.failsWith(LedgerDSLInterpreter.kt:45)
at net.corda.testing.dsl.TransactionDSLInterpreter$DefaultImpls.failsWith(TransactionDSLInterpreter.kt)
at net.corda.testing.dsl.TestTransactionDSLInterpreter.failsWith(TestDSL.kt:74)
at net.corda.testing.dsl.Verifies$DefaultImpls.fails(LedgerDSLInterpreter.kt:75)
at net.corda.testing.dsl.TransactionDSLInterpreter$DefaultImpls.fails(TransactionDSLInterpreter.kt)
at net.corda.testing.dsl.TestTransactionDSLInterpreter.fails(TestDSL.kt:74)
at net.corda.testing.dsl.TransactionDSL.fails(TransactionDSLInterpreter.kt)
at com.template.contracts.ContractTests.lambda$MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction$8(ContractTests.java:134)
at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt:54)
at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt)
at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt:39)
at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt)
at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt:231)
at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt)
at net.corda.testing.common.internal.CommonSerializationTestHelpersKt.asContextEnv(CommonSerializationTestHelpers.kt:11)
at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv(InternalSerializationTestHelpers.kt:33)
at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv$default(InternalSerializationTestHelpers.kt:31)
at net.corda.testing.internal.InternalTestUtilsKt.withTestSerializationEnvIfNotSet(InternalTestUtils.kt:231)
at net.corda.testing.node.NodeTestUtils.ledger(NodeTestUtils.kt:36)
at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt:53)
at net.corda.testing.node.NodeTestUtils.transaction$default(NodeTestUtils.kt:51)
at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt)
at com.template.contracts.ContractTests.MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction(ContractTests.java:130)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)
Caused by: java.lang.ClassNotFoundException: net.corda.core.contracts.CommandData
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at net.corda.core.serialization.internal.AttachmentsClassLoader.loadClass(AttachmentsClassLoader.kt:289)
... 115 more
build.gradle from Contract module
apply plugin: 'net.corda.plugins.cordapp'
apply plugin: 'net.corda.plugins.cordformation'
cordapp {
targetPlatformVersion corda_platform_version
minimumPlatformVersion corda_platform_version
contract {
name "Template CorDapp"
vendor "Corda Open Source"
licence "Apache License, Version 2.0"
versionId 1
}
}
sourceSets {
main{
java {
srcDir 'src/main/java'
java.outputDir = file('bin/main')
}
}
test{
java{
srcDir 'src/test/java'
java.outputDir = file('bin/test')
}
}
}
dependencies {
// Corda dependencies.
cordaCompile "$corda_release_group:corda-core:$corda_release_version"
cordaRuntime "$corda_release_group:corda:$corda_release_version"
testCompile "$corda_release_group:corda-node-driver:$corda_release_version"
}
It looks like something wrong with your project structure since it is a NoClassDefFoundError of a core package.
Try closing the project and also removing the project from your recent project list.
And open the project folder then follow the prompt to import Gradle project.
Edit Configurations and choose "JAR manifest" for "Shorten command line":

Can not Create a Mock call for Method for Junit

Hi So I'm new to Junit and Mockito, so please bare with some misconception/mistakes that Ive made. I have a springbott service that I wanted to test and I want to mock a method call that is being made in one of the methods that I am testing but It will not work for some reason. I used both when(xxx.method(anyArgs)).return(someData) as well as doReturn(someData).when(xxx).method(anyArgs); But I still get the same type of error: InvalidUseOfMatchersException. I mock the service layer but I can not figure out what causes the issue.
The Exact Stack Trace:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
My Service Layer Code:
// imports here
#Service
#AllArgsConstructor
public class EventServiceImpl implements EventService {
private EventModelRepo eventModelRepo;
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
// methods that dont matter
public int createAPost(EventDetails eventDetails) {
//Some where here the isOwner(STRING) is called
}
public static void getRequest(String reqUrl) throws IOException {
GenericUrl url = new GenericUrl(reqUrl);
HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
HttpResponse response = request.execute();
InputStream is = response.getContent();
int ch;
while ((ch = is.read()) != -1) {
System.out.print((char) ch);
}
response.disconnect();
}
public boolean isOwner(String Owner) {
try {
getRequest("http://localhost:9024/login/isAuth?Username=" + Owner);
} catch (HttpResponseException e) {
System.out.println("Error: " + e.getContent());
return false;
} catch (IOException e) {
System.out.println("Could Not Connect To Site/Make Said Request. \nAre You In Testing? \nIf So This Is Ok.");
}
return true;
}
}
And here is my Junit:
//imports
#RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {
#Mock
private EventModelRepo eventModelRepo;
#InjectMocks
private EventServiceImpl eventServiceImpl ;
#Test
public void validatePostDataTest() {
// mocking the HTTP Call in isOwner()
HttpTransport transport = new MockHttpTransport();
HttpRequest request = null;
try {
request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpResponse response = request.execute();
} catch (IOException e) {
e.printStackTrace();
}
EventDetails eventDetails = new EventDetails("username1", "resturant", "idk", "location.", ".com",
"no", "no p", "spring", "fair", "tes");
//If Owner Isn't Validate As Owner/Signed In
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
//doReturn(false).when(eventServiceImpl).isOwner(anyString());
eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);
}
}
So turns out one of the commentors on my post was correct. You can not mock a call from a #InjectMocks. But if you want to you need to have another annotation added to it. That annotation being #Spy. This annotation should be added in the test class, above the #InjectMocks.
More can be found here
#RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {
#Mock
private EventModelRepo eventModelRepo;
#Spy
#InjectMocks
private EventServiceImpl eventServiceImpl ;
#Test
public void validatePostDataTest() {
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);
}
}

Firebase admin sdk: IllegalArgumentException, Preconditions.checkArgument

I am getting the error below:
java.lang.IllegalArgumentException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:111)
at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
at com.google.api.client.json.webtoken.JsonWebSignature$Parser.parse(JsonWebSignature.java:599)
at com.google.firebase.auth.FirebaseToken.parse(FirebaseToken.java:44)
at com.google.firebase.auth.FirebaseAuth$4.execute(FirebaseAuth.java:456)
at com.google.firebase.auth.FirebaseAuth$4.execute(FirebaseAuth.java:449)
at com.google.firebase.internal.CallableOperation.call(CallableOperation.java:36)
at com.google.firebase.auth.FirebaseAuth.verifyIdToken(FirebaseAuth.java:413)
at d.d.pamper.test.ApplicationTest.testFire2(ApplicationTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
I realize the stack is not very helpful. I've debugged inside the Admin SDK. It reads my service json correctly, the FirebaseAuth.getInstance() is not null, I can see my project id get set correctly.
This is how I'm initializing:
if(FirebaseApp.getApps().size() > 0) {
System.out.println("initialized already ");
return;
}
FirebaseOptions options = null;
try {
System.out.println("try initializing");
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(gservicesConfig.getInputStream()))
.setDatabaseUrl("https://pamperanywhere.firebaseio.com")
.build();
} catch (IOException e) {
e.printStackTrace();
}
FirebaseApp.initializeApp(options);
return;
This is how I'm testing my token:
#Test
public void testFire2() {
String idToken = "REFRESH TOKEN FROM FIREBASE";
if(!StringUtils.isEmpty(idToken)) {
FirebaseToken firebaseToken = null;
if(FirebaseAuth.getInstance() == null) {
System.out.println("FirebaseAuth.getInstance() == null");
}
try {
firebaseToken = FirebaseAuth.getInstance().verifyIdToken(idToken, true);
} catch (IllegalArgumentException e) {
System.out.println("exception+IllegalArgumentException");
e.printStackTrace();
} catch (FirebaseAuthException e) {
System.out.println("exception+FirebaseAuthException");
e.printStackTrace();
}
if (firebaseToken == null) {
System.out.println("firebaseToken == null");
}
}
}
I'm not sure why its throwing IllegalArgumentException. I'm able to login to the application fine (front end), I see my refresh token (front end) but on the Admin side its giving me this issue. I am sure I'm passing the correct token because I can login and see the token (front end).
Maven is:
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.2.0</version>
</dependency>
Thank you for your help.
An ID token should be a valid JWT with 3 segments (separated by dots). Refresh tokens are certainly not that. Therefore the underlying token parser is failing with the above assertion error. Here's the relevant bit of code from the Google API client. Basically it cannot find any dots in the given token string.
public JsonWebSignature parse(String tokenString) throws IOException {
// split on the dots
int firstDot = tokenString.indexOf('.');
Preconditions.checkArgument(firstDot != -1);
...
There's a listener:
firebase.auth().onIdTokenChanged((user: firebase.User) => {
console.log("onIdTokenChanged");
if(user && user.uid) {
user.getIdToken(false)
.then((data: any) => {
console.log("data: ", data);
this.idToken = data;
});
}
});
this gets invoked every one hour. I thought I had to implement this logic myself!
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onIdTokenChanged
From official; above is from Ionic2/Angular2, I have that in a dataServiceProvider 's constructor.
firebase.auth().onIdTokenChanged(function(user) {
if (user) {
// User is signed in or token was refreshed.
}
});

java opencv native library and memory limit

I need to allocate rather large matrix using OpenCV 3.1.0. I'm running following code with -Djava.library.path=$MODULE_DIR$\opencv\310\windows\x64\ -Xmx8g arguments:
public class MatTest extends BaseTest {
static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME);}
#Test
public void tooBig() throws IOException {
float[] data = new float[13320*67294];
Mat iMatrix = new Mat(13320, 67294, CvType.CV_32FC1);
iMatrix.put(0, 0, data); //exception here
}
#Test
public void medium() throws IOException {
float[] data = new float[13918*13240];
Mat iMatrix = new Mat(13918, 13240, CvType.CV_32FC1);
iMatrix.put(0, 0, data);
}
}
The first test works, since the seconds throws (line: iMatrix.put(0, 0, data))
java.lang.Exception: unknown exception
at org.opencv.core.Mat.nPutF(Native Method)
at org.opencv.core.Mat.put(Mat.java:953)
at my.app.MatTest.tooBig(MatTest.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
Is it a OpenCV or native library usage limitation? Is there a workaround for such issue?
Edited: attached full code and stacktrace
It is OpenCV issue. There are some variables of signed int type as a matrix size which was exceeded by my huge array. Check source code: link. The workaround is to create the list of smaller Mats and join them using vconcat(slices, result) function.

Categories