Right way to do JMS Application with MDB and Glassfish 3 - ejb

I am new to JMS and I Wrote a Wrote a sender and receiver and it has worked fine . Now i want a MDB to be used for this. I have googled a lot for this but did not find any good website so i am summering the way i wrote. Please correct me if i am wrong and
This is not completely working so i think there is something wrong in my code.
Sender:
public class MySender {
/**
* #param args
*/
public static void main(String[] args) {
try
{ //Create and start connection
Hashtable hashTable = new Hashtable();
hashTable.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.impl.SerialInitContextFactory");
hashTable.put(Context.URL_PKG_PREFIXES, "com.sun.enterprise.naming");
hashTable.put(Context.PROVIDER_URL, "http://localhost:4848");
//1) Create and start connection
InitialContext ctx=new InitialContext(hashTable);
QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");
QueueConnection con=f.createQueueConnection();
con.start();
//2) create queue session
QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
//3) get the Queue object
Queue t=(Queue)ctx.lookup("myQueue");
//4)create QueueSender object
QueueSender sender=ses.createSender(t);
//5) create TextMessage object
//5) create TextMessage object
TextMessage msg=ses.createTextMessage();
msg.setText("Hello ************************************");
sender.send(msg);
con.close();
System.out.println("*****************end********************");
}catch(Exception e){System.out.println(e);} }
}
MDB and Listner:
#MessageDriven(mappedName="myQueue")
public class MyListener implements MessageListener {
public void onMessage(Message message) {
try{
if (message != null && TextMessage.class.isInstance(message)) {
System.out.println("((((((((((((((((((((((((((((((((((");
TextMessage msg=(TextMessage)message;
final XStream xsStream = new XStream();
final TextMessage textMessage = (TextMessage) message;
Reader xmlMessage = new StringReader(textMessage.getText());
Object obj = xsStream.fromXML(xmlMessage);
System.out.println("obj:::::::::::"+obj);
if (obj != null && LetterOutHeader.class.isInstance(obj)) {
LetterOutHeader letterObj = (LetterOutHeader)obj;
System.out.println("one:::::::"+letterObj.getState());
}
System.out.println("following message is received::::::::::::::::::"+msg.getText());
}
}catch(JMSException e){System.out.println(e);}
}
}
Have Created a EJB Project, added a class MyListener and has exported that as a jar and have deployed that to the server.
Wrote a normal java application and have added a class MySender.
Run the MySender as a java program.

Related

JavaFX skips instructions while connecting to server

I have JavaFX application with two scenes. When user fills nick and clicks on button, it should change scenes and then connect to server. But for some unknown reason it first connects to server and change scenes only when it gets respond from server. But it should first do the two set Visible instructions and only then create the Vysilac or am I wrong ?
Here is my code - Button method ( spusteni and cekani are names of the scenes ), Vysilac is class that handles the connection.
Vysilac vysilac;
#FXML
private void pripojSe() throws IOException
{
String nick = textNick.getText();
if (nick != null && !nick.equals(""))
{
spusteni.setVisible(false);
cekani.setVisible(true);
vysilac = new Vysilac(nick);
}
}
public class Vysilac
{
private String nick = "Chyba - nick neexistuje";
private Socket socket;
private ObjectOutputStream output;
private ObjectInputStream input;
Vysilac( String nick) throws IOException
{
this.nick = nick;
socket = new Socket("localhost",33);
output = new ObjectOutputStream(socket.getOutputStream());
input = new ObjectInputStream(socket.getInputStream());
//System.out.println(nick);
output.writeObject(nick);
}
}
Thank for any help or advices:)
You need to run long-running operations on a seperate thread. Otherwise you block the JavaFX application thread that is responsible for updating the UI. In this case I'd use a Task to get the job done:
spusteni.setVisible(false);
cekani.setVisible(true);
Task<Vysilac> task = new Task<Vysilac>() {
#Override
protected Vysilac call() throws IOException {
return new Vysilac(nick);
}
};
// register state handlers
task.setOnSucceeded(evt -> vysilac = task.getValue());
task.setOnFailed(evt -> {
// TODO: error handling
});
new Thread(task).start();

