15 August 2012

Strophe fix for JabberHttpBindingServlet

Strophe.js is best xmpp bosh library , but we found problem with JabberHttpBindingServlet connection ,i tried lot of hours for searching the solution from google , but no luck ,so myself dig the code after nearly one hour i got it . The problem is JHBServlet is expeting child node or empty child node form XMPP_RESTART body tag,but strophe is sending self-closed body tag

Solution : strophe.js

   if (this._data[i] === "restart") {
            body.attrs({
             to: this.domain,
             "xml:lang": "en",
             "xmpp:restart": "true",
             "xmlns:xmpp": Strophe.NS.BOSH
            });
              body.t(' ');  //Solution                       
          } else {
             body.cnode(this._data[i]).up();
          }

or download modified source Strophe.js

27 June 2008

Blob problem (oracle)

Problem
code: st.setBinaryStream(1,streamData,data.length)
while inserting blob .it will throw
ORA-01460: unimplemented or unreasonable conversion requested Exception

Problem root
oracle driver problem (ojdbc14.jar) if you are using oracle 9 driver or minor version driver (ojdbc14.jar) .it will happen

Solution

please download corresponding latest driver from oracle website

XmlBeans - ClassCastException

problem
while creating bean instance .it will throw
Exception in thread "main" java.lang.ClassCastException: com.javaorigin.xmlBean.SampleBean at com.javaorigin.xmlBean.SampleBean.SampleComplexBean.Factory.newInstance(Unknown Source)

Problem Root
This is java major and minor version problem .if you are using xmlbean 2.2.0 with jdk1.4.x
then it will happen

Solution
use latest jdk for compiling scemas (ex: use xmlBean2.2.0 with jdk1.5 )

23 August 2007

create a datasource from a stream using JMF

Two things you need before you can do this. First, you need to take the stream and convert it to a byte buffer (easy enough). Secondly, you need to know the content type of the stream

import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.PullDataSource;

import java.nio.ByteBuffer;
import java.io.IOException;

import javax.media.MediaLocator;
import javax.media.Duration;
import javax.media.Time;


/**
*
* @author Chad McMillan
*/

public class ByteBufferDataSource extends PullDataSource {

protected ContentDescriptor contentType;
protected SeekableStream[] sources;
protected boolean connected;
protected ByteBuffer anInput;

protected ByteBufferDataSource(){
}

/**
* Construct a ByteBufferDataSource from a ByteBuffer.
* @param source The ByteBuffer that is used to create the
* the DataSource.
*/
public ByteBufferDataSource(ByteBuffer input, String contentType) throws IOException {
anInput = input;
this.contentType = new ContentDescriptor(contentType);
connected = false;
}

/**
* Open a connection to the source described by
* the ByteBuffer/CODE>.
*


*
* The connect method initiates communication with the source.
*
* @exception IOException Thrown if there are IO problems
* when connect is called.
*/
public void connect() throws java.io.IOException {
connected = true;
sources = new SeekableStream [1];
sources[0] = new SeekableStream(anInput);
}

/**
* Close the connection to the source described by the locator.
*


* The disconnect method frees resources used to maintain a
* connection to the source.
* If no resources are in use, disconnect is ignored.
* If stop hasn't already been called,
* calling disconnect implies a stop.
*
*/
public void disconnect() {
if(connected) {
sources[0].close();
connected = false;
}
}

/**
* Get a string that describes the content-type of the media
* that the source is providing.
*


* It is an error to call getContentType if the source is
* not connected.
*
* @return The name that describes the media content.
*/
public String getContentType() {
if( !connected) {
throw new java.lang.Error("Source is unconnected.");
}
return contentType.getContentType();
}

public Object getControl(String str) {
return null;
}

public Object[] getControls() {
return new Object[0];
}

public javax.media.Time getDuration() {
return Duration.DURATION_UNKNOWN;
}

/**
* Get the collection of streams that this source
* manages. The collection of streams is entirely
* content dependent. The MIME type of this
* DataSource provides the only indication of
* what streams can be available on this connection.
*
* @return The collection of streams for this source.
*/
public javax.media.protocol.PullSourceStream[] getStreams() {
if( !connected) {
throw new java.lang.Error("Source is unconnected.");
}
return sources;
}

/**
* Initiate data-transfer. The start method must be
* called before data is available.
*(You must call connect before calling start.)
*
* @exception IOException Thrown if there are IO problems with the source
* when start is called.
*/
public void start() throws IOException {
}

/**
* Stop the data-transfer.
* If the source has not been connected and started,
* stop does nothing.
*/
public void stop() throws IOException {
}
}

