Java JUnit Test - Java.Lang.NullPointerException [closed] - java

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.

Related

[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":

How to resolve this NullPointerException being thrown from HibernateTemplate's find(String query) method

How do I resolve this NullPointerException ?
A little background , I am developing a Spring based Project and using HibernateTemlate in DAO layer to do all database related operations.
here is the snippet of code which i have extracted out of my test class which is throwing NullPointerException.
try {
List<Object[]> list = (List<Object[]>) ht.find("select uomId,uomModel from in.nit.model.Uom");
System.out.println(list);
}catch(NullPointerException e) {
e.printStackTrace();
}
And this is the stacktrace of the exception on the console.
```
java.lang.NullPointerException
at in.nit.dao.impl.UomDaoImplTest.test(UomDaoImplTest.java:28)
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:567)
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.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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
```
Here is my model class
```
#Entity
#Table(name="uomtab")
public class Uom {
#Id #GeneratedValue #Column(name="umid") private Integer uomId;
#Column(name="utype") private String uomType;
#Column(name="umodel") private String uomModel;
#Column(name="udesc") private String uomDesc;
public Uom() {
super();
}
public Uom(Integer uomId) {
this.uomId = uomId;
}
public Integer getUomId() {
return uomId;
}
public void setUomId(Integer uomId) {
this.uomId = uomId;
}
public String getUomType() {
return uomType;
}
public void setUomType(String uomType) {
this.uomType = uomType;
}
public String getUomModel() {
return uomModel;
}
public void setUomModel(String uomModel) {
this.uomModel = uomModel;
}
public String getUomDesc() {
return uomDesc;
}
public void setUomDesc(String uomDesc) {
this.uomDesc = uomDesc;
}
#Override
public String toString() {
return "Uom [uomId=" + uomId + ", uomType=" + uomType + ", uomModel=" + uomModel + ",
uomDesc=" + uomDesc + "]";
}
}
```
Also even though the find(String Query) method is deprecated,I have extensively used it in other dao classes of my project which works smooth and fine.
What could be the possible reasons for this exception blowing up my code?
You shouldn't catch that NullPointerException
What is line 28 in your code?
Did you try and debug the line? If it is the ht.find line, the only thing that makes sense is that your HibernateTemplate is null and has not been set correctly.
your error is in class "UomDaoImplTest". That has no relation with Hibernate Template.
can you post your test class.

java.lang.reflect.InvocationTargetException JavaFX TableView

I've encountered this problem while trying to use cellData -> cellData.getValue() to add an attribute from an object, the attribute is a StringProperty and i have a method to return it, and i'm using it in the cellData -> cellData.getValue().methodtoreturnproperty, but it's still giving me java.lang.reflect.InvocationTargetException, does anyone know what i'm doing wrong?
Here's the code:
package projeto.resources;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import projeto.Filmes;
import projeto.MainApp;
import projeto.Sala;
public class FilmeOverviewController {
#FXML
private TableView<Filmes> filmeTable;
#FXML
private TableColumn<Filmes, String> nomeColumn;
#FXML
private TableColumn<Filmes, String> categoriaColumn;
#FXML
private TableColumn<Filmes, String> salaColumn;
#FXML
private Label nomeLabel;
#FXML
private Label salaLabel;
#FXML
private Label categoriaLabel;
#FXML
private Label diretorLabel;
#FXML
private Label duracaoLabel;
#FXML
private Label protagonistaLabel;
#FXML
private Label classificacaoLabel;
// Reference to the main application.
private MainApp mainApp;
public FilmeOverviewController() {
}
#FXML
private void initialize() {
//Inicia a tableview com tres colunas.
nomeColumn.setCellValueFactory(cellData -> cellData.getValue().nomeProperty());
categoriaColumn.setCellValueFactory(cellData -> cellData.getValue().categoriaProperty());
salaColumn.setCellValueFactory(cellData -> cellData.getValue().numeroProperty());
// limpando os detalhes
showFilmeDetails(null);
// adicionando funcao
filmeTable.getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> showFilmeDetails(newValue));
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
//adiciona uma observable list
filmeTable.setItems(mainApp.getfilmeDados());
}
private void showFilmeDetails(Filmes filme) {
if (filme != null) {
nomeLabel.setText(filme.getNome());
categoriaLabel.setText(filme.getCategoria());
duracaoLabel.setText(filme.getDuracao());
protagonistaLabel.setText(filme.getProtagonista());
classificacaoLabel.setText(filme.getClassificacao());
diretorLabel.setText(filme.getDiretor());
salaLabel.setText(filme.getSalaN());
} else {
nomeLabel.setText("");
categoriaLabel.setText("");
duracaoLabel.setText("");
protagonistaLabel.setText("");
classificacaoLabel.setText("");
diretorLabel.setText("");
salaLabel.setText("");
}
}
#FXML
private void handleDeletarFilme() {
int selectedIndex = filmeTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
filmeTable.getItems().remove(selectedIndex);
} else {
Alert alerta = new Alert(AlertType.WARNING);
alerta.setTitle("Nenhum filme selecionado");
alerta.setHeaderText("Nenhuma Selecao");
alerta.setContentText("Por favor selecione um filme para deletar");
alerta.showAndWait();
}
}
#FXML
private void handleNovoFilme() {
Filmes tempFilme = new Filmes("Nome","Categoria");
boolean clicado = mainApp.showEditarFilmeDialog(tempFilme);
if (clicado) {
mainApp.getfilmeDados().add(tempFilme);
}
}
#FXML
private void handleEditarFilme() {
Filmes filmeSelecionado = filmeTable.getSelectionModel().getSelectedItem();
if(filmeSelecionado != null) {
boolean clicado = mainApp.showEditarFilmeDialog(filmeSelecionado);
if(clicado) {
showFilmeDetails(filmeSelecionado);
}
}else {
//se nada for selecionado
Alert alerta = new Alert(AlertType.WARNING);
alerta.initOwner(mainApp.getPrimaryStage());
alerta.setTitle("Nenhuma selecao");
alerta.setHeaderText("Nenhum filme selecionado");
alerta.setContentText("Por favor selecione algum filme.");
alerta.showAndWait();
}
}
}
There's a class called Sala, that's being imported into this controller, i could make it work with another class called Filmes, i don't know exactly why it's not working with the class Sala, here's the code in the class:
package projeto;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Sala {
private boolean e3d;
private int assentosMax;
private int assentosDisp;
private final StringProperty numeroProperty = new SimpleStringProperty();
public Sala(boolean e3d, int assentosMax, int assentosDisp, String numero) {
setNumero(numero);
e3d = this.e3d;
assentosMax = this.assentosMax;
assentosDisp = this.assentosDisp;
}
public boolean isE3d() {
return e3d;
}
public void setE3d(boolean e3d) {
this.e3d = e3d;
}
public int getAssentosMax() {
return assentosMax;
}
public void setAssentosMax(int assentosMax) {
this.assentosMax = assentosMax;
}
public int getAssentosDisp() {
return assentosDisp;
}
public void setAssentosDisp(int assentosDisp) {
this.assentosDisp = assentosDisp;
}
public StringProperty numeroProperty() {
return numeroProperty;
}
public final String getNumero() {
return numeroProperty.get();
}
public final void setNumero(String numero) {
numeroProperty().set(numero);
}
}
Edit: Here's the error:
jun 07, 2018 3:18:37 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 9.0.1 by JavaFX runtime of version 8.0.171
Exception in Application start method
java.lang.reflect.InvocationTargetException
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.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
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 sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.Error: Unresolved compilation problem:
The method numeroProperty() is undefined for the type Filmes
at projeto.resources.FilmeOverviewController.<init>(FilmeOverviewController.java:50)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:51)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at projeto.MainApp.showFilmeOverview(MainApp.java:59)
at projeto.MainApp.start(MainApp.java:50)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
... 1 more
Exception running application projeto.MainApp
Thanks in advance!
This looks like you are expecting one type of object in the table but providing another.
You define your table like this:
#FXML
private TableColumn<Filmes, String> salaColumn;
Your cell value factory is trying to get the following:
salaColumn.setCellValueFactory(cellData -> cellData.getValue().numeroProperty());
The numeroProperty is on the Sala object, not the Filmes Object.
Try the following (Though I am not 100% sure, since your definition of Filmes is not in the question):
salaColumn.setCellValueFactory(cellData -> cellData.getValue().getSala().numeroProperty());
Also - if there is a chance that the Sala object could be null, you'll want to check for that before trying to access the numeroProperty().

