Read operation right after Elasticsearch index creation causes exception - java

I try to perform a read opertion on Elasticsearch index right after it was created. Here is simple code to reproduce this situation:
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import static java.net.InetAddress.getLoopbackAddress;
public class ElasticIssue {
static String index = "my_index";
public static void main(String[] args) {
final Client c = getClient();
deleteIndexIfExists(c);
createIndex(c);
//refresh(c);
//flush(c);
//delay();
//indexDoc(c);
getDoc(c);
}
static void getDoc(Client client) {
client.prepareGet(index, "some-type", "1").get();
}
static void indexDoc(Client client) {
client.prepareIndex(index, "another-type", "25").setSource("{}").get();
}
static void createIndex(Client client) {
client.admin().indices().prepareCreate(index).get();
}
static void delay() {
try {Thread.sleep(3000);} catch (InterruptedException e) {}
}
static void flush(Client client) {
client.admin().indices().prepareFlush(index).get();
}
private static void refresh(Client client) {
client.admin().indices().prepareRefresh(index).get();
}
static void deleteIndexIfExists(Client client) {
final IndicesExistsResponse response = client.admin().indices().prepareExists(index).get();
if (response.isExists()) {
deleteIndex(client);
}
}
static void deleteIndex(Client client) {
client.admin().indices().prepareDelete(index).get();
}
static Client getClient() {
final Settings settings = Settings.builder()
.put("cluster.name", "elasticsearch") //default name
.put("node.name", "my-node")
.build();
return TransportClient.builder()
.settings(settings)
.build()
.addTransportAddress(new InetSocketTransportAddress(getLoopbackAddress(), 9300));
}
}
And then I get the following error:
Exception in thread "main" NoShardAvailableActionException[No shard available for [get [my_index][some-type][1]: routing [null]]]; nested: RemoteTransportException[[my-node][172.17.0.2:9300][indices:data/read/get[s]]]; nested: IllegalIndexShardStateException[CurrentState[RECOVERING] operations only allowed when shard state is one of [POST_RECOVERY, STARTED, RELOCATED]];
at org.elasticsearch.action.support.single.shard.TransportSingleShardAction$AsyncSingleAction.perform(TransportSingleShardAction.java:199)
at org.elasticsearch.action.support.single.shard.TransportSingleShardAction$AsyncSingleAction.onFailure(TransportSingleShardAction.java:186)
at org.elasticsearch.action.support.single.shard.TransportSingleShardAction$AsyncSingleAction.access$1300(TransportSingleShardAction.java:115)
at org.elasticsearch.action.support.single.shard.TransportSingleShardAction$AsyncSingleAction$2.handleException(TransportSingleShardAction.java:240)
at org.elasticsearch.transport.TransportService$DirectResponseChannel.processException(TransportService.java:855)
at org.elasticsearch.transport.TransportService$DirectResponseChannel.sendResponse(TransportService.java:833)
at org.elasticsearch.transport.TransportService$4.onFailure(TransportService.java:387)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:39)
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)
Caused by: RemoteTransportException[[my-node][172.17.0.2:9300][indices:data/read/get[s]]]; nested: IllegalIndexShardStateException[CurrentState[RECOVERING] operations only allowed when shard state is one of [POST_RECOVERY, STARTED, RELOCATED]];
Caused by: [my_index][[my_index][3]] IllegalIndexShardStateException[CurrentState[RECOVERING] operations only allowed when shard state is one of [POST_RECOVERY, STARTED, RELOCATED]]
at org.elasticsearch.index.shard.IndexShard.readAllowed(IndexShard.java:1035)
at org.elasticsearch.index.shard.IndexShard.get(IndexShard.java:651)
at org.elasticsearch.index.get.ShardGetService.innerGet(ShardGetService.java:173)
at org.elasticsearch.index.get.ShardGetService.get(ShardGetService.java:86)
at org.elasticsearch.action.get.TransportGetAction.shardOperation(TransportGetAction.java:101)
at org.elasticsearch.action.get.TransportGetAction.shardOperation(TransportGetAction.java:44)
at org.elasticsearch.action.support.single.shard.TransportSingleShardAction$ShardTransportHandler.messageReceived(TransportSingleShardAction.java:282)
at org.elasticsearch.action.support.single.shard.TransportSingleShardAction$ShardTransportHandler.messageReceived(TransportSingleShardAction.java:275)
at org.elasticsearch.transport.TransportRequestHandler.messageReceived(TransportRequestHandler.java:33)
at org.elasticsearch.transport.RequestHandlerRegistry.processMessageReceived(RequestHandlerRegistry.java:75)
at org.elasticsearch.transport.TransportService$4.doRun(TransportService.java:376)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
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)
It seems like Elasticsearch index creation was not complete despite response was already returned. That is a bit frustrating. And if I do any of: delay, index any doc, refresh index, flush index (uncomment any line for this); then read operation performs successfully.
What is the explanation of this behavior? What is a recommended way to make sure that index is ready to work? Listed solutions are found by experiment.
I'am using Elasticsearch 2.3.3 and Java 8. All communication with Elasticsearch is done using Transport protocol (with Java api).
For easier setup here is docker command to get container with all necessary settings:
docker run -p 9200:9200 -p 9300:9300 elasticsearch:2.3.3 -Des.node.name="my-node"
Here is Maven dependency for Elasticsearch Java API:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
</dependency>