(and for your stream)

import java.lang.reflect.Method;
import java.lang.reflect.Constructor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.BufferUnderflowException;


import javax.media.protocol.PullSourceStream;
import javax.media.protocol.Seekable;
import javax.media.protocol.ContentDescriptor;
/**
*
* @author Chad McMillan
*/
public class SeekableStream implements PullSourceStream, Seekable {


protected ByteBuffer inputBuffer;

/**
* a flag to indicate EOF reached
*/


/** Creates a new instance of SeekableStream */
public SeekableStream(ByteBuffer byteBuffer) {
inputBuffer = byteBuffer;
this.seek((long)(0)); // set the ByteBuffer to to beginning
}

/**
* Find out if the end of the stream has been reached.
*
* @return Returns true if there is no more data.
*/
public boolean endOfStream() {
return (! inputBuffer.hasRemaining());
}

/**
* Get the current content type for this stream.
*
* @return The current ContentDescriptor for this stream.
*/
public ContentDescriptor getContentDescriptor() {
return null;
}

/**
* Get the size, in bytes, of the content on this stream.
*
* @return The content length in bytes.
*/
public long getContentLength() {
return inputBuffer.capacity();
}

/**
* Obtain the object that implements the specified
* Class or Interface
* The full class or interface name must be used.
*


*
* The control is not supported.
* null is returned.
*
* @return null.
*/
public Object getControl(String controlType) {
return null;
}

/**
* Obtain the collection of objects that
* control the object that implements this interface.
*


*
* No controls are supported.
* A zero length array is returned.
*
* @return A zero length array
*/
public Object[] getControls() {
Object[] objects = new Object[0];

return objects;
}

/**
* Find out if this media object can position anywhere in the
* stream. If the stream is not random access, it can only be repositioned
* to the beginning.
*
* @return Returns true if the stream is random access, false if the stream can only
* be reset to the beginning.
*/
public boolean isRandomAccess() {
return true;
}

/**
* Block and read data from the stream.
*


* Reads up to length bytes from the input stream into
* an array of bytes.
* If the first argument is null, up to
* length bytes are read and discarded.
* Returns -1 when the end
* of the media is reached.
*
* This method only returns 0 if it was called with
* a length of 0.
*
* @param buffer The buffer to read bytes into.
* @param offset The offset into the buffer at which to begin writing data.
* @param length The number of bytes to read.
* @return The number of bytes read, -1 indicating
* the end of stream, or 0 indicating read
* was called with length 0.
* @throws IOException Thrown if an error occurs while reading.
*/
public int read(byte[] buffer, int offset, int length) throws IOException {

// return n (number of bytes read), -1 (eof), 0 (asked for zero bytes)

if ( length == 0 )
return 0;
try {
inputBuffer.get(buffer,offset,length);
return length;
}
catch ( BufferUnderflowException E ) {
return -1;
}
}

public void close() {

}
/**
* Seek to the specified point in the stream.
* @param where The position to seek to.
* @return The new stream position.
*/
public long seek(long where) {
try {
inputBuffer.position((int)(where));
return where;
}
catch (IllegalArgumentException E) {
return this.tell(); // staying at the current position
}
}

/**
* Obtain the current point in the stream.
*/
public long tell() {
return inputBuffer.position();
}

/**
* Find out if data is available now.
* Returns true if a call to read would block
* for data.
*
* @return Returns true if read would block; otherwise
* returns false.
*/
public boolean willReadBlock() {
return (inputBuffer.remaining() == 0);
}
}

