google Analytics

Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Sunday, August 15, 2010

(JMS) Sending Large Messages to Queue

public class LargeMessageExample
{
public static void main(final String[] args)
{
new LargeMessageExample().run(args);
}
private final long FILE_SIZE = 10L * 1024 * 1024 * 1024; // 10 GiB message
@Override
public boolean runExample() throws Exception
{
Connection connection = null;
InitialContext initialContext = null;\
try
{
// Step 1. Create an initial context to perform the JNDI lookup.
initialContext = getContext(0);
// Step 2. Perfom a lookup on the queue
Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue");
// Step 3. Perform a lookup on the Connection Factory. This ConnectionFactory has a special attribute set on
// it.
// Messages with more than 10K are considered large
ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
// Step 4. Create the JMS objects
connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue);
// Step 5. Create a huge file - this will form the body of the message we will send.
File fileInput = new File("huge_message_to_send.dat");
createFile(fileInput, FILE_SIZE);

// Step 6. Create a BytesMessage
BytesMessage message = session.createBytesMessage();

// Step 7. We set the InputStream on the message. When sending the message will read the InputStream
// until it gets EOF. In this case we point the InputStream at a file on disk, and it will suck up the entire
// file, however we could use any InputStream not just a FileInputStream.
FileInputStream fileInputStream = new FileInputStream(fileInput);
BufferedInputStream bufferedInput = new BufferedInputStream(fileInputStream);

message.setObjectProperty("JMS_HQ_InputStream", bufferedInput);

System.out.println("Sending the huge message.");

// Step 9. Send the Message
producer.send(message);

System.out.println("Large Message sent");

System.out.println("Stopping server.");

// Step 10. To demonstrate that that we're not simply streaming the message from sending to consumer, we stop
// the server and restart it before consuming the message. This demonstrates that the large message gets
// persisted, like a
// normal persistent message, on the server. If you look at ./build/data/largeMessages you will see the
// largeMessage stored on disk the server

connection.close();

initialContext.close();

stopServer(0);

// Give the server a little time to shutdown properly
Thread.sleep(5000);

startServer(0);

System.out.println("Server restarted.");

// Step 11. Now the server is restarted we can recreate the JMS Objects, and start the new connection

initialContext = getContext(0);

queue = (Queue)initialContext.lookup("/queue/exampleQueue");

cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");

connection = cf.createConnection();

session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

MessageConsumer messageConsumer = session.createConsumer(queue);

connection.start();

System.out.println("Receiving message.");

// Step 12. Receive the message. When we receive the large message we initially just receive the message with
// an empty body.
BytesMessage messageReceived = (BytesMessage)messageConsumer.receive(120000);

System.out.println("Received message with: " + messageReceived.getBodyLength() +
" bytes. Now streaming to file on disk.");

// Step 13. We set an OutputStream on the message. This causes the message body to be written to the
// OutputStream until there are no more bytes to be written.
// You don't have to use a FileOutputStream, you can use any OutputStream.
// You may choose to use the regular BytesMessage or
// StreamMessage interface but this method is much faster for large messages.

File outputFile = new File("huge_message_received.dat");

FileOutputStream fileOutputStream = new FileOutputStream(outputFile);

BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutputStream);

// Step 14. This will save the stream and wait until the entire message is written before continuing.
messageReceived.setObjectProperty("JMS_HQ_SaveStream", bufferedOutput);

fileOutputStream.close();

System.out.println("File streamed to disk. Size of received file on disk is " + outputFile.length());

return true;
}
finally
{
// Step 12. Be sure to close our resources!
if (initialContext != null)
{
initialContext.close();
}

if (connection != null)
{
connection.close();
}
}
}

private void createFile(final File file, final long fileSize) throws FileNotFoundException, IOException
{
FileOutputStream fileOut = new FileOutputStream(file);
BufferedOutputStream buffOut = new BufferedOutputStream(fileOut);
byte[] outBuffer = new byte[1024 * 1024];
for (long i = 0; i < fileSize; i += outBuffer.length)
{
buffOut.write(outBuffer);
}
buffOut.close();
}

}

Monday, August 2, 2010

EJB3 Session Bean annotation Example

--jndi.properties
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1300
/**
* Session Bean implementation class CallEjb3Bean
*/
@Stateless(name="CallEjb3Bean", mappedName="CallEjb3")
public class CallEjb3Bean implements CallEjb3BeanLocal {

/**
* Default constructor.
*/
public CallEjb3Bean() {
System.out.println("CallEjb3Bean");
}

public void callme(){
System.out.println("callme-->> Called");
}

}

@Local
public interface CallEjb3BeanLocal {
public void callme();
}


