I'm trying to execute a web service based on its owls description file using owls-api-3.1.
The web service is a simple jax-ws service deployed using grizzly, the owls file is generated using the WSDL2OWLS class found in the code examples (downloaded and extracted from the src jar), the code is hosted in this github repository.
(the web service is well tested using soapUI)
The web service definition
#WebService(serviceName = "Hello", targetNamespace = HelloService.WSDL_FILE)
public class HelloService {
public static final String ROUTE = "/hello";
public static final String OWLS_FILE = Bootstrap.OWLS_DIR + "/hello.owl";
public static final String WSDL_FILE = "HTTP://127.0.0.1/hello?wsdl";
/**
* This is a sample web service operation
*
* #param name
* #return
*/
#WebMethod(operationName = "hello")
public String hello(#WebParam(name = "name") String name) {
return "Hello " + name;
}
}
The web service deployment
HttpServer httpServer = new HttpServer();
NetworkListener networkListener = new NetworkListener("grizzly", "0.0.0.0", 8080);
httpServer.addListener(networkListener);
httpServer.getServerConfiguration().addHttpHandler(new CLStaticHttpHandler(Bootstrap.class.getClassLoader(), "static/"), "/");
httpServer.getServerConfiguration().addHttpHandler(new JaxwsHandler(new HelloService()), HelloService.ROUTE);
httpServer.start();
Thread.sleep(2 * 1000); // The services are up and running
System.out.println(" --- OWLS client --- ");
new HelloServiceOWLSClient().start();
Thread.currentThread().join();
The OWLS client
public class HelloServiceOWLSClient {
private static final Logger LOG = Logger.getLogger(HelloServiceOWLSClient.class.getName());
public void start() {
try {
OWLKnowledgeBase kb = OWLFactory.createKB();
Service service = kb.readService(URI.create(HelloService.OWLS_FILE));
Process process = service.getProcess();
ProcessExecutionEngine executionEngine = OWLSFactory.createExecutionEngine();
ValueMap<Input, OWLValue> inputs = new ValueMap<>();
inputs.setValue(process.getInput("name"), kb.createDataValue("tarrsalah"));
LOG.log(Level.INFO, inputs.debugString());
ValueMap<Output, OWLValue> outputs = executionEngine.execute(process, inputs, kb);
LOG.log(Level.INFO, outputs.debugString());
} catch (IOException | ExecutionException ex) {
LOG.log(Level.SEVERE, ex.toString());
} finally {
}
}
}
The complete stack trace
May 25, 2014 1:34:33 AM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [0.0.0.0:8080]
May 25, 2014 1:34:34 AM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
--- OWLS client ---
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://www.daml.org/services/owl-s/1.2/Service.owl# ...
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://www.daml.org/services/owl-s/1.2/Profile.owl# ...
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://www.daml.org/services/owl-s/1.2/ActorDefault.owl# ...
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://www.daml.org/services/owl-s/1.2/ServiceParameter.owl# ...
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://www.daml.org/services/owl-s/1.2/ServiceCategory.owl# ...
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://www.daml.org/services/owl-s/1.2/Process.owl# ...
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://www.daml.org/services/owl-s/1.2/generic/ObjectList.owl# ...
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://www.daml.org/services/owl-s/1.2/generic/Expression.owl# ...
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://www.daml.org/services/owl-s/1.2/Grounding.owl# ...
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://on.cs.unibas.ch/owl-s/1.2/MoreGroundings.owl# ...
INFO [org.tarrsalah.owls.examples.Bootstrap.main()] (Vocabulary.java:118) - Loading ontology http://on.cs.unibas.ch/owl-s/1.2/FLAService.owl# ...
May 25, 2014 1:34:38 AM org.tarrsalah.owls.examples.HelloServiceOWLSClient start
INFO: (name = tarrsalah)
May 25, 2014 1:34:39 AM org.tarrsalah.owls.examples.HelloServiceOWLSClient start
INFO: (return = Hello null)
-----
In the last line, I was expected Hello tarrsalah instead of Hello null
The complete owls file generated
<?xml version="1.0"?>
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:grounding="http://www.daml.org/services/owl-s/1.2/Grounding.owl#"
xmlns="http://www.example.org/service.owl"
xmlns:owl="http://www.w3.org/2002/07/owl#"
xmlns:list="http://www.daml.org/services/owl-s/1.2/generic/ObjectList.owl#"
xmlns:expr="http://www.daml.org/services/owl-s/1.2/generic/Expression.owl#"
xmlns:swrl="http://www.w3.org/2003/11/swrl#"
xmlns:service="http://www.daml.org/services/owl-s/1.2/Service.owl#"
xmlns:profile="http://www.daml.org/services/owl-s/1.2/Profile.owl#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:process="http://www.daml.org/services/owl-s/1.2/Process.owl#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xml:base="http://www.example.org/service.owl">
<owl:Ontology rdf:about="">
<owl:imports rdf:resource="http://www.daml.org/services/owl-s/1.2/Grounding.owl"/>
<owl:imports rdf:resource="http://www.daml.org/services/owl-s/1.2/Profile.owl"/>
</owl:Ontology>
<service:Service rdf:ID="helloService">
<service:supports>
<grounding:WsdlGrounding rdf:ID="helloGrounding"/>
</service:supports>
<service:describedBy>
<process:AtomicProcess rdf:ID="helloProcess"/>
</service:describedBy>
<service:presents>
<profile:Profile rdf:ID="helloProfile"/>
</service:presents>
</service:Service>
<profile:Profile rdf:about="#helloProfile">
<profile:hasOutput>
<process:Output rdf:ID="return">
<process:parameterType rdf:datatype="http://www.w3.org/2001/XMLSchema#anyURI"
>http://www.w3.org/2001/XMLSchema#string</process:parameterType>
<rdfs:label>return</rdfs:label>
</process:Output>
</profile:hasOutput>
<profile:hasInput>
<process:Input rdf:ID="name">
<process:parameterType rdf:datatype="http://www.w3.org/2001/XMLSchema#anyURI"
>http://www.w3.org/2001/XMLSchema#string</process:parameterType>
<rdfs:label>name</rdfs:label>
</process:Input>
</profile:hasInput>
<profile:textDescription>Auto generated from HTTP://127.0.0.1/hello?wsdl</profile:textDescription>
<profile:serviceName>hello</profile:serviceName>
<service:presentedBy rdf:resource="#helloService"/>
</profile:Profile>
<process:AtomicProcess rdf:about="#helloProcess">
<process:hasOutput rdf:resource="#return"/>
<process:hasInput rdf:resource="#name"/>
<service:describes rdf:resource="#helloService"/>
<rdfs:label>helloProcess</rdfs:label>
</process:AtomicProcess>
<grounding:WsdlGrounding rdf:about="#helloGrounding">
<grounding:hasAtomicProcessGrounding>
<grounding:WsdlAtomicProcessGrounding rdf:ID="helloAtomicProcessGrounding"/>
</grounding:hasAtomicProcessGrounding>
<service:supportedBy rdf:resource="#helloService"/>
</grounding:WsdlGrounding>
<grounding:WsdlAtomicProcessGrounding rdf:about="#helloAtomicProcessGrounding">
<grounding:wsdlOutput>
<grounding:WsdlOutputMessageMap>
<grounding:wsdlMessagePart rdf:datatype="http://www.w3.org/2001/XMLSchema#anyURI"
>HTTP://127.0.0.1/hello?wsdl#return</grounding:wsdlMessagePart>
<grounding:owlsParameter rdf:resource="#return"/>
</grounding:WsdlOutputMessageMap>
</grounding:wsdlOutput>
<grounding:wsdlInput>
<grounding:WsdlInputMessageMap>
<grounding:wsdlMessagePart rdf:datatype="http://www.w3.org/2001/XMLSchema#anyURI"
>HTTP://127.0.0.1/hello?wsdl#name</grounding:wsdlMessagePart>
<grounding:owlsParameter rdf:resource="#name"/>
</grounding:WsdlInputMessageMap>
</grounding:wsdlInput>
<grounding:wsdlOutputMessage rdf:datatype="http://www.w3.org/2001/XMLSchema#anyURI"
>http://127.0.0.1/hello?wsdl#helloResponse</grounding:wsdlOutputMessage>
<grounding:wsdlInputMessage rdf:datatype="http://www.w3.org/2001/XMLSchema#anyURI"
>http://127.0.0.1/hello?wsdl#hello</grounding:wsdlInputMessage>
<grounding:wsdlDocument rdf:datatype="http://www.w3.org/2001/XMLSchema#anyURI"
>HTTP://127.0.0.1/hello?wsdl</grounding:wsdlDocument>
<grounding:wsdlOperation>
<grounding:WsdlOperationRef>
<grounding:operation rdf:datatype="http://www.w3.org/2001/XMLSchema#anyURI"
>HTTP://127.0.0.1/hello?wsdl#hello</grounding:operation>
</grounding:WsdlOperationRef>
</grounding:wsdlOperation>
<grounding:owlsProcess rdf:resource="#helloProcess"/>
</grounding:WsdlAtomicProcessGrounding>
</rdf:RDF>
It seems that axis 1.4 use rpc soap binding to call a web service, Setting The SOAPBinding to Style.RPC in the web service declaration solves the problem.
WebService(serviceName = "Hello", targetNamespace = "http://127.0.0.1/hello")
#SOAPBinding(style = Style.RPC)
public class HelloService {
public static final String ROUTE = "/hello";
public static final String OWLS_FILE = Bootstrap.OWLS_DIR + "/hello.owl";
public static final String WSDL_FILE = "http://127.0.0.1/hello?wsdl";
/**
* This is a sample web service operation
*
* #param name
* #return
*/
#WebMethod(operationName = "hello")
#WebResult(name="greeting")
public String hello(#WebParam(name = "name") String name) {
return "Hello " + name;
}
}
Related
Anyone having simulator example of OPC UA, I am using OPC UA project https://github.com/OPCFoundation/UA-Java .
I have tried all the server mentioned on this git hub page, but none of them are working for me https://github.com/node-opcua/node-opcua/wiki/publicly-available-OPCUA-servers.
I am using org.opcfoundation.ua.examples.SampleClient utility to check connection and sample values, but not able to do so. If any one having working exampe w.r.t this please share along with code. Once this working I need to configure this setting in apache Nifi to make data pipeline.
code:
public class SampleClient {
public static final Locale ENGLISH = Locale.ENGLISH;
public static final Locale ENGLISH_FINLAND = new Locale("en", "FI");
public static final Locale ENGLISH_US = new Locale("en", "US");
public static final Locale FINNISH = new Locale("fi");
public static final Locale FINNISH_FINLAND = new Locale("fi", "FI");
public static final Locale GERMAN = Locale.GERMAN;
public static final Locale GERMAN_GERMANY = new Locale("de", "DE");
public static void main(String[] args)
throws Exception {
// if (args.length==0) {
// System.out.println("Usage: SampleClient [server uri]");
// return;
// }
//String url = /*args[0]*/"opc.tcp://uademo.prosysopc.com:53530/OPCUA/SimulationServer";
//String url = /*args[0]*/"opc.tcp://uademo.prosysopc.com:53530";
//String url = /*args[0]*/"opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";
String url="opc.tcp://mfactorengineering.com:4840";
//String url="opc.tcp://commsvr.com:51234/UA/CAS_UA_Server";
//String url="opc.tcp://uademo.prosysopc.com:53530/OPCUA/SimulationServer";
//String url="opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";
//String url="opc.tcp://opcua.demo-this.com:51211/UA/SampleServer";
//String url="opc.tcp://opcua.demo-this.com:51212/UA/SampleServer";
//String url="opc.tcp://demo.ascolab.com:4841";
//String url="opc.tcp://alamscada.dynu.com:4096";
System.out.print("SampleClient: Connecting to "+url+" .. ");
////////////// CLIENT //////////////
// Create Client
Application myApplication = new Application();
Client myClient = new Client(myApplication);
myApplication.addLocale( ENGLISH );
myApplication.setApplicationName( new LocalizedText("Java Sample Client", Locale.ENGLISH) );
myApplication.setProductUri( "urn:JavaSampleClient" );
CertificateUtils.setKeySize(1024); // default = 1024
KeyPair pair = ExampleKeys.getCert("SampleClient");
myApplication.addApplicationInstanceCertificate( pair );
// The HTTPS SecurityPolicies are defined separate from the endpoint securities
myApplication.getHttpsSettings().setHttpsSecurityPolicies(HttpsSecurityPolicy.ALL);
// Peer verifier
myApplication.getHttpsSettings().setHostnameVerifier( SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER );
myApplication.getHttpsSettings().setCertificateValidator( CertificateValidator.ALLOW_ALL );
// The certificate to use for HTTPS
KeyPair myHttpsCertificate = ExampleKeys.getHttpsCert("SampleClient");
myApplication.getHttpsSettings().setKeyPair( myHttpsCertificate );
// Connect to the given uri
SessionChannel mySession = myClient.createSessionChannel(url);
// mySession.activate("username", "123");
mySession.activate();
//////////////////////////////////////
///////////// EXECUTE //////////////
// Browse Root
BrowseDescription browse = new BrowseDescription();
browse.setNodeId( Identifiers.RootFolder );
browse.setBrowseDirection( BrowseDirection.Forward );
browse.setIncludeSubtypes( true );
browse.setNodeClassMask( NodeClass.Object, NodeClass.Variable );
browse.setResultMask( BrowseResultMask.All );
BrowseResponse res3 = mySession.Browse( null, null, null, browse );
System.out.println(res3);
// Read Namespace Array
ReadResponse res5 = mySession.Read(
null,
null,
TimestampsToReturn.Neither,
new ReadValueId(Identifiers.Server_NamespaceArray, Attributes.Value, null, null )
);
String[] namespaceArray = (String[]) res5.getResults()[0].getValue().getValue();
System.out.println(Arrays.toString(namespaceArray));
// Read a variable
ReadResponse res4 = mySession.Read(
null,
500.0,
TimestampsToReturn.Source,
new ReadValueId(new NodeId(6, 1710), Attributes.Value, null, null )
);
System.out.println(res4);
res4 = mySession.Read(
null,
500.0,
TimestampsToReturn.Source,
new ReadValueId(new NodeId(6, 1710), Attributes.DataType, null, null )
);
System.out.println(res4);
///////////// SHUTDOWN /////////////
mySession.close();
mySession.closeAsync();
//////////////////////////////////////
}
}
exception:
SampleClient: Connecting to opc.tcp://mfactorengineering.com:4840 .. 2017-07-20 11:24:34,909 [main] INFO CryptoUtil - SecurityProvider initialized from org.bouncycastle.jce.provider.BouncyCastleProvider
2017-07-20 11:24:34,909 [main] INFO CryptoUtil - Using SecurityProvider BC
2017-07-20 11:24:35,549 [main] INFO TcpConnection - mfactorengineering.com/184.173.118.46:4840 Connecting
2017-07-20 11:24:36,142 [main] INFO TcpConnection - mfactorengineering.com/184.173.118.46:4840 Connected
2017-07-20 11:24:36,753 [main] INFO SecureChannelTcp - 1804305022 Closed
2017-07-20 11:24:36,768 [TcpConnection/Read] INFO TcpConnection - mfactorengineering.com/184.173.118.46:4840 Closed (expected)
2017-07-20 11:24:36,768 [main] INFO TcpConnection - mfactorengineering.com/184.173.118.46:4840 Closed
2017-07-20 11:24:36,768 [main] INFO TcpConnection - mfactorengineering.com/184.173.118.46:4840 Connecting
2017-07-20 11:24:37,408 [main] INFO TcpConnection - mfactorengineering.com/184.173.118.46:4840 Connect failed
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.net.SocketInputStream.read(SocketInputStream.java:223)
at org.opcfoundation.ua.utils.bytebuffer.InputStreamReadable._get(InputStreamReadable.java:53)
at org.opcfoundation.ua.utils.bytebuffer.InputStreamReadable.getInt(InputStreamReadable.java:144)
at org.opcfoundation.ua.transport.tcp.io.TcpConnection.open(TcpConnection.java:500)
at org.opcfoundation.ua.transport.tcp.io.SecureChannelTcp.open(SecureChannelTcp.java:565)
at org.opcfoundation.ua.application.Client.createSecureChannel(Client.java:641)
at org.opcfoundation.ua.application.Client.createSecureChannel(Client.java:555)
at org.opcfoundation.ua.application.Client.createSessionChannel(Client.java:370)
at org.opcfoundation.ua.application.Client.createSessionChannel(Client.java:345)
at org.opcfoundation.ua.examples.SampleClient.main(SampleClient.java:120)
2017-07-20 11:24:37,464 [main] WARN SecureChannelTcp - Connection failed: Bad_CommunicationError (code=0x80050000, description="2147811328, Connection reset")
2017-07-20 11:24:37,464 [main] WARN SecureChannelTcp - Bad_CommunicationError: Retrying
2017-07-20 11:24:37,464 [main] INFO TcpConnection - mfactorengineering.com/184.173.118.46:4840 Connecting
2017-07-20 11:24:38,056 [main] INFO TcpConnection - mfactorengineering.com/184.173.118.46:4840 Connected
2017-07-20 11:24:38,368 [TcpConnection/Read] WARN TcpConnection - mfactorengineering.com/184.173.118.46:4840 Error
org.opcfoundation.ua.common.ServiceResultException: Bad_SecurityChecksFailed (code=0x80130000, description="An error occurred verifying security")
at org.opcfoundation.ua.transport.tcp.io.TcpConnection$ReadThread.run(TcpConnection.java:782)
2017-07-20 11:24:38,368 [TcpConnection/Read] INFO TcpConnection - mfactorengineering.com/184.173.118.46:4840 Closed
Exception in thread "main" org.opcfoundation.ua.common.ServiceResultException: Bad_SecurityChecksFailed (code=0x80130000, description="An error occurred verifying security")
at org.opcfoundation.ua.transport.tcp.io.TcpConnection$ReadThread.run(TcpConnection.java:782)
The example is written such that it always selects the most secure connection, which on the other hand requires that the server accepts the Application Instance Certificate of the client application, before it enables the connection. Bad_SecurityChecksFailed is the standard error code from the server, when it does not accept the client connection.
Since you cannot control these publicly available servers to make them trust your client application, your only alternative is to try to connect without security, if the server allows that.
For this, you need to change the code so that it picks an insecure endpoint.
Replace
SessionChannel mySession = myClient.createSessionChannel(url);
with
EndpointDescription[] endpoints = myClient.discoverEndpoints(url);
// Filter out all but opc.tcp protocol endpoints
endpoints = selectByProtocol(endpoints, "opc.tcp");
// Filter out all but Signed & Encrypted endpoints
endpoints = selectByMessageSecurityMode(endpoints, MessageSecurityMode.None);
// Choose one endpoint
if (endpoints.length == 0)
throw new Exception("The server does not support insecure connections");
EndpointDescription endpoint = endpoints[0];
//////////////////////////////////////
SessionChannel mySession = myClient.createSessionChannel(endpoint);
(according to the lines of ClientExample1)
I'm new with terracotta. I want to create a clustered server cache but found some difficulties with configuration files.
Here is my tc-config-terracotta.xml file (with which I launch terracotta server)
<?xml version="1.0" encoding="UTF-8"?>
<tc-config xmlns="http://www.terracotta.org/config"
xmlns:ohr="http://www.terracotta.org/config/offheap-resource">
<servers>
<server host="localhost" name="clustered">
<logs>/path/log/terracotta/server-logs</logs>
</server>
</servers>
<plugins>
<config>
<ohr:offheap-resources>
<ohr:resource name="primary-server-resource" unit="MB">128
</ohr:resource>
<ohr:resource name="secondary-server-resource" unit="MB">96
</ohr:resource>
</ohr:offheap-resources>
</config>
</plugins>
</tc-config>
I used the ehcache-clustered-3.3.1-kit to launch the server.
$myPrompt/some/dir/with/ehcache/clustered/server/bin>./start-tc-server.sh -f /path/to/conf/tc-config-terracotta.xml
No problem for the server to start
2017-06-01 11:29:14,052 INFO - New logging session started.
2017-06-01 11:29:14,066 INFO - Terracotta 5.2.2, as of 2017-03-29 at 15:26:20 PDT (Revision 397a456cfe4b8188dfe8b017a5c14346f79c2fcf from UNKNOWN)
2017-06-01 11:29:14,067 INFO - PID is 6114
2017-06-01 11:29:14,697 INFO - Successfully loaded base configuration from file at '/path/to/conf/tc-config-terracotta.xml'.
2017-06-01 11:29:14,757 INFO - Available Max Runtime Memory: 1822MB
2017-06-01 11:29:14,836 INFO - Log file: '/path/log/terracotta/server-logs/terracotta-server.log'.
2017-06-01 11:29:15,112 INFO - Becoming State[ ACTIVE-COORDINATOR ]
2017-06-01 11:29:15,129 INFO - Terracotta Server instance has started up as ACTIVE node on 0:0:0:0:0:0:0:0:9510 successfully, and is now ready for work.
Here is the ehcache-terracotta.xml configuration file
<ehcache:config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:terracotta='http://www.ehcache.org/v3/clustered'
xmlns:ehcache='http://www.ehcache.org/v3'
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.3.xsd
http://www.ehcache.org/v3/clustered http://www.ehcache.org/schema/ehcache-clustered-ext-3.3.xsd">
<ehcache:service>
<terracotta:cluster>
<terracotta:connection url="terracotta://localhost:9510/clustered" />
<terracotta:server-side-config
auto-create="true">
<terracotta:default-resource from="primary-server-resource" />
</terracotta:server-side-config>
</terracotta:cluster>
</ehcache:service>
<ehcache:cache alias="myTest">
<ehcache:key-type>java.lang.String</ehcache:key-type>
<ehcache:value-type>java.lang.String</ehcache:value-type>
<ehcache:resources>
<terracotta:clustered-dedicated unit="MB">10
</terracotta:clustered-dedicated>
</ehcache:resources>
<terracotta:clustered-store consistency="strong" />
</ehcache:cache>
</ehcache:config>
I have a class to test the conf:
import java.net.URL;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.Configuration;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.xml.XmlConfiguration;
public class TestTerracottaCacheManager
{
private static TestTerracottaCacheManager cacheManager = null;
private CacheManager cm;
private Cache<Object, Object> cache;
private static final String DEFAULT_CACHE_NAME = "myTest";
private String cacheName;
public static TestTerracottaCacheManager getInstance()
{
if (cacheManager == null)
{
cacheManager = new TestTerracottaCacheManager();
}
return cacheManager;
}
private TestTerracottaCacheManager()
{
// 1. Create a cache manager
final URL url =
TestTerracottaCacheManager.class.getResource("/ehcache-terracotta.xml");
System.out.println(url);
Configuration xmlConfig = new XmlConfiguration(url);
cm = CacheManagerBuilder.newCacheManager(xmlConfig);
cm.init();
intializeCache();
}
private void intializeCache()
{
// 2. Get a cache called "cache1", declared in ehcache.xml
cache = cm.getCache(cacheName == null ? DEFAULT_CACHE_NAME : cacheName,
Object.class, Object.class);
if (cache == null)
{
throw new NullPointerException();
}
}
public void put(Object key, Object value)
{
cache.put(key, value);
}
public Object get(String key)
{
// 5. Print out the element
Object ele = cache.get(key);
return ele;
}
public boolean isKeyInCache(Object key)
{
return cache.containsKey(key);
}
public void closeCache()
{
// 7. shut down the cache manager
cm.close();
}
public static void main(String[] args)
{
TestTerracottaCacheManager testCache = TestTerracottaCacheManager.getInstance();
testCache.put("titi", "1");
System.out.println(testCache.get("titi"));
testCache.closeCache();
}
public String getCacheName()
{
return cacheName;
}
public void setCacheName(String cacheName)
{
this.cacheName = cacheName;
}
}
I've got an exception. Here it's the stack trace:
14:18:38.978 [main] ERROR org.ehcache.core.EhcacheManager - Initialize failed.
Exception in thread "main" org.ehcache.StateTransitionException: Unable to validate cluster tier manager for id clustered
at org.ehcache.core.StatusTransitioner$Transition.failed(StatusTransitioner.java:235)
at org.ehcache.core.EhcacheManager.init(EhcacheManager.java:587)
at fr.test.cache.TestTerracottaCacheManager.<init>(TestTerracottaCacheManager.java:41)
at fr.test.cache.TestTerracottaCacheManager.getInstance(TestTerracottaCacheManager.java:28)
at fr.test.cache.TestTerracottaCacheManager.main(TestTerracottaCacheManager.java:81)
Caused by: org.ehcache.clustered.client.internal.ClusterTierManagerValidationException: Unable to validate cluster tier manager for id clusteredENS
at org.ehcache.clustered.client.internal.ClusterTierManagerClientEntityFactory.retrieve(ClusterTierManagerClientEntityFactory.java:196)
at org.ehcache.clustered.client.internal.service.DefaultClusteringService.autoCreateEntity(DefaultClusteringService.java:215)
at org.ehcache.clustered.client.internal.service.DefaultClusteringService.start(DefaultClusteringService.java:148)
at org.ehcache.core.internal.service.ServiceLocator.startAllServices(ServiceLocator.java:118)
at org.ehcache.core.EhcacheManager.init(EhcacheManager.java:559)
... 3 more
Caused by: org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException: Default resource not aligned. Client: primary-server-resource Server: null
at org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException.withClientStackTrace(InvalidServerSideConfigurationException.java:43)
at org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException.withClientStackTrace(InvalidServerSideConfigurationException.java:22)
at org.ehcache.clustered.common.internal.messages.ResponseCodec.decode(ResponseCodec.java:197)
at org.ehcache.clustered.common.internal.messages.EhcacheCodec.decodeResponse(EhcacheCodec.java:110)
at org.ehcache.clustered.common.internal.messages.EhcacheCodec.decodeResponse(EhcacheCodec.java:37)
at com.tc.object.EntityClientEndpointImpl$InvocationBuilderImpl$1.getWithTimeout(EntityClientEndpointImpl.java:193)
at com.tc.object.EntityClientEndpointImpl$InvocationBuilderImpl$1.getWithTimeout(EntityClientEndpointImpl.java:175)
at org.ehcache.clustered.client.internal.SimpleClusterTierManagerClientEntity.waitFor(SimpleClusterTierManagerClientEntity.java:184)
at org.ehcache.clustered.client.internal.SimpleClusterTierManagerClientEntity.invokeInternal(SimpleClusterTierManagerClientEntity.java:148)
at org.ehcache.clustered.client.internal.SimpleClusterTierManagerClientEntity.validate(SimpleClusterTierManagerClientEntity.java:120)
at org.ehcache.clustered.client.internal.ClusterTierManagerClientEntityFactory.retrieve(ClusterTierManagerClientEntityFactory.java:190)
... 7 more
Caused by: org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException: Default resource not aligned. Client: primary-server-resource Server: null
at org.ehcache.clustered.server.EhcacheStateServiceImpl.checkConfigurationCompatibility(EhcacheStateServiceImpl.java:207)
at org.ehcache.clustered.server.EhcacheStateServiceImpl.validate(EhcacheStateServiceImpl.java:194)
at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.validate(ClusterTierManagerActiveEntity.java:253)
at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.invokeLifeCycleOperation(ClusterTierManagerActiveEntity.java:203)
at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.invoke(ClusterTierManagerActiveEntity.java:147)
at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.invoke(ClusterTierManagerActiveEntity.java:57)
at com.tc.objectserver.entity.ManagedEntityImpl.performAction(ManagedEntityImpl.java:741)
at com.tc.objectserver.entity.ManagedEntityImpl.invoke(ManagedEntityImpl.java:488)
at com.tc.objectserver.entity.ManagedEntityImpl.lambda$processInvokeRequest$2(ManagedEntityImpl.java:319)
at com.tc.objectserver.entity.ManagedEntityImpl$SchedulingRunnable.run(ManagedEntityImpl.java:1048)
at com.tc.objectserver.entity.RequestProcessor$EntityRequest.invoke(RequestProcessor.java:170)
at com.tc.objectserver.entity.RequestProcessor$EntityRequest.run(RequestProcessor.java:161)
at com.tc.objectserver.entity.RequestProcessorHandler.handleEvent(RequestProcessorHandler.java:27)
at com.tc.objectserver.entity.RequestProcessorHandler.handleEvent(RequestProcessorHandler.java:23)
at com.tc.async.impl.StageQueueImpl$HandledContext.runWithHandler(StageQueueImpl.java:502)
at com.tc.async.impl.StageImpl$WorkerThread.run(StageImpl.java:192)
I think it's a problem in the XML files, but I'm not sure. Someone can help please?
Thanks
What the exception tells you is that the configuration of the clustered bits of your cache manager and cache differ between what the cluster knows and what the client ask.
The most likely explanation is that you ran your client code once with a different config, realised there was an issue or just wanted to change something. And then tried to run the client without destroying the cahche manager on the cluster or restarting the server.
You simply need to restart your server, to lose all clustered state since you want a different setup.
I've tried to reproduce your issue in my IDE, copying / pasting your 3 files.
I found an error in intializeCache():
cache = cm.getCache(cacheName == null ? DEFAULT_CACHE_NAME : cacheName,
Object.class, Object.class);
triggered a :
Exception in thread "main" java.lang.IllegalArgumentException: Cache 'myTest' type is <java.lang.String, java.lang.String>, but you retrieved it with <java.lang.Object, java.lang.Object>
at org.ehcache.core.EhcacheManager.getCache(EhcacheManager.java:162)
at MyXmlClient.intializeCache(MyXmlClient.java:48)
So please make sure that your xml configuration matches your Java code : you used <String, String> in XML, use <String, String> in your java code :
cache = cm.getCache(cacheName == null ? DEFAULT_CACHE_NAME : cacheName,
String.class, String.class);
Everything else worked fine !
INFO --- [8148202b7ba8914] customer.logger.tsa : Connection successfully established to server at 127.0.0.1:9510
INFO --- [ main] org.ehcache.core.EhcacheManager : Cache 'myTest' created in EhcacheManager.
1
INFO --- [ main] org.ehcache.core.EhcacheManager : Cache 'myTest' removed from EhcacheManager.
INFO --- [ main] o.e.c.c.i.s.DefaultClusteringService : Closing connection to cluster terracotta://localhost:9510
The error you gave is coming form a mismatch between the terracotta server offheap resource use in your client and the terracotta server offheap configuration ; make sure they match ! (copying / pasting your example they did !)
#AnthonyDahanne I am using ehcache-clustered-3.8.1-kit to launch the server. I have ehcache.xml my spring boot application is automatically picking my ehache.xml so I am not explicitly writing cacheManager.
<ehcache:config
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:terracotta='http://www.ehcache.org/v3/clustered'
xmlns:ehcache='http://www.ehcache.org/v3'
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.8.xsd
http://www.ehcache.org/v3/clustered http://www.ehcache.org/schema/ehcache-clustered-ext-3.8.xsd">
<ehcache:service>
<terracotta:cluster>
<terracotta:connection url="terracotta://localhost:9410/clustered"/>
<terracotta:server-side-config auto-create="true">
<!--<terracotta:default-resource from="default-resource"/>-->
<terracotta:shared-pool name="shared-pool-expense" unit="MB">100</terracotta:shared-pool>
</terracotta:server-side-config>
</terracotta:cluster>
</ehcache:service>
<ehcache:cache alias="areaOfCircleCache">
<ehcache:key-type>java.lang.String</ehcache:key-type>
<ehcache:value-type>com.db.entity.LogMessage</ehcache:value-type>
<ehcache:resources>
<!-- <ehcache:heap unit="entries">100</ehcache:heap>
<ehcache:offheap unit="MB">10</ehcache:offheap>-->
<terracotta:clustered-dedicated unit="MB">10</terracotta:clustered-dedicated>
</ehcache:resources>
</ehcache:cache>
</ehcache:config>
I have a java app that runs jetty:
public class ServerRunner {
private final static org.apache.log4j.Logger logger = LoggingUtils.getLogger();
public static void main(String[] args) throws Exception {
PromptoConfig.s.initLog();
final int port = 8082;
final Server jettyServer = new Server(port);
final HandlerCollection handlers = new HandlerCollection();
// Creating the first web application context
final WebAppContext webappContext = new WebAppContext();
System.out.println("===== PromptoConfig.s.RESOURCES_BASE " + PromptoConfig.s.RESOURCES_BASE);
webappContext.setResourceBase(PromptoConfig.s.RESOURCES_BASE);
webappContext.setContextPath("/");
System.out.println("===== PromptoConfig.s.WEB_XML_PATH " + PromptoConfig.s.WEB_XML_PATH);
webappContext.setDefaultsDescriptor(PromptoConfig.s.WEB_XML_PATH);
// webappContext.setTempDirectory(new File(temp));
DBSQLConfig.s().DB = com.waze.prompto.config.DBSQLConfig.s.DB;
webappContext.setExtractWAR(false);
handlers.addHandler(webappContext);
// Adding the handlers to the server.
jettyServer.setHandler(handlers);
try {
jettyServer.start();
jettyServer.join();
} catch (Exception ex) {
logger.error("failed to init jetty server", ex);
} finally {
jettyServer.destroy();
}
}
}
i see in the logs debug info in intellij console:
633016 [org.eclipse.jetty.server.session.HashSessionManager#22fcf7abTimer] DEBUG org.eclipse.jetty.server.session - Scavenging sessions at 1496325042425
How can i turn this debug logs off?
You appear to have configured log4j on your environment.
private final static org.apache.log4j.Logger logger = LoggingUtils.getLogger();
The output format is also not the default format from Jetty's internal StdErrLog
Yours
633016 [org.eclipse.jetty.server.session.HashSessionManager#22fcf7abTimer] DEBUG org.eclipse.jetty.server.session - Scavenging sessions at 1496325042425
Jetty's StdErrLog
2017-06-01 14:30:17.978:DBUG:oejs.session:main: SessionManager default maxInactiveInterval=1800
At this point, this is no longer a jetty logging configuration, but a log4j configuration.
Just set the org.eclipse.jetty logger level to INFO or WARN in your log4j.properties or log4j.xml
If you use jetty-server from eclipse
Add configuration
log4j.category.org.eclipse.jetty=error
in the file src/main/resources/log4j.properties
I am trying to build an app as a learning experience. I am getting a null pointer exception, but it is happening the second time the code is being called.
So my code calls this as part of it's startup.
// Sanity checks
sanity = new SanityChecks();
logger.info("Checking sanity...");
try {
sanity.doBasicChecks();
logger.info("It all looks sane.");
}
catch( final Exception ex){
logger.error("Something is wrong, we are not sane. Aborting...", ex);
stop();
}
Other classes are:
package nz.co.great_ape.tempusFugit;
import com.almworks.sqlite4java.SQLite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Checks to see if all is ok for standard usage of tempusFugit.
*
* Checks for valid paths, existing database etc, if not assumes that
* this is the first time tempusFugit has been run for this user and
* tries to set up the basic files and data.
*
* #author Rob Brown-Bayliss
* Created on 2/11/14
*/
public class SanityChecks {
public static final Logger logger = LoggerFactory.getLogger(AppConsts.LOGGER_NAME);
public SanityChecks() {
// todo
// todo
SQLite.setLibraryPath(AppConsts.HOME_DIR); // TODO: Why is this required? can we not place the native libs somewhere else or in the jar?
// todo
// todo
}
/**
* Performs basic checks to see if it is ok to run the app. If not it will attempt to
* set up for first time use.
*
* #return true if all is ok
*/
public boolean doBasicChecks() {
logger.info("Starting basic checks...");
if (!HomeDirExists()) {
return false;
}
if (!DatabaseExists()) {
logger.info("Trying to create a new database.");
DatabaseUpgrade dug = new DatabaseUpgrade();
if (!dug.upGrade()) {
return false;
}
logger.info("Created a new database.");
// At this point a usable database should exist and it should be current
}
if (!DatabaseVersionCorrect()) {
// // If the database is old we will upgrade it to the current version.
// DatabaseUpgrade dug = new DatabaseUpgrade();
// if (!dug.upGrade()) {
// return false;
// }
logger.info("is this it?.");
}
// At this point all basic checks have passed and we are good to go...
logger.info("Basic checks are complete. All is good in the universe...");
return true;
}
/**
* Checks if the app home directory exists, if not it tries to create it.
*
* #return true if exists or was able to create the directory
*/
private boolean HomeDirExists() {
if (!Files.isDirectory(Paths.get(AppConsts.HOME_DIR))) {
try {
Files.createDirectory(Paths.get(AppConsts.HOME_DIR));
}
catch (IOException io) {
logger.error("The directory " + AppConsts.HOME_DIR + " does not exist and could not be created. This is not the best but we can survive.", io);
return false;
}
}
logger.info("The directory " + AppConsts.HOME_DIR + " exists. This is good.");
return true;
}
/**
* Checks if the SQLite database exists, if not it tries to create it.
* or was able to create the database
*
* #return true if the database exists
*/
private boolean DatabaseExists() {
if (Files.notExists(Paths.get(AppConsts.TF_DATABASE))) {
logger.error("The database " + AppConsts.TF_DATABASE + " does not exist. This is bad.");
return false;
}
logger.info("The database " + AppConsts.TF_DATABASE + " exists. This is good.");
return true;
}
/**
* Checks if the SQLite database is correct for this version.
*
* #return true if correct version
*/
private boolean DatabaseVersionCorrect() {
Integer expectedVersion = AppConsts.TF_DATABASE_VERSION;
logger.info("Checking the database version is correct. Looking for version "+ expectedVersion + "." );
DatabaseUpgrade dug = new DatabaseUpgrade();
logger.info("Checking the database version is correct. Looking for version "+ expectedVersion + "." );
Integer currentVersion = dug.getVersion();
if (currentVersion < expectedVersion) {
logger.info("Expected version " + expectedVersion + ", but database is version " + currentVersion + ". This is bad.");
return false;
}
logger.info("The database version is correct. This is good.");
return true;
}
}
And:
package nz.co.great_ape.tempusFugit;
import com.almworks.sqlite4java.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Setup the database for current version tempusFugit. This will upgrade an
* existing database or create a new empty database if required.
*
* #author Rob Brown-Bayliss
* Created on 4/11/14
*/
public class
DatabaseUpgrade {
public static final Logger logger = LoggerFactory.getLogger(AppConsts.LOGGER_NAME);
private SQLiteConnection dbConn = null;
private SQLiteQueue sQueue = null;
private int currentVersion;
public DatabaseUpgrade() {
}
/**
* Attempts to upgrade the existing database to the current version, or if
* there is no existing database then create one suitable for the current app version.
*
* #return true if there is a current and usable database
*/
public boolean upGrade() {
logger.info(" Started an upgrade on the database, if the database does not exist it will be created at the current version, ");
logger.info(" if it exists but is an older version it will be upgraded to the current version.");
if (openDatabase()) {
currentVersion = getVersion();
if (currentVersion == AppConsts.FAIL) {
logger.info("Database version is unknown. The file will be deleted and a new database created. We can survive this.");
// TODO: Ask user if we should delete the old one or make a backup?
closeDatabase();
deleteDatabase();
openDatabase();
}
if (currentVersion != AppConsts.TF_DATABASE_VERSION) {
logger.info("Current Database version is " + currentVersion);
// TODO: Backup current database.
if (currentVersion < 1) {
if (!makeVersionOne()) {
logger.error("Unable to upgrade the database. This is VERY bad.");
return false;
}
}
currentVersion = 1;
}
closeDatabase(); // good practice
}
logger.info("The database is the current version. This is good.");
return true;
}
/**
* Turns a blank SQLite database into a tempusFugit version 1 database by
* adding the required tables and data.
*/
private boolean makeVersionOne() {
logger.info("Attempting to upgrade to version 1.");
String CT_SQL = "CREATE TABLE IF NOT EXISTS dbVersion (id INTEGER PRIMARY KEY AUTOINCREMENT, version INTEGER NOT NULL UNIQUE, ";
CT_SQL = CT_SQL + "upgraded INTEGER(4) NOT NULL DEFAULT (strftime('%s','now'))); ";
String IN_SQL = "INSERT INTO dbVersion(version) values (1); ";
try {
execSQL("BEGIN TRANSACTION; ");
execSQL(CT_SQL); // create the table
execSQL(IN_SQL); // insert the record
execSQL("COMMIT; ");
}
catch (Exception ex) {
logger.error("Attempted upgrade of " + AppConsts.TF_DATABASE + " to version 1 has failed. This is VERY bad.", ex);
return false;
}
logger.info("The database has been upgraded to version 1. This is good.");
return true;
}
private Integer execSQL(String SQL) {
return sQueue.execute(new SQLiteJob<Integer>() {
protected Integer job(SQLiteConnection con) throws SQLiteException {
SQLiteStatement st = null;
try {
st = con.prepare(SQL);
st.step();
return AppConsts.SUCCESS;
}
catch (Exception ex) {
logger.error("Tried to execute SQL: " + SQL, ex);
return AppConsts.FAIL;
}
finally {
if (st != null) {
st.dispose();
}
}
}
}).complete();
}
/**
* Gets the current database version
*
* #return version as an int
*/
public int getVersion() {
return sQueue.execute(new SQLiteJob<Integer>() {
protected Integer job(SQLiteConnection con) throws SQLiteException {
SQLiteStatement st = null;
try {
st = con.prepare("SELECT version, upgraded FROM dbVersion ORDER BY upgraded DESC LIMIT 1;");
st.step();
return st.columnInt(0);
}
catch (Exception ex) {
logger.error("The database version of " + AppConsts.TF_DATABASE + " is unknown. This is bad.", ex);
return AppConsts.FAIL;
}
finally {
if (st != null) {
st.dispose();
}
}
}
}).complete();
}
/**
* Opens an existing SQLite database or creates a new blank database
* if none exists.
*
* #return false if there is a problem. // TODO: Is it possible to have a problem?
*/
private boolean openDatabase() {
try {
dbConn = new SQLiteConnection(new File(AppConsts.TF_DATABASE));
dbConn.open(true);
sQueue = new SQLiteQueue(new File(AppConsts.TF_DATABASE));
sQueue.start();
return true;
}
catch (Exception ex) {
logger.error("The database " + AppConsts.TF_DATABASE + " could not be opened or created. This is VERY bad.", ex);
return false;
}
}
/**
* Closes an open database.
*
* #return false if there is a problem. // TODO: Is it possible to have a problem?
*/
private boolean closeDatabase() {
try {
if (dbConn != null) {
dbConn.dispose();
}
return true;
}
catch (Exception ex) {
logger.error("The database " + AppConsts.TF_DATABASE + " could not be closed.", ex);
return false;
}
}
/**
* Deletes an existing database.
*
* #return false if there is a problem. // TODO: Is it possible to have a problem?
*/
private boolean deleteDatabase() {
try {
Files.delete(Paths.get(AppConsts.TF_DATABASE));
logger.info("The database " + AppConsts.TF_DATABASE + " has been deleted.");
return true;
}
catch (Exception ex) {
logger.error("The database " + AppConsts.TF_DATABASE + " could not be deleted.", ex);
return false;
}
}
}
Plus the constants:
package nz.co.great_ape.tempusFugit;
/**
* Constants used by tempusFugit
*
* #author Rob Brown-Bayliss
* Created on 31/10/14
*/
public class AppConsts {
// Application
public static final String APP_NAME = "Tempus Fugit";
public static final String VERSION_NUMBER = "0.0.1";
// Debug Mode On-Off
public static final boolean DEBUG_MODE = true;
// Data files and paths
public static final String FS = System.getProperty("file.separator");
public static final String HOME_DIR = System.getProperty("user.home") + FS + ".tempusFugit"; // This is the tempusFugit home, not the users home.
public static final String USER_NAME = System.getProperty("user.name");
public static final String LOGGER_NAME = "nz.co.great_ape.tempusFugit";
public static final String LOG_FILE = HOME_DIR + FS + "tempusFugit.log";
// Database
public static final String TF_DATABASE = HOME_DIR + FS + "tfData.sql";
public static final int TF_DATABASE_VERSION = 1; // This is the current version of the database
// Error codes
public static final int UNKNOWN = -1;
public static final int FAIL = 0;
public static final int SUCCESS = 1;
}
What I don't know is why the call if (!DatabaseVersionCorrect()) crashes with a null pointer.
Can anyone help here?
This is the stack trace
/usr/lib/jvm/java-8-oracle/bin/java -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:49764,suspend=y,server=n -javaagent:/home/rob/Projects/IntelliJ/plugins/Groovy/lib/agent/gragent.jar -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/java-8-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-8-oracle/jre/lib/management-agent.jar:/usr/lib/jvm/java-8-oracle/jre/lib/deploy.jar:/usr/lib/jvm/java-8-oracle/jre/lib/javaws.jar:/usr/lib/jvm/java-8-oracle/jre/lib/plugin.jar:/usr/lib/jvm/java-8-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfxswt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/rt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-8-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/dnsns.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunec.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/localedata.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/zipfs.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jfxrt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/nashorn.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/cldrdata.jar:/home/rob/Projects/tempusFugit/build/classes/main:/home/rob/Projects/tempusFugit/build/resources/main:/home/rob/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-api/1.7.7/2b8019b6249bb05d81d3a3094e468753e2b21311/slf4j-api-1.7.7.jar:/home/rob/.gradle/caches/modules-2/files-2.1/com.almworks.sqlite4java/sqlite4java/1.0.392/d6234e08ff4e1607ff5321da2579571f05ff778d/sqlite4java-1.0.392.jar:/home/rob/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-classic/1.1.2/b316e9737eea25e9ddd6d88eaeee76878045c6b2/logback-classic-1.1.2.jar:/home/rob/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-core/1.1.2/2d23694879c2c12f125dac5076bdfd5d771cc4cb/logback-core-1.1.2.jar:/home/rob/Projects/IntelliJ/lib/idea_rt.jar nz.co.great_ape.tempusFugit.MainApp
Connected to the target VM, address: '127.0.0.1:49764', transport: 'socket'
10:43:43.371 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Time flies...
10:43:43.379 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - https://www.youtube.com/watch?v=ESto79osxOY
10:43:43.379 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Tempus Fugit Version: 0.0.1
10:43:43.379 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - javafx.runtime.version: 8.0.25-b17
10:43:43.380 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - logged on as: rob
10:43:43.383 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Checking sanity...
10:43:43.383 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Starting basic checks...
10:43:43.393 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - The directory /home/rob/.tempusFugit exists. This is good.
10:43:43.394 [JavaFX Application Thread] ERROR nz.co.great_ape.tempusFugit - The database /home/rob/.tempusFugit/tfData.sql does not exist. This is bad.
10:43:43.394 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Trying to create a new database.
10:43:43.397 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Started an upgrade on the database, if the database does not exist it will be created at the current version,
10:43:43.397 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - if it exists but is an older version it will be upgraded to the current version.
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] DB[1]: instantiated [/home/rob/.tempusFugit/tfData.sql]
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] Internal: loaded sqlite4java-linux-amd64-1.0.392 from /home/rob/.tempusFugit/libsqlite4java-linux-amd64-1.0.392.so
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] Internal: loaded sqlite 3.8.7, wrapper 1.3
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] DB[1]: opened
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] DB[2]: instantiated [/home/rob/.tempusFugit/tfData.sql]
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] DB[2]: opened
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] DB[1]: connection closed
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] DB[3]: instantiated [/home/rob/.tempusFugit/tfData.sql]
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] DB[3]: opened
10:43:43.507 [SQLiteQueue[tfData.sql]] ERROR nz.co.great_ape.tempusFugit - The database version of /home/rob/.tempusFugit/tfData.sql is unknown. This is bad.
com.almworks.sqlite4java.SQLiteException: [1] DB[2] prepare() SELECT version, upgraded FROM dbVersion ORDER BY upgraded DESC LIMIT 1; [no such table: dbVersion]
at com.almworks.sqlite4java.SQLiteConnection.throwResult(SQLiteConnection.java:1436) ~[sqlite4java-1.0.392.jar:392]
at com.almworks.sqlite4java.SQLiteConnection.prepare(SQLiteConnection.java:580) ~[sqlite4java-1.0.392.jar:392]
at com.almworks.sqlite4java.SQLiteConnection.prepare(SQLiteConnection.java:635) ~[sqlite4java-1.0.392.jar:392]
at com.almworks.sqlite4java.SQLiteConnection.prepare(SQLiteConnection.java:622) ~[sqlite4java-1.0.392.jar:392]
at nz.co.great_ape.tempusFugit.DatabaseUpgrade$2.job(DatabaseUpgrade.java:121) [main/:na]
at nz.co.great_ape.tempusFugit.DatabaseUpgrade$2.job(DatabaseUpgrade.java:117) [main/:na]
at com.almworks.sqlite4java.SQLiteJob.execute(SQLiteJob.java:372) [sqlite4java-1.0.392.jar:392]
at com.almworks.sqlite4java.SQLiteQueue.executeJob(SQLiteQueue.java:534) [sqlite4java-1.0.392.jar:392]
at com.almworks.sqlite4java.SQLiteQueue.queueFunction(SQLiteQueue.java:667) [sqlite4java-1.0.392.jar:392]
at com.almworks.sqlite4java.SQLiteQueue.runQueue(SQLiteQueue.java:623) [sqlite4java-1.0.392.jar:392]
at com.almworks.sqlite4java.SQLiteQueue.access$000(SQLiteQueue.java:77) [sqlite4java-1.0.392.jar:392]
at com.almworks.sqlite4java.SQLiteQueue$1.run(SQLiteQueue.java:205) [sqlite4java-1.0.392.jar:392]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25]
10:43:43.508 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Database version is unknown. The file will be deleted and a new database created. We can survive this.
10:43:43.509 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - The database /home/rob/.tempusFugit/tfData.sql has been deleted.
10:43:43.510 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Current Database version is 0
10:43:43.510 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Attempting to upgrade to version 1.
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] DB[4]: instantiated [/home/rob/.tempusFugit/tfData.sql]
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] DB[4]: opened
Nov 30, 2014 10:43:43 AM com.almworks.sqlite4java.Internal log
INFO: [sqlite] DB[3]: connection closed
10:43:43.640 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - The database has been upgraded to version 1. This is good.
10:43:43.640 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - The database is the current version. This is good.
10:43:43.640 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Created a new database.
10:43:43.640 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Checking the database version is correct. Looking for version 1.
10:43:43.640 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Checking the database version is correct. Looking for version 1.
10:43:43.641 [JavaFX Application Thread] ERROR nz.co.great_ape.tempusFugit - Something is wrong, we are not sane. Aborting...
java.lang.NullPointerException: null
at nz.co.great_ape.tempusFugit.DatabaseUpgrade.getVersion(DatabaseUpgrade.java:117) ~[main/:na]
at nz.co.great_ape.tempusFugit.SanityChecks.DatabaseVersionCorrect(SanityChecks.java:111) ~[main/:na]
at nz.co.great_ape.tempusFugit.SanityChecks.doBasicChecks(SanityChecks.java:54) ~[main/:na]
at nz.co.great_ape.tempusFugit.MainApp.start(MainApp.java:78) ~[main/:na]
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(LauncherImpl.java:821) [jfxrt.jar:na]
at com.sun.javafx.application.LauncherImpl$$Lambda$56/1015064561.run(Unknown Source) [jfxrt.jar:na]
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(PlatformImpl.java:323) [jfxrt.jar:na]
at com.sun.javafx.application.PlatformImpl$$Lambda$50/591723622.run(Unknown Source) [jfxrt.jar:na]
at com.sun.javafx.application.PlatformImpl.lambda$null$164(PlatformImpl.java:292) [jfxrt.jar:na]
at com.sun.javafx.application.PlatformImpl$$Lambda$52/1657335803.run(Unknown Source) [jfxrt.jar:na]
at java.security.AccessController.doPrivileged(Native Method) [na:1.8.0_25]
at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(PlatformImpl.java:291) [jfxrt.jar:na]
at com.sun.javafx.application.PlatformImpl$$Lambda$51/1166726978.run(Unknown Source) [jfxrt.jar:na]
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) [jfxrt.jar:na]
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method) [jfxrt.jar:na]
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$45(GtkApplication.java:126) [jfxrt.jar:na]
at com.sun.glass.ui.gtk.GtkApplication$$Lambda$42/1167116739.run(Unknown Source) [jfxrt.jar:na]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25]
10:43:43.641 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Game Over...
10:43:44.563 [JavaFX Application Thread] INFO nz.co.great_ape.tempusFugit - Game Over...
The problem is te fact that you call
DatabaseUpgrade dug = new DatabaseUpgrade();
logger.info(...);
Integer currentVersion = dug.getVersion();
But your dbConn and sQueue in DatabaseUpgrade are still null. Since you didn't called the private openDatabase() method which initializes your varaibles. So When you call getVersion() your sQueue.execute(...) blowups because you cannot call a method on a null object.
What is the problem when I execute the maven command in the loop ? The goal is to update the version of pom.xml of the list of bundles. The first iteration, maven execute correctly (update pom.xml), but it makes error for all item after.
for (String bundlePath: bundlesToUpdate)
{
MavenCli cli = new MavenCli();
String[] arguments = {
"-Dtycho.mode=maven",
"org.eclipse.tycho:tycho-versions-plugin:set-version",
"-DgenerateBackupPoms=false",
"-DnewVersion=" + version};
int result = cli.doMain(arguments, bundlePath, System.out, System.err);
}
Same error with the code:
`MavenCli cli = new MavenCli();
for (String bundlePath: bundlesToUpdate)
{
String[] arguments = {
"-Dtycho.mode=maven",
"org.eclipse.tycho:tycho-versions-plugin:set-version",
"-DgenerateBackupPoms=false",
"-DnewVersion=" + version};
int result = cli.doMain(arguments, bundlePath, System.out, System.err);
}`
First time, it's ok:
[main] INFO org.eclipse.tycho.versions.manipulation.PomManipulator - pom.xml//project/version: 2.2.6-SNAPSHOT => 2.2.7-SNAPSHOT
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - ------------------------------------------------------------------------
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - Reactor Summary:
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger -
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - XXXX project ....................... SUCCESS [ 0.216 s]
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - com.sungard.valdi.bus.fixbroker.client.bnp ........ SKIPPED
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - XXX project Feature ...................... SKIPPED
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - ------------------------------------------------------------------------
[main] INFO org.apache.maven.cli.event.ExecutionEventLogger - BUILD SUCCESS
After the errors are:
[main] ERROR org.apache.maven.cli.MavenCli - Error executing Maven.
[main] ERROR org.apache.maven.cli.MavenCli - java.util.NoSuchElementException
role: org.apache.maven.eventspy.internal.EventSpyDispatcher
roleHint:
[main] ERROR org.apache.maven.cli.MavenCli - Caused by: null
[main] ERROR org.apache.maven.cli.MavenCli - Error executing Maven.
[main] ERROR org.apache.maven.cli.MavenCli - java.util.NoSuchElementException
role: org.apache.maven.eventspy.internal.EventSpyDispatcher
roleHint:
The solution I found is to use Maven Invoker and it works fine for the same functionality:
public class MavenInvoker {
public static void main(String[] args) throws IOException, NoHeadException, GitAPIException
{
MavenInvoker toto = new MavenInvoker();
toto.updateVersionMavenInvoker("2.2.8-SNAPSHOT", "TECHNICAL\\WEB" );
}
private InvocationRequest request = new DefaultInvocationRequest();
private DefaultInvoker invoker = new DefaultInvoker();
public InvocationResult updateVersionMavenInvoker(String newVersion, String folderPath)
{
InvocationResult result = null;
request.setPomFile( new File(folderPath+"\\pom.xml" ) );
String version = "-DnewVersion="+newVersion;
request.setGoals( Arrays.asList("-Dtycho.mode=maven",
"org.eclipse.tycho:tycho-versions-plugin:set-version",
"-DgenerateBackupPoms=false",
version) );
try {
result = invoker.execute( request );
} catch (MavenInvocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
This works for me inside a custom maven plugin (using Maven 3.5.0):
ClassRealm classRealm = (ClassRealm) Thread.currentThread().getContextClassLoader();
MavenCli cli = new MavenCli(classRealm.getWorld());
cli.doMain( ... );
The plexus Launcher sets the context class loader to its ClassRealm, which has access to the "global" ClassWorld.
Not sure how stable that solution is, but so far looking good.
Used imports:
import org.codehaus.plexus.classworlds.ClassWorld;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.apache.maven.cli.MavenCli;
See the email thread for a more detail explanation: https://dev.eclipse.org/mhonarc/lists/sisu-users/msg00063.html
It seems the correct way is to give MainCli a ClassWorld instance on construction so it can maintain a proper state through multiple calls.
Example:
final ClassWorld classWorld = new ClassWorld("plexus.core", getClass().getClassLoader());
MavenCli cli = new MavenCli(classWorld);
String[] arguments = {
"-Dtycho.mode=maven",
"org.eclipse.tycho:tycho-versions-plugin:set-version",
"-DgenerateBackupPoms=false",
"-DnewVersion=" + version};
int result = cli.doMain(arguments, bundlePath, System.out, System.err);