16 August 2007

Getting Session Object using Session Id (HttpServlet )

HttpSessionContext is very usefull interface for getting all session objects using with session Id .

HttpSessionContext sc=request.getSession().getSessionContext();
HttpSession session=sc.getSession(session_id);


But In version 2.1 of the Servlet API the HttpSessionContext class was deprecated for security reasons by Sun, with no plans for a replacement. In short, steer clear of HttpSessionContext

19 July 2007

Access environment using ant

You can access environment variables within Ant using:


<property environment="env">


This provides all environment variables as Ant properties prefixed by "env.". For example, CLASSPATH would be accessible in Ant as ${env.CLASSPATH}.

Tomcat 5 Application Server Module Ant Code

http://www.blogger.com/post-create.g?blogID=2703864537782412832

18 July 2007

ANT Heap Memory

Well a bit of Googling turned up that Ant looks for an environment variable called ANT_OPTS which is use to set Java parameters. Just set the environment variable and off you go. So I added the following to increase the heap size:

export ANT_OPTS=-Xmx256m

That sets the maximum heap size to 256 Megabytes. It solved my problem as the XSLT transform topped out at about 220Meg. So if you ever need to increase the size of the Ant JVM, now you know how.

07 July 2007

Java Report - Open Source & Free

Popular Java Report Generating Tool

JasperReports is a powerful open source Java reporting tool that has the ability to deliver rich content onto the screen, to the printer or into PDF, HTML, XLS, CSV and XML files.

It is entirely written in Java and can be used in a variety of Java enabled applications, including J2EE or Web applications, to generate dynamic content.

Its main purpose is to help creating page oriented, ready to print documents in a simple and flexible manner.

JasperReport Home : http://jasperforge.org/sf/projects/jasperreports

06 July 2007

J2EE MVC Frameworks (Open Source )

Popular Frameworks

1. Spring Framework
2. Struts Framework
3. JavaServerFace (jsf)

Spring Framework

Introducing Spring is harder than most frameworks because it's not a single-purpose technology. Spring can be thought of as a huge framework of best practices for almost every area of Java software development. Everything from Plain-Old-Java-Object (POJO) development, to web application development, to enterprise application development, to persistence layer management and aspect oriented programming (AOP). Spring supports it all and does so with some of the most well designed and heavily tested code in the Java industry.

Because of its size, we need to focus this tutorial on the simplest application of Spring which is POJO development utilizing dependency injection. To clarify, dependency injection is a mechanism by which Spring handles creation and initializaton of the proper type of child object for a parent object at the moment the parent object needs the reference to the child. An example of where this is useful in the context of enterprise Java programming would be for your web application to instantly have access to your data-access layer in order to read or write an object from the database. This is a classic example of allowing Spring to inject the reference to the data-access layer into a POJO in the web application in order to load or save an object.

To immediately demystify any all-knowing magic from your minds about this process, the way this is done in the Spring is that the object reference relationships are mapped out in XML configuration files in Spring 1.2 and handled with Java 5 annotations in Spring 2.0.

Using this declarative method, Spring developers can actually soft-wire their application portions together using these annotations or XML configuration files such that when the application runs, Spring creates and instantiates all the object relationships "on demand". The advantage to having everything soft-wired is that portions of an application can quickly and easily be swapped out for alternative implementations (e.g. testing implementations) by simply changing around the annotations or XML configuration information and rerunning the application. There isn't even a need to recompile the application in some cases. This can be a huge boon to developers working on large applications that require constant testing or when delivering a larger application in interations. Spring provides a very natural way to thinking about these problems encouraging you to maintain your application in a modular architecture that supports this plugging and unplugging capability.

Spring Home : http://www.springframework.org/

Popular Tutorials

Tutorial Site -myeclipse

Tutorial Site -SpringHome
Tutorial Site-Roseindia



Struts

What Is the Struts Framework?