You need to wait till the index is created. This is what you can do to wait till the health of index is in yellow status.
After index creation function call the below function :
static void indexStatusCheck(Client client) {
ClusterHealthResponse response = client.admin().cluster().prepareHealth().setIndices(index).setWaitForYellowStatus().get();
if (response.getStatus() == ClusterHealthStatus.RED) {
throw Exception("Index not ready");
}
}
Then you can proceed with the getDoc() call.

Related

Java gRPC Server Not Starting

I am trying to implement gRPC service in my code with condition to use one instance of the server class the code building successfully but i got a runtime error.
How can I fix this error?
Exception in thread "main" java.lang.NullPointerException: bindableService
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:897)
at io.grpc.internal.AbstractServerImplBuilder.addService(AbstractServerImplBuilder.java:120)
at io.grpc.internal.AbstractServerImplBuilder.addService(AbstractServerImplBuilder.java:56)
at com.mypackage.cu.comms.CURequestHandlerService.<init>(Unknown Source)
at com.mypackage.cu.comms.CURequestHandlerService.start(Unknown Source)
at com.mypackage.cu.entities.ControlUnit.initSystem(Unknown Source)
at com.mypackage.cu.entities.ControlUnit.run(Unknown Source)
at com.mypackage.cu.entities.ControlUnit.main(Unknown Source)
the genrated grpc java class is CURequestHandlerGrpc.
the server class CURequestHandlerService:
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
\\ ..
public class CURequestHandlerService extends CURequestHandlerGrpc.CURequestHandlerImplBase {
private final Server server;
private static CURequestHandlerService INSTANCE = null;
private CURequestHandlerService(int port) {
this.server = ServerBuilder.forPort(port)
.addService(INSTANCE)
.build();
}
public static void start(int port) {
if (INSTANCE == null)
INSTANCE = new CURequestHandlerService(port);
try {
INSTANCE.server.start();
} catch (IOException e) {
System.out.println("Can't start GRPC server!");
}
}
in main class
CURequestHandlerService.start(16440);
I am using Ant since it is an old project and i maintaining it.
I add all grpc dependencies jars to dependencies directory.
my dependencies jars:
amqp-client-5.7.3.jar
failureaccess-1.0.1.jar
grpc-all-1.27.0.jar
grpc-api-1.27.0.jar
grpc-auth-1.27.0.jar
grpc-context-1.27.0.jar
grpc-core-1.27.0.jar
grpc-netty-1.27.0.jar
grpc-netty-shaded-1.27.0.jar
grpc-protobuf-1.27.0.jar
grpc-protobuf-lite-1.27.0.jar
grpc-stub-1.27.0.jar
grpc-testing-1.27.0.jar
guava-28.2-jre.jar
json-smart-1.2.jar
lettuce-4.3.0.Final-shaded.jar
libthrift-0.9.3.jar
opencensus-api-0.20.0.jar
opencensus-contrib-grpc-metrics-0.20.0.jar
perfmark-api-0.21.0.jar
protobuf-java-3.11.3.jar
protobuf-java-util-3.11.3.jar
protoc-gen-grpc-java-1.27.0-linux-x86_64.exe
slf4j-api-1.7.22.jar
slf4j-simple-1.7.22.jar
I found out the problem it is not a dependency issue after reading the server example in grpc-java repository. I underhanded that you must split the server class from the implementation class which extends form the Grpc generated class.
server class
/**
* Grpc instance class that used to initiate the server and call implementation class
*/
public class GrpcServer {
private final Server server;
private static GrpcServer INSTANCE = null;
private GrpcServer(int port) {
this.server = ServerBuilder.forPort(port)
.addService(new CURequestHandlerService())
.build();
}
public static void start(int port) {
if (INSTANCE == null)
INSTANCE = new GrpcServer(port);
try {
INSTANCE.server.start();
System.out.println("GRPC server started");
} catch (IOException e) {
System.out.println("Can't start GRPC server!");
}
}
}
implementation class
**
* Request Handler class contains the implementation for all functions initiated in proto files
* The implemented function
* */
public class CURequestHandlerService extends CURequestHandlerGrpc.CURequestHandlerImplBase{
public synchronized void Method1(Messages.Method1Input input,
StreamObserver<Messages.Method1Output> output) {
//...
output.onNext(outputResponse);
output.onCompleted();
}

Java-grpc and tikv-java: NoSuchFieldError: CONTEXT_SPAN_KEY

I am using java-grpc together with tikv-java (separately they work OK). But together I am struggling with the following error:
Exception in thread "main" java.lang.NoSuchFieldError: CONTEXT_SPAN_KEY
at io.grpc.internal.CensusTracingModule$TracingClientInterceptor.interceptCall(CensusTracingModule.java:327)
at io.grpc.ClientInterceptors$InterceptorChannel.newCall(ClientInterceptors.java:104)
at io.grpc.internal.ManagedChannelImpl.newCall(ManagedChannelImpl.java:551)
at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:113)
at com.pv.app.GetInsertServiceGrpc$GetInsertServiceBlockingStub.insert(GetInsertServiceGrpc.java:195)
at com.pv.app.Client.main(Client.java:55)
My code-client:
package com.pv.app;
import io.grpc.*;
public class Client {
public static void main(String[] args) throws Exception {
// Channel is the abstraction to connect to a service endpoint
// Let's use plaintext communication because we don't have certs
final ManagedChannel channel =
ManagedChannelBuilder.forTarget("0.0.0.0:8080").usePlaintext().build();
GetInsertServiceGrpc.GetInsertServiceBlockingStub stub =
GetInsertServiceGrpc.newBlockingStub(channel);
GetInsertServiceOuterClass.HelloMessage request =
GetInsertServiceOuterClass.HelloMessage.newBuilder().setName("hello").build();
System.out.println(request);
System.out.println("b4 req");
// Finally, make the call using the stub
stub.insert(request);
channel.shutdownNow();
}
}
My code-server:
package com.pv.app;
import io.grpc.Server;
import io.grpc.ServerBuilder;
/** Hello world! */
public class App {
public static void main(String[] args) throws Exception {
System.out.println("Hello-start");
Server server = ServerBuilder.forPort(8080).addService(new GetInsertServiceImpl()).build();
// Start the server
server.start();
// Server threads are running in the background.
System.out.println("Server started");
// Don't exit the main thread. Wait until server is terminated.
server.awaitTermination();
}
}
My code-implementation:
package com.pv.app;
import org.tikv.common.TiConfiguration;
import org.tikv.common.TiSession;
import org.tikv.raw.RawKVClient;
public class GetInsertServiceImpl
extends GetInsertServiceGrpc.GetInsertServiceImplBase {
#Override
public void insert(
GetInsertServiceOuterClass.HelloMessage request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
// HelloRequest has toString auto-generated.
System.out.println("insert");
System.out.println(request);
TiConfiguration conf = TiConfiguration.createRawDefault("pd0:2379");
System.out.println(1);
System.out.println("2");
System.out.println(conf);
TiSession session = TiSession.create(conf);
System.out.println("3");
RawKVClient client = session.createRawClient();
System.out.println("4");
// When you are done, you must call onCompleted.
responseObserver.onCompleted();
}
}
My proto:
syntax = "proto3";
import "google/protobuf/empty.proto";
option java_package = "com.pv.app";
// Request payload
message HelloMessage {
string name = 1;
}
// Defining a Service, a Service can have multiple RPC operations
service GetInsertService {
// Define a RPC operation
rpc insert (HelloMessage) returns (google.protobuf.Empty) {
};
}
What I do to deploy:
In downloaded repo client-java I do mvn clean install -Dmaven.test.skip=true
In my project folder
mvn install:install-file \
-Dfile=../client-java/target/tikv-client-java-2.0-SNAPSHOT.jar \
-DgroupId=org.tikv \
-DartifactId=tikv-client-java \
-Dversion=2.0-SNAPSHOT \
-Dpackaging=jar
In my project pom.xml
<dependency>
<groupId>org.tikv</groupId>
<artifactId>tikv-client-java</artifactId>
<version>2.0-SNAPSHOT</version>
</dependency>
Running java 8:
mvn -DskipTests package exec:java -Dexec.mainClass=com.pv.app.App
mvn -DskipTests package exec:java -Dexec.mainClass=com.pv.app.Client
Does anyone have a suggestion how to fix?
Full code is available here
I did my searching, tried to exclude grpc and opencensus, switch versions - did not help.
The problem is caused by conflicting io.opencensus versions. I was able to fix it by shading it in the tikv/client-java project.
In the tikv/client-java, pom.xml, maven-shade-plugin configuration:
<relocations>
...
<relocation>
<pattern>io.opencensus</pattern>
<shadedPattern>shade.io.opencensus</shadedPattern>
</relocation>
<relocations>
UPDATE
I have just realized that there were changes to the pom.xml merged to the master yesterday, so you may want to update it if you haven't yet.
UPDATE 2
I have just checked your project with the recent version of the tikv/client-java. The NoSuchFieldError: CONTEXT_SPAN_KEY is gone. There are other errors (java.net.UnknownHostException) but they are rather not related.

Get data from DBUS org.freedesktop.dbus and java - org.freedesktop.DBus$Error$UnknownMethod: Method doesn't exist

I try to get some data from a dbus service and work with it in Java.
I can get the information in cli with the following command:
dbus-send --print-reply --system --dest=com.victronenergy.solarcharger.ttyUSB0 /Dc/0/Voltage com.victronenergy.BusItem.GetValue
The result is:
method return time=1538903662.321580 sender=:1.14 -> destination=:1.806 serial=335692 reply_serial=2
variant double 13.43
What I tried to get this data in Java, is:
After hours of reading, I created an Interface.
package javadbus;
import java.util.Map;
import org.freedesktop.dbus.DBusInterface;
import org.freedesktop.dbus.DBusSignal;
import org.freedesktop.dbus.Variant;
import org.freedesktop.dbus.exceptions.DBusException;
public interface BusItem extends DBusInterface
{
public static class PropertiesChanged extends DBusSignal
{
public final Map<String,Variant> changes;
public PropertiesChanged(String path, Map<String,Variant> changes) throws DBusException
{
super(path, changes);
this.changes = changes;
}
}
public String GetDescription(String language, int length);
public Variant GetValue();
public String GetText();
public int SetValue(Variant value);
public Variant GetMin();
public Variant GetMax();
public int SetDefault();
public Variant GetDefault();
}
Here I call getConnection() and getRemoteObject() successfully.
package javadbus;
import org.freedesktop.dbus.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
import org.freedesktop.dbus.Variant;
public class VictronEnergyDBusSolarCharger {
private String port;
private DBusConnection conn;
public VictronEnergyDBusSolarCharger(String port) {
this.port = port;
try {
this.conn = DBusConnection.getConnection(DBusConnection.SYSTEM);
} catch (DBusException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getData(String item) {
BusItem bi;
String data = null;
Variant vData = null;
try {
bi = (BusItem)conn.getRemoteObject("com.victronenergy.solarcharger." + this.port, item, BusItem.class);
vData = bi.GetValue();
//data = bi.GetText();
} catch (DBusException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
...
}
It was a big task to resolve all dependecies and get the code compiled. But finaly I did it. So, javac now runs without errors.
But if I try to call the Method GetValue(), I get the following Exception:
[Sender] INFO org.freedesktop.dbus.MessageWriter - <= MethodCall(0,1) { Path=>/org/freedesktop/DBus, Interface=>org.freedesktop.DBus, Member=>Hello, Destination=>org.freedesktop.DBus } { }
[Sender] INFO org.freedesktop.dbus.MessageWriter - <= MethodCall(0,3) { Path=>/Dc/0/Voltage, Interface=>javadbus.BusItem, Member=>GetValue, Destination=>com.victronenergy.solarcharger.ttyUSB0 } { }
Exception in thread "main" org.freedesktop.DBus$Error$UnknownMethod: Method "GetValue" with signature "" on interface "javadbus.BusItem" doesn't exist
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 org.freedesktop.dbus.Error.getException(Error.java:141)
at org.freedesktop.dbus.Error.throwException(Error.java:171)
at org.freedesktop.dbus.RemoteInvocationHandler.executeRemoteMethod(RemoteInvocationHandler.java:158)
at org.freedesktop.dbus.RemoteInvocationHandler.invoke(RemoteInvocationHandler.java:222)
at com.sun.proxy.$Proxy1.GetValue(Unknown Source)
at javadbus.VictronEnergyDBusSolarCharger.getData(VictronEnergyDBusSolarCharger.java:28)
at javadbus.VictronEnergyDBusSolarCharger.getDcV(VictronEnergyDBusSolarCharger.java:38)
at javadbus.MainClass.main(MainClass.java:7)
Is it necessary to make a implementation of this Method GetValue? But why e.g. how should I do this? I only want to get this Information and not provide it like a Server.
Why was it a big task to get all dependencies?
dbus-java library and dependencies are all available at maven central, so a proper maven project should just work out-of-the-box.
Back to topic:
You don't have to implement GetValue(), but you need a suitable java interface for BusItem.
As far as I can see in the documentation of victronenergy (https://www.victronenergy.com/live/open_source:ccgx:d-bus) , your interface is not correct.
You provide SetDefault()/GetDefault() methods, which are only available on com.victronenergy.settings Objects, but you want to retrieve a com.victronenergy.BusItem (no part of the com.victronenergy.settings package).
This is one error. The second error is: you use the wrong package name for your BusItem class.
In your case DBus will try to resolve an object with the path javadbus.BusItem which is not provided by the connected BusAddress com.victronenergy.solarcharger.ttyUSB0.
The BusItem class has to be in package com.victronenergy or you have to use the annotation #DBusInterfaceName("com.victronenergy.BusItem").
The annotation will tell the DBus library to ignore the java package/class name and use the one provided in the annotation.
The Inteface BusItem had been created by CreateInterface-Script from https://dbus.freedesktop.org/doc/dbus-java/dbus-java/dbus-javase10.html and the XML from Introspect()
But you solved my real problem. I used the annotation #DBusInterfaceName("com.victronenergy.BusItem") now. No Exception anymore an i get data from my solarcharger. Thank you so much!

Can't connect to my tomcat 8 websocket

I have written a client program that connects to my websocket on the server. I set up tomcat8 with the examples working and hit the EchoAnnotation endpoint with my client program.
I wrote this endpoint program as follows:
#ServerEndpoint(value = "/websocket")
public class PortServer implements AirMessageListener {
public PortServer() { }
#OnOpen
public void start(Session session) {
//do stuff
}
#OnClose
public void end() {
//do stuff
}
}
#OnMessage
public void incoming(String message) {
//do stuff
}
#OnError
public void onError(Throwable tw) throws Throwable {
//do stuff
}
I compile this and create a war file called portserver and drop it into my tomcat webapps directory. I then switched my client program from connecting to: ws://localhost:8080/examples/websocket/echoAnnotation to ws://localhost:8080/portserver/websocket and run it. I get:
Connecting to:ws://localhost:8080/portserver/websocket
Exception in thread "main" com.corrisoft.air.exception.AirException: Error connecting to server
at com.corrisoft.air.socket.AirSocketClient.<init>(AirSocketClient.java:60)
at test.corrisoft.air.portserver.SocketConversation.<init>(SocketConversation.java:46)
at test.corrisoft.air.portserver.RunPortServerTester.initConfigProperties(RunPortServerTester.java:76)
at test.corrisoft.air.portserver.RunPortServerTester.<init>(RunPortServerTester.java:34)
at test.corrisoft.air.portserver.RunPortServerTester.main(RunPortServerTester.java:109)
Caused by: javax.websocket.DeploymentException: Handshake error.
at org.glassfish.tyrus.client.ClientManager$1$1.run(ClientManager.java:466)
at org.glassfish.tyrus.client.ClientManager$1.run(ClientManager.java:502)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.glassfish.tyrus.client.ClientManager$SameThreadExecutorService.execute(ClientManager.java:654)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at org.glassfish.tyrus.client.ClientManager.connectToServer(ClientManager.java:359)
at org.glassfish.tyrus.client.ClientManager.connectToServer(ClientManager.java:195)
at com.corrisoft.air.socket.AirSocketClient.<init>(AirSocketClient.java:58)
... 4 more
Caused by: org.glassfish.tyrus.core.HandshakeException: Response code was not 101: 404.
at org.glassfish.tyrus.core.Handshake.validateServerResponse(Handshake.java:279)
at org.glassfish.tyrus.client.TyrusClientEngine.processResponse(TyrusClientEngine.java:138)
at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleHandshake(GrizzlyClientFilter.java:318)
at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleRead(GrizzlyClientFilter.java:288)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:291)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:209)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:137)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:115)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:550)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:744)
I placed an index.html inside my portserver app and can hit: http://localhost:8080/portserver just fine, which means the directories are OK. I then verified that my class was in my WEB-INF/classes directory.
I looked at the examples and found the ExamplesConfig class that I thought might be a "magic" class that enables the endpoints, so I implemented my own and and stuck in the jar file.
/**
*
*/
package com.corrisoft.air.portserver;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerApplicationConfig;
import javax.websocket.server.ServerEndpointConfig;
/**
* #author Corrisoft Android Development
*/
public class WebSocketConfig implements ServerApplicationConfig {
/* (non-Javadoc)
* #see javax.websocket.server.ServerApplicationConfig#getAnnotatedEndpointClasses(java.util.Set)
*/
#Override
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
// Deploy all WebSocket endpoints defined by annotations in the
// web application. Filter out all others to avoid issues when running
// tests on Gump
Set<Class<?>> results = new HashSet<>();
for (Class<?> clazz : scanned) {
if (clazz.getPackage().getName().startsWith("com.corrisoft.air")) {
System.out.println("Adding endpoint for:" + clazz.getName());
results.add(clazz);
}
}
return results;
}
/* (non-Javadoc)
* #see javax.websocket.server.ServerApplicationConfig#getEndpointConfigs(java.util.Set)
*/
#Override
public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> scanned) {
return null;
}
}
It does not seem to be running this class.
Is there some configuration I missed?
Turns out that the problem was that one of my dependent classes was missing from the classpath. Tomcat 8, under these circumstances, doesn't add the endpoint and doesn't throw an exception into the log.
I deployed the same war file to tomcat 7 and got an exception. Worked the classpath until it was good and then deployed back to tomcat 8 where it is now working.
I created defect 56442 here: https://issues.apache.org/bugzilla/show_bug.cgi?id=56442 for tomcat eating the exception instead of displaying in the log.
For anyone else plagued by this; take a CLOSE look at your URI. I was piecing my url together, based on a configuration file. I missed a single "/" character when constructing the URL, and was convinced that it was correct! If you do stuff like the following, I suggest, printing out the "constructed URL" and studying that closely before chasing your tail:
public static final String WEBSOCKETHOST = "localhost"; // TODO: Get from configuration
public static final int WEBSOCKETPORT = 10080; // TODO: Get from configuration
public static final String WEBSOCKETSERVERROOT = "/sceagents"; // TODO: Get from configuration
public static final String WEBSOCKETSERVERENDPOINT = "neo"; // TODO: Get from configuration
public static final String WEBSOCKETPROTOCOL = "ws"; // TODO: Get from configuration
String uri = WEBSOCKETPROTOCOL + "://" + WEBSOCKETHOST + ":" + Integer.toString(WEBSOCKETPORT) + WEBSOCKETSERVERROOT + "/" + WEBSOCKETSERVERENDPOINT;