Adding FilteredList and SortedList to make a Search bar in Javafx returns java.lang.reflect.InvocationTargetException

I am trying to make a Search bar using JFXTextField in Javafx8. But when I add FilteredList and SortedList in my Code, The Application no longer run and Output shows the following Exception:
Exception in Application start method
java.lang.reflect.InvocationTargetException
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.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
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 sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: javafx.fxml.LoadException: file:/C:/Users/Zed%20and%20White/Documents/NetBeansProjects/Project_EMS/dist/run1317715357/Project_EMS.jar!/project_ems/FrontEnd.fxml:22
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at project_ems.Project_EMS.start(Project_EMS.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
... 1 more
Caused by: java.lang.NullPointerException
at javafx.collections.transformation.TransformationList.<init>(TransformationList.java:65)
at javafx.collections.transformation.FilteredList.<init>(FilteredList.java:66)
at javafx.collections.transformation.FilteredList.<init>(FilteredList.java:87)
at project_ems.FrontEndController.<init>(FrontEndController.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:51)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
... 17 more
Exception running application project_ems.Project_EMS
I have followed this method Create Search TextField to Search in a Javafx table
Here's my Code:
ObservableList:
private ObservableList<DataHandler_ExamsListing> EListingData;
Block of Code that Uses the Above Observable List:
private void LoadEListingData(){
try {
DBE.resultSet = DBE.statement.executeQuery("SELECT * FROM Exam");
EListingData = FXCollections.observableArrayList();
while (DBE.resultSet.next()) {
EListingData.add(new DataHandler_ExamsListing(DBE.resultSet.getInt("ExamID"),DBE.resultSet.getString("ExamName"),DBE.resultSet.getString("ExamDate"),DBE.resultSet.getString("ExamComment")));
}
EListingTable.setItems(EListingData);
} catch (SQLException e) {
}
}
FilteredList and SortedList (Both are Global):
private final FilteredList<DataHandler_ExamsListing> FilteredData = new FilteredList<>(EListingData);
private final SortedList<DataHandler_ExamsListing> sortedData = new SortedList<>(FilteredData);
SearchBar FXML:
#FXML // fx:id="SearchExam_Elisting"
private JFXTextField SearchExam_Elisting; // Value injected by FXMLLoader
ActionEvent on SearchBar:
#FXML
private void SearchExamList(ActionEvent event) {
SearchExam_Elisting.textProperty().addListener((observable, oldValue, newValue) -> {
FilteredData.setPredicate(DataHandler_ExamsListing -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (DataHandler_ExamsListing.getExamName().toLowerCase().contains(lowerCaseFilter)) {
return true;
}
return false;
});
});
sortedData.comparatorProperty().bind(EListingTable.comparatorProperty());
EListingTable.setItems(sortedData);
System.out.println("DOne");
}
if I comment out FilteredList and SortedList and the ActionEvent, The App runs smoothly.
Please help me resolve this Issue. Thanks!
I don't know what you mean by "Both are global". The closest thing to a global scope would be static fields and none of the fields is declared as static.
But as for the issue in the question:
You're initializing the FilteredData field when declaring it which results in the assignment being executed even before a constructor would be executed. This means there is no way the LoadEListingData is executed before the assignment
FilteredData = new FilteredList<>(EListingData);
for this reason EListingData is still null at that time. This is not allowed though.
You need change the time this field is initialized, e.g. to after loading the data using the LoadEListingData.
Alternatively you could initialize the field with a empty ObservableList and fill this list later when the LoadEListingData method is called:
private final ObservableList<DataHandler_ExamsListing> EListingData = FXCollections.observableArrayList();
private final FilteredList<DataHandler_ExamsListing> FilteredData = new FilteredList<>(EListingData);
private final SortedList<DataHandler_ExamsListing> sortedData = new SortedList<>(FilteredData);
#FXML
private void initialize() {
EListingTable.setItems(sortedData);
}
private void LoadEListingData(){
List<DataHandler_ExamsListing> data = new ArrayList<>();
try {
// prepare data for insert using single update
DBE.resultSet = DBE.statement.executeQuery("SELECT * FROM Exam"); // directly accessing static fields of a different class is a terrible idea since it violates the information hiding principle
while (DBE.resultSet.next()) {
data.add(new DataHandler_ExamsListing(DBE.resultSet.getInt("ExamID"),DBE.resultSet.getString("ExamName"),DBE.resultSet.getString("ExamDate"),DBE.resultSet.getString("ExamComment")));
}
} catch (SQLException e) {
e.printStackTrace(); // Never just ignore an exception unless it's expected
return;
}
// update data
EListingData.setAll(data);
}

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