The Struts Framework is a standard for developing well-architected Web applications. It has the following features:

  • Open source
  • Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:
    • Model: application state
    • View: presentation of data (JSP, HTML)
    • Controller: routing of the application flow
  • Implements the JSP Model 2 Architecture
  • Stores application routing information and request mapping in a single core file, struts-config.xml
The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer.

Struts is a popular open source framework from Apache Software Foundation to build web applications that integrate with standard technologies such as Servlets, Java Beans and Java Server pages.

Struts offers many benefits to the web application developer,including the Model-View-Controller (MVC) design patterns (best practice) in web applications.

The Model-View-Controller paradigm applied to web applications lets you separately display code (for example, HTML and tag libraries) from flow control logic (action classes) from the data model to be displayed and updated by the application.

Struts offers a set of tag libraries to support the faster development of the different layers of the web application.

The basic idea of the MVC architecture is to divide the application into three layers: Model that represents the data layer, a view layer that represents the data processed by the model component; and a Controller component that is responsible for interaction between the model and the controller.

So when we say Struts is an MVC framework for web based applications, we actually mean that it facilitates the rapid development of applications by providing a Controller that helps interaction between the model and the view so that an application developer has not to worry about how to make view and the model independent of each other and yet exist in coordination.


Struts Home http://struts.apache.org

Popular Struts Tutorial

Ttorial Site- Roseindia

Ttorial Site-visualbuilder

Ttorial Site-laliluna

Ttorial Site-exadel.


JSF

JavaServer Faces technology simplifies building user interfaces for JavaServer applications. Developers of various skill levels can quickly build web applications by: assembling reusable UI components in a page; connecting these components to an application data source; and wiring client-generated events to server-side event handlers.

What Is JavaServer Faces?

  • Page navigation specification
  • Standard user interface components like input fields, buttons, and links
  • User input validation
  • Easy error handling
  • Java bean management
  • Event handling
  • Internationalization support
JSF Home : http://java.sun.com/javaee/javaserverfaces/

Populat JSF Tutorials

Ttorial Site-coreservlets.com

Ttorial Site-exadel

Ttorial Site-java.sun

Ttorial Site-jsftutorials

Ttorial Site-roseindia







23 June 2007

java.OutOfMemoryException solution

OurJava Program is running under theJVM, jvm is heart of the java,jvm is control the whole java program. jvm is allocating the memory space for every java instance . the default memory size is 64 mb . if any java instance exceed this size then Java.OutOfMemoryException will occurs .But we can change the default jvm size in runtime .

if you want allocate 250 mb then

Syntax java -Xmx250m ClassFileName



ex : java -Xmx500m -jar soundtracker.jar
java
-Xmx200m HelloWorld

05 May 2007

Mixing two audio files using Java Sound

There are no special methods in the Java Sound API to do this. However, mixing is a trivial signal processing task, it can be accomplished with plain Java code .
So manually mixing the two or more audioinputstreams using some attitional api
note: each Audiofile length must be same

Download the Sample Sourcecode with API : Sample Source code ais_mixer.rar
Alternate Downloading Mirror :mirror(ais_mixer.rar)

or


Example:

first convert audiofile to audioinputstream

audioInputStream = AudioSystem.getAudioInputStream(soundFile);
audioInputStream2 = AudioSystem.getAudioInputStream(soundFile2);

Create one collection list object using arraylist then add all audioinputstream's

Collection list=new ArrayList();
list.add(audioInputStream2);
list.add(audioInputStream);

then pass the audioformat and collection list to MixingAudioInputStream constructor

MixingAudioInputStream mixer=new MixingAudioInputStream(audioFormat, list);

finaly read data from mixed audioninputstream and give it to sourcedataline

nBytesRead =mixer.read(abData, 0,abData.length);

int nBytesWritten = line.write(abData, 0, nBytesRead);

27 April 2007

simple application for voice transmission and receiving using java rtp

Transmitter

import javax.media.*;
import javax.media.control.*;
import javax.media.protocol.*;
import javax.media.format.*;

import java.io.IOException;
import java.io.File;
import java.util.Vector;