SoapFault handling with Spring WS client - WebServiceGatewaySupport and WebServiceTemplate

I am trying to write a Spring WS client using WebServiceGatewaySupport. I managed to test the client for a successful request and response. Now I wanted to write test cases for soap faults.
public class MyClient extends WebServiceGatewaySupport {
public ServiceResponse method(ServiceRequest serviceRequest) {
return (ServiceResponse) getWebServiceTemplate().marshalSendAndReceive(serviceRequest);
}
#ActiveProfiles("test")
#RunWith(SpringRunner.class)
#SpringBootTest(classes = SpringTestConfig.class)
#DirtiesContext
public class MyClientTest {
#Autowired
private MyClient myClient;
private MockWebServiceServer mockServer;
#Before
public void createServer() throws Exception {
mockServer = MockWebServiceServer.createServer(myClient);
}
}
My question is how do i stub the soap fault response in the mock server, so that my custom FaultMessageResolver will be able to unmarshall soap fault?
I tried couple of things below, but nothing worked.
// responsePayload being SoapFault wrapped in SoapEnvelope
mockServer.expect(payload(requestPayload))
.andRespond(withSoapEnvelope(responsePayload));
// tried to build error message
mockServer.expect(payload(requestPayload))
.andRespond(withError("soap fault string"));
// tried with Exception
mockServer.expect(payload(requestPayload))
.andRespond(withException(new RuntimeException));
Any help is appreciated. Thanks!
Follow Up:
Ok so, withSoapEnvelope(payload) I managed to get the controller to go to my custom MySoapFaultMessageResolver.
public class MyCustomSoapFaultMessageResolver implements FaultMessageResolver {
private Jaxb2Marshaller jaxb2Marshaller;
#Override
public void resolveFault(WebServiceMessage message) throws IOException {
if (message instanceof SoapMessage) {
SoapMessage soapMessage = (SoapMessage) message;
SoapFaultDetailElement soapFaultDetailElement = (SoapFaultDetailElement) soapMessage.getSoapBody()
.getFault()
.getFaultDetail()
.getDetailEntries()
.next();
Source source = soapFaultDetailElement.getSource();
jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setContextPath("com.company.project.schema");
Object object = jaxb2Marshaller.unmarshal(source);
if (object instanceof CustomerAlreadyExistsFault) {
throw new CustomerAlreadyExistsException(soapMessage);
}
}
}
}
But seriously!!! I had to unmarshall every message and check the instance of it. Being a client I should be thorough with all possible exceptions of the service here, and create custom runtime exceptions and throw it from the resolver. Still at the end, its been caught in WebServiceTemplate and re thrown as just a runtime exception.
You could try with something like this:
#Test
public void yourTestMethod() // with no throw here
{
Source requestPayload = new StringSource("<your request>");
String errorMessage = "Your error message from WS";
mockWebServiceServer
.expect(payload(requestPayload))
.andRespond(withError(errorMessage));
YourRequestClass request = new YourRequestClass();
// TODO: set request properties...
try {
yourClient.callMethod(request);
}
catch (Exception e) {
assertThat(e.getMessage()).isEqualTo(errorMessage);
}
mockWebServiceServer.verify();
}
In this part of code mockWebServiceServer represents the instance of MockWebServiceServer class.

How to send objects over a network using Kryonet?

I am new to networking, and I am trying to network a board game that I have created using java.A friend of mine pointed me towards the Kryonet library. So far, it's great. I don't have to deal with sockets!
The problem I'm coming across is sending objects. Mainly, I have a Board type object. This object contains other objects, such as ArrayList objects and Fort objects.
I tried just registering the Board object, but I received these errors:
Exception in thread "Server" com.esotericsoftware.kryo.KryoException: java.lang.
IllegalArgumentException: Class is not registered: Game.Tile
Note: To register this class use: kryo.register(Game.Tile.class);
Serialization trace:
t0 (Game.Board)
at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.write(FieldSerializer.java:585)
at com.esotericsoftware.kryo.serializers.FieldSerializer.write(FieldSerializer.java:213)
at com.esotericsoftware.kryo.Kryo.writeClassAndObject(Kryo.java:571)
at com.esotericsoftware.kryonet.KryoSerialization.write(KryoSerializatio
n.java:50)
at com.esotericsoftware.kryonet.TcpConnection.send(TcpConnection.java:192)
etc....
Ok fine, Then I will also register Tile.class,
More errors, but then I need to register ArrayList.class - so I register it, and again more errors, so I register Fort.class.
When I register Fort.class, I enter into an infinite loop and get a ton of errors like this:
at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.write(FieldSerializer.java:564)
at com.esotericsoftware.kryo.serializers.FieldSerializer.write(FieldSerializer.java:213)
at com.esotericsoftware.kryo.Kryo.writeObject(Kryo.java:504)
at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.write(FieldSerializer.java:564)
at com.esotericsoftware.kryo.serializers.FieldSerializer.write(FieldSerializer.java:213)
at com.esotericsoftware.kryo.Kryo.writeObject(Kryo.java:504)
at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.write(FieldSerializer.java:564)
This leads me to believe I don't quite understand how to register properly and I can't find much information about how to register nested objects. My Fort class is actually an enumerated class but I'm not sure if that makes a difference? Any help would be greatly appreciated!
I have included a class with most of my networking code so you can see an idea of what I am trying to do.
This is my code for the networking:
public class Network extends Listener {
private Server server;
private Client client;
private boolean isServer;
private boolean messageReceived;
private PacketMessage message;
private Board board;
public Network(boolean isServer, Board board) throws IOException {
messageReceived = false;
this.board = board;
this.isServer = isServer;
if (isServer) {
initServer();
// receive();
} else {
initClient();
//probably want to run this in main
client();
}
}
private void initServer() throws IOException {
// 127.0.0.1 means myself
// ports up to 1024 are special and reserved
server = new Server();
registerClasses(server.getKryo());
server.bind(8000, 8001);
// starting a new thread
server.start();
// call my received and my connected
server.addListener(this);
}
private void initClient() throws IOException {
// 127.0.0.1 means myself
// ports up to 1024 are special and reserved
client = new Client();
registerClasses(client.getKryo());
// starting a new thread
client.start();
client.connect(5000, "127.0.0.1", 8000, 8001);
// call my received and call my connected
client.addListener(this);
}
//call in main
//
public void client(){
while(true){
sendRequest();
receive();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// tell Kryo what things it's going to have to send
private void registerClasses(Kryo kryo) {
kryo.register(Request.class);
kryo.register(PacketMessage.class);
kryo.register(Fort.class);
kryo.register(ArrayList.class);
kryo.register(Tile.class);
kryo.register(Board.class);
}
private void sendRequest() {
client.sendTCP(new Request());
}
private void receive() {
messageReceived = false;
while (!messageReceived) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// message.message is really packet.message
System.out.println("Received a message from the host: "
+ message.message);
}
public void received(Connection c, Object p) {
System.out.println("Received Message");
// Is the received packet the same class as PacketMessage.class?
if (p instanceof PacketMessage) {
// Cast it so we can access the message within
// PacketMessage packet =(PacketMessage) p;
// System.out.println("Received a message from the host: "+pa cket.message);
message = (PacketMessage) p;
// We have now received the message!
messageReceived = true;
}
else if (p instanceof Request){
// Create a message packet
PacketMessage packetMessage = new PacketMessage();
// Assign the message text
packetMessage.message = "Hello friend! The time is: "
+ new Date().toString();
// Send the message
//probably want another method to send
c.sendTCP(packetMessage);
c.sendTCP(board);
}
}
// This is run when a connection is received!
public void connected(Connection c) {
System.out.println("Received a connection from "
+ c.getRemoteAddressTCP().getHostString());
}
}
What is likely happening is that your Fort class contains a member of type Board, and this circular reference causes an infinite loop when serializing Fort.
Use the transient keyword to exclude members from serialization, or remove the circular reference altogether.

Netty: What is the right way to share NioClientSocketChannelFactory among multiple Netty Clients

I am new to Netty. I am using “Netty 3.6.2.Final”. I have created a Netty Client (MyClient) that talks to a remote server (The server implements a custom protocol based on TCP). I create a new ClientBootstrap instance for each MyClient instance (within the constructor).
My question is if I share “NioClientSocketChannelFactory” factory object among all the instances of MyClient then when/how do I release all the resources associated with the “NioClientSocketChannelFactory”?
In other words, since my Netty Client runs inside a JBOSS container running 24x7, should I release all resources by calling “bootstrap.releaseExternalResources();” and when/where should I do so?
More Info: My Netty Client is called from two scenarios inside a JBOSS container. First, in an infinite for loop with each time passing the string that needs to be sent to the remote server (in effect similar to below code)
for( ; ; ){
//Prepare the stringToSend
//Send a string and receive a string
String returnedString=new MyClient().handle(stringToSend);
}
Another scenarios is my Netty Client is called within concurrent threads with each thread calling “new MyClient().handle(stringToSend);”.
I have given the skeleton code below. It is very similar to the TelnetClient example at Netty website.
MyClient
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
public class MyClient {
//Instantiate this only once per application
private final static Timer timer = new HashedWheelTimer();
//All below must come from configuration
private final String host ="127.0.0.1";
private final int port =9699;
private final InetSocketAddress address = new InetSocketAddress(host, port);
private ClientBootstrap bootstrap;
//Timeout when the server sends nothing for n seconds.
static final int READ_TIMEOUT = 5;
public MyClient(){
bootstrap = new ClientBootstrap(NioClientSocketFactorySingleton.getInstance());
}
public String handle(String messageToSend){
bootstrap.setOption("connectTimeoutMillis", 20000);
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);
bootstrap.setOption("remoteAddress", address);
bootstrap.setPipelineFactory(new MyClientPipelineFactory(messageToSend,bootstrap,timer));
// Start the connection attempt.
ChannelFuture future = bootstrap.connect();
// Wait until the connection attempt succeeds or fails.
channel = future.awaitUninterruptibly().getChannel();
if (!future.isSuccess()) {
return null;
}
// Wait until the connection is closed or the connection attempt fails.
channel.getCloseFuture().awaitUninterruptibly();
MyClientHandler myClientHandler=(MyClientHandler)channel.getPipeline().getLast();
String messageReceived=myClientHandler.getMessageReceived();
return messageReceived;
}
}
Singleton NioClientSocketChannelFactory
public class NioClientSocketFactorySingleton {
private static NioClientSocketChannelFactory nioClientSocketChannelFactory;
private NioClientSocketFactorySingleton() {
}
public static synchronized NioClientSocketChannelFactory getInstance() {
if ( nioClientSocketChannelFactory == null) {
nioClientSocketChannelFactory=new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
}
return nioClientSocketChannelFactory;
}
protected void finalize() throws Throwable {
try{
if(nioClientSocketChannelFactory!=null){
// Shut down thread pools to exit.
nioClientSocketChannelFactory.releaseExternalResources();
}
}catch(Exception e){
//Can't do anything much
}
}
}
MyClientPipelineFactory
public class MyClientPipelineFactory implements ChannelPipelineFactory {
private String messageToSend;
private ClientBootstrap bootstrap;
private Timer timer;
public MyClientPipelineFactory(){
}
public MyClientPipelineFactory(String messageToSend){
this.messageToSend=messageToSend;
}
public MyClientPipelineFactory(String messageToSend,ClientBootstrap bootstrap, Timer timer){
this.messageToSend=messageToSend;
this.bootstrap=bootstrap;
this.timer=timer;
}
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
// Add the text line codec combination first,
//pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
//Add readtimeout
pipeline.addLast("timeout", new ReadTimeoutHandler(timer, MyClient.READ_TIMEOUT));
// and then business logic.
pipeline.addLast("handler", new MyClientHandler(messageToSend,bootstrap));
return pipeline;
}
}
MyClientHandler
public class MyClientHandler extends SimpleChannelUpstreamHandler {
private String messageToSend="";
private String messageReceived="";
public MyClientHandler(String messageToSend,ClientBootstrap bootstrap) {
this.messageToSend=messageToSend;
this.bootstrap=bootstrap;
}
#Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e){
e.getChannel().write(messageToSend);
}
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e){
messageReceived=e.getMessage().toString();
//This take the control back to the MyClient
e.getChannel().close();
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
// Close the connection when an exception is raised.
e.getChannel().close();
}
}
You should only call releaseExternalResources() once you are sure you not need it anymore. This may be for example when the application gets stopped or undeployed.