@Stateless(mappedName="testejb")
public class TestEjb3Bean implements TestEjb3BeanRemote, TestEjb3BeanLocal {

/**
* Default constructor.
*/
public TestEjb3Bean() {
System.out.println("TestEjb3Bean->>>>>>> Called");
}
@EJB
private static CallEjb3BeanLocal local;

public void sayHello(String name){
System.out.println("Name-->>"+name);
try {
System.out.println("Start--------------->g>>>");
InitialContext ctx = new InitialContext();
local.callme();
System.out.println("Ends--------------->>>>");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception----------------->>");
}
}

}

@Local
public interface TestEjb3BeanLocal {
public void sayHello(String name);
}

@Remote
public interface TestEjb3BeanRemote {
public void sayHello(String name);
}


public class Client
{
@EJB
public static TestEjb3BeanRemote remote;
public static void main(String[] args) throws Exception
{
InitialContext ctx = new InitialContext();
TestEjb3BeanRemote testEjb3BeanRemote = (TestEjb3BeanRemote) ctx.lookup("testejb");
testEjb3BeanRemote.sayHello("ANISH");

}
}

Wednesday, July 28, 2010

Ejb3 Stateful Bean Example

--jndi.properties
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost

@Stateful
@Remote(ShoppingCart.class)
public class ShoppingCartBean implements ShoppingCart, Serializable
{
private HashMap cart = new HashMap();

public void buy(String product, int quantity)
{
if (cart.containsKey(product))
{
int currq = cart.get(product);
currq += quantity;
cart.put(product, currq);
}
else
{
cart.put(product, quantity);
}
}

public HashMap getCartContents()
{
return cart;
}

@Remove
public void checkout()
{
System.out.println("To be implemented");
}
}



import java.util.HashMap;
import javax.ejb.Remove;

public interface ShoppingCart
{
void buy(String product, int quantity);

HashMap getCartContents();

@Remove void checkout();
}


public class Client
{
public static void main(String[] args) throws Exception
{
InitialContext ctx = new InitialContext();
ShoppingCart cart = (ShoppingCart) ctx.lookup("ShoppingCartBean/remote");

System.out.println("Buying 1 memory stick");
cart.buy("Memory stick", 1);
System.out.println("Buying another memory stick");
cart.buy("Memory stick", 1);

System.out.println("Buying a laptop");
cart.buy("Laptop", 1);

System.out.println("Print cart:");
HashMap fullCart = cart.getCartContents();
for (String product : fullCart.keySet())
{
System.out.println(fullCart.get(product) + " " + product);
}

System.out.println("Checkout");
cart.checkout();

System.out.println("Should throw an object not found exception by invoking on cart after @Remove method");
try
{
cart.getCartContents();
}
catch (javax.ejb.NoSuchEJBException e)
{
System.out.println("Successfully caught no such object exception.");
}


}
}

EJB3 Stateless Bean Example

A stateful session bean automatically saves bean state between client invocations
without your having to write any additional code,Amazon. In contrast,
stateless session beans do not maintain any state and model application services
that can be completed in a single client invocation. You could build stateless
session beans for implementing business processes such as charging a credit card
or checking customer credit history

for example

import javax.ejb.Stateless;

@Stateless
public class CalculatorBean implements CalculatorRemote, CalculatorLocal
{
public int add(int x, int y)
{
return x + y;
}

public int subtract(int x, int y)
{
return x - y;
}
}


@Local
public interface CalculatorLocal extends Calculator
{
}

@Remote
public interface CalculatorRemote extends Calculator
{

}


public interface Calculator
{
int add(int x, int y);

int subtract(int x, int y);
}


public class Client
{
public static void main(String[] args) throws Exception
{
InitialContext ctx = new InitialContext();
Calculator calculator = (Calculator) ctx.lookup("CalculatorBean/remote");

System.out.println("1 + 1 = " + calculator.add(1, 1));
System.out.println("1 - 1 = " + calculator.subtract(1, 1));
}
}

Thursday, July 8, 2010

Message Driven Bean 3.0

Message Driven Bean(MDB) 3.0 Exampe:--

import javax.ejb.MessageDriven;

import javax.ejb.ActivationConfigProperty;

import javax.jms.Message;

import javax.jms.MessageListener;

/**

*

* @author NathA1

*

*/

@MessageDriven(activationConfig =

{

@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"),

@ActivationConfigProperty(propertyName="destination", propertyValue="queue/anish"),

@ActivationConfigProperty(propertyName ="acknowledgeMode",propertyValue = "Auto-acknowledge"),

@ActivationConfigProperty(propertyName ="subscriptionDurability",propertyValue = "NonDurable"),

@ActivationConfigProperty(propertyName = "messageSelector",propertyValue = "Priority = ‘HIGH'"),

@ActivationConfigProperty(propertyName = "minSession",propertyValue = "1"),

@ActivationConfigProperty(propertyName = "maxSession",propertyValue = "15"),

@ActivationConfigProperty(propertyName = "maxMessages",propertyValue = "1")

})

public class MyMdb implements MessageListener {

@Override

public void onMessage(Message arg0) {

// TODO Auto-generated method stub

}

}