public class MediaTransmitter {

private MediaLocator mediaLocator = null;
private DataSink dataSink = null;

private Processor mediaProcessor = null;
private static final Format[] FORMATS = new Format[] {
new AudioFormat(AudioFormat.ULAW_RTP)};

private static final ContentDescriptor CONTENT_DESCRIPTOR =
new ContentDescriptor(ContentDescriptor.RAW_RTP);

public MediaTransmitter(MediaLocator locator) {
mediaLocator = locator;
}

public void startTransmitting() throws IOException {

mediaProcessor.start();
dataSink.open();
dataSink.start();
}

public void stopTransmitting() throws IOException {

dataSink.stop();
dataSink.close();
mediaProcessor.stop();
mediaProcessor.close();
}


public void setDataSource(DataSource ds) throws IOException,
NoProcessorException, CannotRealizeException, NoDataSinkException {


mediaProcessor = Manager.createRealizedProcessor(
new ProcessorModel(ds, FORMATS, CONTENT_DESCRIPTOR));


dataSink = Manager.createDataSink(mediaProcessor.getDataOutput(),
mediaLocator);
}



public static void main(String[] args) {

try {

MediaLocator locator = new MediaLocator("rtp://192.168.1.111:333/audio");
MediaTransmitter transmitter = new MediaTransmitter(locator);
System.out.println("-> Created media locator: '" +
locator + "'");

Vector devices=CaptureDeviceManager.getDeviceList ( null );
CaptureDeviceInfo cdi= (CaptureDeviceInfo) devices.elementAt ( 0 );

DataSource source = Manager.createDataSource(
cdi.getLocator());

transmitter.setDataSource(source);
System.out.println("-> Set the data source on the transmitter");

transmitter.startTransmitting();
System.out.println("-> Transmitting...");
System.out.println(" Press the Enter key to exit");

System.in.read();
System.out.println("-> Exiting");
transmitter.stopTransmitting();

} catch (Throwable t) {
t.printStackTrace();
}

System.exit(0);
}
}


Receiver

import javax.media.*;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;

public class SimpleAudioPlayer {


private Player audioPlayer = null;

public SimpleAudioPlayer(MediaLocator url) throws IOException, NoPlayerException,
CannotRealizeException {
audioPlayer = Manager.createRealizedPlayer(url);
}

public void play() {
audioPlayer.start();
}


public void stop() {
audioPlayer.stop();
audioPlayer.close();
}
public static void main(String[] args) {
try {
MediaLocator loc=new MediaLocator("rtp://192.168.1.111:333/audio");
SimpleAudioPlayer player = new SimpleAudioPlayer(loc);
System.out.println(" Press the Enter key to exit");
player.play();
System.in.read();
System.out.println("-> Exiting");
player.stop();

} catch (Exception ex) {
ex.printStackTrace();
}

System.exit(0);
}
}


15 April 2007

Java TV API Overview

The Java TV API is being designed to provide access to functionality unique to digital television receivers, including:

  • Audio/video streaming
  • Conditional access
  • Access to in-band and out-of-band data channels
  • Access to service information
  • Tuner control for channel changing
  • On-screen graphics control
More :http://java.sun.com/products/javatv/

12 April 2007

Sound over IP with jmf RTP

This code will allow you to send and recive sound over IP network using RTP protocol.


import java.io.IOException;
import java.util.Vector;

import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.DataSink;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.NoProcessorException;
import javax.media.NotRealizedError;
import javax.media.Player;
import javax.media.Processor;
import javax.media.control.FormatControl;
import javax.media.control.TrackControl;
import javax.media.format.AudioFormat;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.DataSource;