Error using neo4j with jdk 1.7

I am using Java 1.7 with neo4j-community-2.0-1.1 to build a sample neo4j graph database. Please see below my code
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
public class showData {
private static final String Neo4J_DBPath = "/Technology/neo4j-community-2.0-1.1";
/**
* #param args
*/
Node first;
Node second;
Relationship relation;
GraphDatabaseService graphDataService;
//List of relationships
private static enum RelationshipTypes implements RelationshipType
{
KNOWS
}
public static void main(String[] args)
{
showData data = new showData();
data.createDatabase();
data.removeData();
data.shutDown();
}
void createDatabase()
{
//GraphDatabaseService
graphDataService = new GraphDatabaseFactory().newEmbeddedDatabase(Neo4J_DBPath);
// Begin transaction
Transaction transaction = graphDataService.beginTx();
try
{
// create nodes and set the properties the nodes
first = graphDataService.createNode();
first.setProperty("Name", "Ravneet Kaur");
second = graphDataService.createNode();
second.setProperty("Name", "Harpreet Singh");
//specify the relationships
relation = first.createRelationshipTo(second, RelationshipTypes.KNOWS);
relation.setProperty("relationship-type", "knows");
//success transaction
System.out.println(first.getProperty("name").toString());
System.out.println(relation.getProperty("relationship-type").toString());
System.out.println(second.getProperty("name").toString());
transaction.success();
}
finally
{
transaction.finish();
}
}
void removeData()
{
Transaction transaction = graphDataService.beginTx();
try
{
first.getSingleRelationship(RelationshipTypes.KNOWS,Direction.OUTGOING).delete();
System.out.println("Nodes are deleted");
//delete the nodes
first.delete();
second.delete();
transaction.success();
}
finally
{
transaction.finish();
}
}
void shutDown()
{
graphDataService.shutdown();
System.out.println("Database is shutdown");
}
}
Earlier I was using Jave 1.6 to compile this code, but got to know that this neo4j jar complies with jdk 1.7. So I changed it to JDK 1.7 and made all necessary changes in Installed JRE, Execution Environments and Java Build Path in eclipse to point to latest java.
Now I get the following error
Exception in thread "main" java.lang.RuntimeException: Error starting org.neo4j.kernel.EmbeddedGraphDatabase, /Technology/neo4j-community-2.0-1.1
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:330)
at org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:63)
at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:92)
at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:198)
at org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(GraphDatabaseFactory.java:69)
at com.PNL.data.neo4j.showData.createDatabase(showData.java:45)
at com.PNL.data.neo4j.showData.main(showData.java:34)
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.impl.transaction.XaDataSourceManager#7594035c' was successfully initialized, but failed to start. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:509)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:307)
... 6 more
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource#24367e26' was successfully initialized, but failed to start. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:509)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
at org.neo4j.kernel.impl.transaction.XaDataSourceManager.start(XaDataSourceManager.java:164)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:503)
... 8 more
Caused by: org.neo4j.kernel.impl.storemigration.UpgradeNotAllowedByConfigurationException: Failed to start Neo4j with an older data store version. To enable automatic upgrade, please set configuration parameter "allow_store_upgrade=true"
at org.neo4j.kernel.impl.storemigration.ConfigMapUpgradeConfiguration.checkConfigurationAllowsAutomaticUpgrade(ConfigMapUpgradeConfiguration.java:39)
at org.neo4j.kernel.impl.storemigration.StoreUpgrader.attemptUpgrade(StoreUpgrader.java:71)
at org.neo4j.kernel.impl.nioneo.store.StoreFactory.tryToUpgradeStores(StoreFactory.java:144)
at org.neo4j.kernel.impl.nioneo.store.StoreFactory.newNeoStore(StoreFactory.java:124)
at org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource.start(NeoStoreXaDataSource.java:323)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:503)
... 11 more
BTW: Also my neo4j configuration parameter "allow_store_upgrade" is set to "true".
Any help will be really appreciated.
Regards
In your code the configuration is not picked up. To change this use the following snippet to initialize your db:
GraphDatabaseService graphDb = new GraphDatabaseFactory()
.newEmbeddedDatabaseBuilder(Neo4J_DBPath)
.loadPropertiesFromFile("confdir/neo4j.properties")
.newGraphDatabase();
Make sure neo4j.properties contains allow_store_upgrade=true. Alternatively you can use the deprecated setConfig(name, value) on the factory.

Categories

Resources