how to load class from jar inside equinox server side application in jboss 7

I'm face a problem since few days and I can't get solution. below is my app structure:
I have ejbapp.jar inside MyearDeployedOnJboss7.ear at the same level of equinox-server-side-app.war (built using warproduct) and I want to load class from MyJarToLaoadForEjbapp.jar which is in iModernizeWebClient_1.0.0.jar which is in plugins folder of equinox-server-side-app.war (I want show image of app structure but I cannot send image because forum rules need 10 score to be able to do that)
My question is how to allow ejbapp.jar load classes from "MyJarToLaoadForEjbapp.jar" inside MyWebClient_1.0.0.jar's plugin folder which is in the equinox-server-side-app.war.
I think using servletbridge classloader but no idea how to use it.
in my launch.ini I've:
osgi.*=#null org.osgi.*=#null eclipse.*=#null osgi.parentClassloader=app osgi.contextClassLoaderParent=app
I resolved my proble using Servlet HttpServiceTracker from the OSGI spec. how to do it : write HttpServiceTracker liket that :
public class HttpServiceTracker extends ServiceTracker {
private static final Logger logger = Logger
.getLogger(HttpServiceTracker.class.getName());
public HttpServiceTracker(BundleContext context) {
super(context, HttpService.class.getName(), null);
}
public Object addingService(ServiceReference reference) {
HttpService httpService = (HttpService) context.getService(reference);
logger.info("default context path : "
+ org.eclipse.rap.ui.internal.servlet.HttpServiceTracker.ID_HTTP_CONTEXT);
try {
logger.info("will register servlet ");
httpService.registerServlet("/programLauncherServlet",
new ProgramLauncherServlet(), null, null);
logger.info("servlet has been registred with http context ");
// httpService.registerResources( "/", "/html", null );
} catch (Exception e) {
//e.printStackTrace();
logger.info("The alias '/programLauncherServlet' is already in use");
}
return httpService;
}
public void removedService(ServiceReference reference, Object service) {
logger.info("will unregister servlet ");
HttpService httpService = (HttpService) service;
httpService.unregister("/programLauncher");
super.removedService(reference, service);
logger.info("servlet has been unregistred");
}
in your plugin activator class at method start :
#Override
public void start(BundleContext context) throws Exception {
super.start(context);
Activator.plugin = this;
BundleContext osgiContext = BundleReference.class
.cast(AnyClassOfYourProject.class.getClassLoader()).getBundle()
.getBundleContext();
serviceTracker = new HttpServiceTracker(osgiContext);
serviceTracker.open();
LOGGER.info("servlet published !!");
LOGGER.info("Bundle started.");
}
and for unregister the servlet at the stop method :
public void stop(BundleContext context) throws Exception {
Activator.plugin = null;
serviceTracker.close();
serviceTracker = null;
LOGGER.info("servlet unregistered from context !!");
super.stop(context);
}
that's all. your servlet is accessible outside your eclipse bundle and you can call methods inside the bundle.

Resources