public class SimpleVoiceTransmiter {

/**
* @param args
*/
public static void main(String[] args) {
// First find a capture device that will capture linear audio
// data at 8bit 8Khz
AudioFormat format= new AudioFormat(AudioFormat.LINEAR,
8000,
8,
1);

Vector devices= CaptureDeviceManager.getDeviceList( format);

CaptureDeviceInfo di= null;

if (devices.size() > 0) {
di = (CaptureDeviceInfo) devices.elementAt( 0);
}
else {
// exit if we could not find the relevant capturedevice.
System.exit(-1);
}

// Create a processor for this capturedevice & exit if we
// cannot create it
Processor processor = null;
try {
processor = Manager.createProcessor(di.getLocator());
} catch (IOException e) {
System.exit(-1);
} catch (NoProcessorException e) {
System.exit(-1);
}

// configure the processor
processor.configure();

while (processor.getState() != Processor.Configured){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

processor.setContentDescriptor(
new ContentDescriptor( ContentDescriptor.RAW));

TrackControl track[] = processor.getTrackControls();

boolean encodingOk = false;

// Go through the tracks and try to program one of them to
// output gsm data.

for (int i = 0; i < track.length; i++) {
if (!encodingOk && track[i] instanceof FormatControl) {
if (((FormatControl)track[i]).
setFormat( new AudioFormat(AudioFormat.GSM_RTP,
8000,
8,
1)) == null) {

track[i].setEnabled(false);
}
else {
encodingOk = true;
}
} else {
// we could not set this track to gsm, so disable it
track[i].setEnabled(false);
}
}

// At this point, we have determined where we can send out
// gsm data or not.
// realize the processor
if (encodingOk) {
processor.realize();
while (processor.getState() != Processor.Realized){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// get the output datasource of the processor and exit
// if we fail
DataSource ds = null;

try {
ds = processor.getDataOutput();
} catch (NotRealizedError e) {
System.exit(-1);
}

// hand this datasource to manager for creating an RTP
// datasink our RTP datasink will multicast the audio
try {
String url= "rtp://224.0.0.1:22224/audio/16";

MediaLocator m = new MediaLocator(url);

DataSink d = Manager.createDataSink(ds, m);
d.open();
d.start();
processor.start();
} catch (Exception e) {
System.exit(-1);
}
}



}

}




import java.io.IOException;
import java.net.MalformedURLException;

import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;

public class SimpleVoiceReciver{

/**
* @param args
*/
public static void main(String[] args) {
String url= "rtp://192.168.1.111:22224/audio/16";

MediaLocator mrl= new MediaLocator(url);

if (mrl == null) {
System.err.println("Can't build MRL for RTP");
System.exit(-1);
}

// Create a player for this rtp session
Player player = null;
try {
player = Manager.createPlayer(mrl);
} catch (NoPlayerException e) {
System.err.println("Error:" + e);
System.exit(-1);
} catch (MalformedURLException e) {
System.err.println("Error:" + e);
System.exit(-1);
} catch (IOException e) {
System.err.println("Error:" + e);
System.exit(-1);
}

if (player != null) {
System.out.println("Player created.");
player.realize();
// wait for realizing
while (player.getState() != Player.Realized){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
player.start();
} else {
System.err.println("Player doesn't created.");
System.exit(-1);
}
}

}

Record and Save Audio Using Java

Step 1:
First Read The Audio From MicroPhone

int cnt = targetDataLine.read( tempBuffer,0, tempBuffer.length);


Step 2:
Save data in output stream

byteArrayOutputStream.write(tempBuffer, 0, cnt);

Step 3:
Get the saved data into a byte array object.

byte audioData[]=byteArrayOutputStream.toByteArray();

Step 4:
Get an input stream on the byte array containing the data

InputStream byteArrayInputStream = new ByteArrayInputStream(audioData);
AudioFormat audioFormat = getAudioFormat();
audioInputStream =new AudioInputStream(byteArrayInputStream,audioFormat,
audioData.length/audioFormat.getFrameSize());



Step 5: Save To File

if (AudioSystem.isFileTypeSupported(AudioFileFormat.Type.AU,
audioInputStream)) {
AudioSystem.write(audioInputStream, AudioFileFormat.Type.AU, file);
}

Note :If U want Full Source Code for This One then Download the Java File
http://javasoft.phpnet.us/src/AudioRecorder.java

RTP Using Java

Download Sample Application For RTP using Java

http://www.live-share.com/files/202962/rtpvoice.rar.html


http://www.live-share.com/files/202964/sam.zip.html