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.
Related
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.
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":
I am new to cryptography. I am working on a poc to encrypt and decrypt a string. When I decrypt the encrypted string it works sometimes but other times throws Tag mismatch error. Am I missing anything?
Here is my code:
EncryptionServiceImpl.java
public class EncryptionServiceImpl {
private static final Logger log = LoggerFactory.getLogger("EncryptionServiceImpl");
private final KeysetHandle keysetHandle;
private final Aead aead;
public EncryptionServiceImpl() throws GeneralSecurityException {
AeadConfig.register();
this.keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM);
aead = AeadFactory.getPrimitive(keysetHandle);
}
public String encrypt(String text) throws GeneralSecurityException {
log.info(String.format("Encrypting %s", text));
byte[] plainText = text.getBytes();
byte[] additionalData = "masterkey".getBytes();
byte[] cipherText = aead.encrypt(plainText,additionalData);
String output = new String(cipherText);
log.info(String.format("The encrypted text: %s", output));
return output;
}
public String decrypt(String text) throws GeneralSecurityException {
log.info(String.format("Decrypting %s", text));
byte[] cipherText = text.getBytes();
byte[] additionalData = "masterkey".getBytes();
byte[] decipheredData = aead.decrypt(cipherText,additionalData);
String output = new String(decipheredData);
log.info(String.format("The decrypted text: %s", output));
return output;
}
}
EncryptionServiceImplTest.java
public class EncryptionServiceImplTest {
#Test
public void encrypt() throws IOException, GeneralSecurityException {
EncryptionServiceImpl encryptionService = new EncryptionServiceImpl();
String encryptedText = encryptionService.encrypt("Hello World");
assertThat(encryptedText, Matchers.notNullValue());
}
#Test
public void decrypt() throws IOException, GeneralSecurityException {
EncryptionServiceImpl encryptionService = new EncryptionServiceImpl();
String encryptedText = encryptionService.encrypt("Hello World");
String decrypedText = encryptionService.decrypt(encryptedText);
assertThat(decrypedText, Matchers.is("Hello World"));
}
}
Exception:
INFO: ciphertext prefix matches a key, but cannot decrypt: javax.crypto.AEADBadTagException: Tag mismatch!
com.encryption.api.service.EncryptionServiceImplTest > decrypt FAILED
java.security.GeneralSecurityException at EncryptionServiceImplTest.java:25
decryption failed
java.security.GeneralSecurityException: decryption failed
at com.google.crypto.tink.aead.AeadFactory$1.decrypt(AeadFactory.java:109)
at com.encryption.api.service.EncryptionServiceImpl.decrypt(EncryptionServiceImpl.java:53)
at com.encryption.api.service.EncryptionServiceImplTest.decrypt(EncryptionServiceImplTest.java:25)
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.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
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.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy1.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:108)
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.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:146)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:128)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
1 test completed, 1 failed
If the byte-sequence of an encrypted message is stored in a string, an appropriate encoding must be used. Appropriate means that the encoding must allow all bytes or byte-combinations in the sequence. If this is not the case, values in the byte-sequence are changed automatically and unnoticed during storage. If a byte-array is then reconstructed from the string during decryption, the original and reconstructed byte-arrays differ and the decryption fails. This is very well explained here.
Since AES-GCM generates a new initialization vector for each encryption, the encrypted message is different for each encryption, even with identical plaintext.
Both leads to the fact that in your example the encryption sometimes works and sometimes not: Whenever the byte-sequence is compatible to the encoding you are using, the decryption works, otherwise not.
If you want to be independent of an encoding, simply use the byte-array itself, i.e. the encrypt-method returns the byte-array instead of a string and analogously, instead of a string the byte-array is passed to the decrypt-method.
I revised the code but still I see that the decryption fails for the same request sometimes.
public class Utils {
private static final Logger log = LoggerFactory.getLogger(Utils.class);
private Aead aead;
private static Utils utils;
private Utils() {
try {
AeadConfig.register();
KeysetHandle keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM);
aead = AeadFactory.getPrimitive(keysetHandle);
} catch (GeneralSecurityException e) {
log.error(String.format("Error occured: %s",e.getMessage())).log();
}
}
public static Utils getInstance() {
if(null == utils) {
utils = new Utils();
}
return utils;
}
public String encrypt(String text) throws GeneralSecurityException, UnsupportedEncodingException {
byte[] plainText = text.getBytes("ISO-8859-1");
byte[] additionalData = null;
byte[] cipherText = aead.encrypt(plainText,additionalData);
String output = Base64.getEncoder().encodeToString(cipherText);
return output;
}
public String decrypt(String text) throws GeneralSecurityException, UnsupportedEncodingException {
byte[] cipherText = Base64.getDecoder().decode(text);
byte[] additionalData = null;
byte[] decipheredData = aead.decrypt(cipherText,additionalData);
String output = new String(decipheredData,"ISO-8859-1");
return output;
}
}
I too did not get error in the code when I ran in local machine. But when I deployed in
cloud (google cloud) I started seeing error.
Here is my Junit code:
public class UtilsTest {
private static final Utils cryptographicUtils = Utils.getInstance();
#Test
public void encrypt() throws IOException, GeneralSecurityException {
String encryptedText = cryptographicUtils.encrypt("Hello World");
assertThat(encryptedText, Matchers.notNullValue());
}
#Test
public void decrypt() throws IOException, GeneralSecurityException {
String encryptedText = cryptographicUtils.encrypt("Hello 123456");
String decrypedText = cryptographicUtils.decrypt(encryptedText);
assertThat(decrypedText, Matchers.is("Hello 123456"));
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am quite new to Java and JUnit testing and am very confused with an error I am getting. The error, Null Pointer exception as the code below I am guessing is because something is equal to null but i am unsure why.
java.lang.NullPointerException
at com.nsa.y1.trafficlights.FourWayJunctionTest.PhaseOneInitiation(FourWayJunctionTest.java:47)
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:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
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.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
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.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
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.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:377)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745) com.nsa.y1.trafficlights.FourWayJunctionTest > PhaseOneInitiation FAILED
java.lang.NullPointerException at FourWayJunctionTest.java:47
Here is the test file:
package com.nsa.y1.trafficlights;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by c167 on 12/03/2017.
*/
public class FourWayJunctionTest {
private Light greenLight, amberLight, redLight, greenRightArrow, greenLeftArrow;
private FourLightTrafficLight turnRightTrafficLight;
boolean lightStateRed;
boolean lightStateAmber;
boolean lightStateGreen;
private TrafficLight northLeftStraight;
private FourLightTrafficLight northLeftArrow;
private FourLightTrafficLight northRightArrow;
private TrafficLight eastLeftStraight;
private TrafficLight westStraightRight;
private FourWayJunction junction = new FourWayJunction();
#Before
public void createLights() throws Exception {
greenLight = (new Light(Shape.CIRCLE, Colour.GREEN));
amberLight = (new Light(Shape.CIRCLE, Colour.AMBER));
redLight = (new Light(Shape.CIRCLE, Colour.RED));
northRightArrow = new FourLightTrafficLight();
northLeftArrow = new FourLightTrafficLight();
northLeftStraight = new TrafficLight();
eastLeftStraight = new TrafficLight();
westStraightRight = new TrafficLight();
}
#Test
public void PhaseOneInitiation() throws Exception {
createLights();
//Greenleftarrow should be on, northleft on, and eat left on. All others off.
junction.initiatePhaseOne();
assertEquals(greenLeftArrow.isOn(), true);
}
}
This is the code containing the methods:
package com.nsa.y1.trafficlights;
/**
* Created by on 13/03/2017.
*/
public class FourWayJunction extends FourLightTrafficLight{
// Evans junction recreation in cardiff
private Light greenLight, amberLight, redLight, greenRightArrow, greenLeftArrow;
private TrafficLight oppositeTrafficLight;
private FourLightTrafficLight turnRightTrafficLight;
boolean lightStateRed;
boolean lightStateAmber;
boolean lightStateGreen;
private TrafficLight northLeftStraight;
private FourLightTrafficLight northLeftArrow;
private FourLightTrafficLight northRightArrow;
private TrafficLight eastLeftStraight;
private TrafficLight westStraightRight;
public FourWayJunction() {
greenLight = (new Light(Shape.CIRCLE, Colour.GREEN));
amberLight = (new Light(Shape.CIRCLE, Colour.AMBER));
redLight = (new Light(Shape.CIRCLE, Colour.RED));
northRightArrow = new FourLightTrafficLight();
northLeftArrow = new FourLightTrafficLight();
northLeftStraight = new TrafficLight();
eastLeftStraight = new TrafficLight();
westStraightRight = new TrafficLight();
}
public void initiatePhaseOne() {
// Left arrow for buses and taxis on, north green light for left on but no right arrow.
// Also green light on for the East Traffic light.
// All others off.
westStraightRight.getRedLight().turnOn();
northRightArrow.getGreenLight().turnOff();
if (westStraightRight.getRedLight().isOn() && !northRightArrow.getGreenLight().isOn()){
northLeftArrow.getGreenLight().turnOn();
northLeftStraight.setTrafficLightOn(northLeftStraight);
eastLeftStraight.setTrafficLightOn(eastLeftStraight);
}
else {
System.out.println("Problems, traffic wil collide");
westStraightRight.setTrafficLightOff(westStraightRight);
northRightArrow.getGreenLight().turnOff();
}
}
public void initiatePhaseTwo() {
// North left straight, left arrow, and right arrow are on.
// West straight right light off.
// East Left Straight light is off.
if (!eastLeftStraight.getRedLight().isOn()) {
eastLeftStraight.setTrafficLightOff(eastLeftStraight);
northRightArrow.getGreenLight().turnOn();
}
else {
northRightArrow.getGreenLight().turnOn();
}
}
public void initiatePhaseThree() {
// All lights are off except for the EastStraightRight light.
if (northRightArrow.getGreenLight().isOn() && !northLeftStraight.getRedLight().isOn() &&
northLeftArrow.getGreenLight().isOn()) {
northRightArrow.getGreenLight().turnOff();
northLeftArrow.getGreenLight().turnOff();
northLeftStraight.setTrafficLightOff(northLeftStraight);
}
else {
eastLeftStraight.setTrafficLightOn(eastLeftStraight);
}
}
public FourLightTrafficLight getTrafficLight(FourLightTrafficLight light) {
return light;
}
}
public void setTrafficLightOn(TrafficLight trafficLight) {
trafficLight.getRedLight().turnOff();
LightPause();
trafficLight.getAmberLight().turnOn();
LightPause();
trafficLight.getGreenLight().turnOn();
}
public void setTrafficLightOff(TrafficLight trafficLight) {
trafficLight.getGreenLight().turnOff();
LightPause();
trafficLight.getGreenLight().turnOff();
trafficLight.getAmberLight().turnOn();
LightPause();
trafficLight.getRedLight().turnOn();
}
Thanks for your help :)
greenLeftArrow is not initialized to a value (it's automatically initialized to null) so calling greenLeftArrow.isOn() in the PhaseOneInitialization method will throw a NullPointerException.
You should initialize greenLeftArrow object first like you did for example greenLight. You cannot call methods on not initialized objects.
You can also use assertTrue or assertFalse to simplify your code.
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