Messaging API gives you an easy and powerful tool for remote code execution. The short overview of the API is in Messaging chapter.
All you will need to do is to define specific message class or classes (should be shared between client and server).
The client side can issue messages using:
Java: MessageSender#send(message)
The server side should register a message listener:
Java: Configuration#setMessageRecipient(MessageRecipient)
Java: processMessage(ObjectContainer objectContainer, Object message)
method. ObjectContainer parameter gives full control over the database.
Let's reset our database and try updating using special UpdateServer message.
01private static void setObjects() { 02
new File(DB4O_FILE_NAME).delete(); 03
ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME); 04
try { 05
for (int i = 0; i < 5; i++) { 06
Car car = new Car("car" + i); 07
container.set(car); 08
} 09
container.set(new RemoteExample()); 10
} finally { 11
container.close(); 12
} 13
checkCars(); 14
}
01private static void updateCarsWithMessage() { 02
Configuration configuration = Db4o.newConfiguration(); 03
configuration.messageLevel(0); 04
ObjectServer server = Db4o.openServer(configuration, DB4O_FILE_NAME, 0xdb40); 05
server.grantAccess("user", "password"); 06
// create message handler on the server 07
server.ext().configure().clientServer().setMessageRecipient( 08
new MessageRecipient() { 09
public void processMessage( 10
MessageContext context, 11
Object message) { 12
// message type defines the code to be 13
// executed 14
if (message instanceof UpdateServer) { 15
Query q = context.container().query(); 16
q.constrain(Car.class); 17
ObjectSet objectSet = q.execute(); 18
while (objectSet.hasNext()) { 19
Car car = (Car) objectSet.next(); 20
car.setModel("Updated2-" 21
+ car.getModel()); 22
context.container().set(car); 23
} 24
context.container().commit(); 25
} 26
} 27
}); 28
try { 29
ObjectContainer client = Db4o.openClient("localhost", 0xdb40, "user", "password"); 30
// send message object to the server 31
MessageSender sender = client.ext().configure() 32
.clientServer().getMessageSender(); 33
sender.send(new UpdateServer()); 34
client.close(); 35
} finally { 36
server.close(); 37
} 38
checkCars(); 39
}
The advantage of this method is that having predefined message types you can make any changes to the handling code only on the server side. In the situations with many distributed clients it can really save you lots of time on support.