How to encode a string to base64 in java ?

Hi, I want to send my user name to my SMTP server encoded in base64 .
How do I do this ??
Ramesh

Ok I wait for you.
I guess the following covert a string to base 8
String userName ="Ramesh"
byte[] strBytes = userName.getBytes("UTF-8");
I do not know about base64.
I need this urgently because I am sending my user name and password to my SMTP server and they should be encoded in base64.
Please help.
Ramesh

Similar Messages

  • How to encode sql string for SQL Server when using JDBC?

    in code, dynamically generate sql stirng like:
    String sqlstring = "select column from table where column=' " + var + " ' ";
    Question is: if var include char ' , it will cause error becuase ' is reserved by SQL Server for string reference.
    So how to encode string for dynamic sql string? for example, following sql(when var =" I'm tester"):
    select column from table where column like ' I'm tester '
    Edited by: KentZhou on Jun 17, 2009 3:10 PM

    Use PreparedStatement. Use it all the way. It not only saves you from SQL injections, but also eases setting non-standard Java objects like Date and InputStream in a SQL statement.
    Prepare here: [http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html].

  • How to store multiline string literal in to java bean shell variable

    Hello Experts
    How to store multiline string literals in java bean shell like we use triple quote for jython variable
    Using Jython
    str=""" helllo
    welcome to my world"""
    above syntax is working but not for java bean shell like below
    String str=""" hello
    welcome to my world""";
    So how to do this in java bean shell. I came to this scenario while storing logs to a variable. I believe there is no solution for storing multiline strings to java bean shell variable.
    <@
    String str="<%=odiRef.getPrevStepLog("MESSAGE")%>";
    @>
    Any suggestion will be highly appreciated.
    Thank You.

    maddythehunk wrote:
    Im trying this but its not working...
    while(billingQueryParamsItr.hasNext()) {
         billingQueryParam = (BillingQueryParam) billingQueryParamsItr.next();
         System.out.println("****** Param Name-->"+billingQueryParam.getParamName());
         String[0] name = billingQueryParam.getParamName(); // giving error ; expected
         //billingItemActionForm.setParamName(billingQueryParam.getParamName());
    Declare the array outside of the loop. Fill the array as you iterate. And stop putting your error messages inside of comments in the code.

  • How to encode a string containing HTML

    I have a string which contains HTML tags. This will be written to file so i need to encode it i guess to ISO-8859-1
    Please note: i am using JDK1.2.2
    My code is
    bytes = new byte[(int)rs.getString(k).length()*4];
    desc = new String(bytes, "ISO-8859-1");     
    This does not work. The tags remain the same i.e. "<" and ">" are still there in the String. In what format should HTML be encoded and what am i doing wrong above?

    or...
          * Encodes any special characters in the specified string with their
          * entity equivalents. 
          * @param  str  the original string
          * @return  the encoded string
         public static String encodeEntities(String str) {
              StringBuffer sb = new StringBuffer(str);
              // must replace '&' first
              char[] chars = {     // list of characters to replace
                   '&',      '<',      '>',      '\'',      '\"'
              String[] ents = {     // list of entities to replace with
                   "&",      "<",      ">",      "&apos;", """
              int len = Math.min(chars.length, ents.length);
              for(int i = 0; i < len; i++) {
                   for(int j = 0; j < sb.length(); j++) {
                        if(sb.charAt(j) == chars) {
                             sb.replace(j, j+1, ents[i]);
              return sb.toString();
         * Decodes any entities in the specified string with their character
         * equivalents.
         * @param str the encoded string
         * @return the decoded string
         public static String decodeEntities(String str) {
              if(str == null) {
                   return null;
              StringBuffer sb = new StringBuffer(str);
              String[] ents = {     // list of entities to replace
                   "&",      "<",      ">",      "&apos;", """
              String[] chars = {     // list of characters to replace with
                   "&",      "<",      ">",      "\'",      "\""
              int len = Math.min(chars.length, ents.length);
              int k = 0;
              for(int i = 0; i < len; i++) {
                   for(int j = 0; j < sb.length(); j++) {
                        k = j + ents[i].length();
                        if(k >= sb.length()) {
                             break;
                        if(sb.substring(j, k).equals(ents[i])) {
                             sb.replace(j, k, chars[i]);
              return sb.toString();

  • How to put a String(date) into Date (java.util.date)??

    hi there
    I got a GUI here and I need to read some JMaskedTextFields from it. I put them all into Strings. Now I need to pass them to the search-function, but one of the search arguments is not string. Its Date. I tried to initialize Date with Date(String s) but he doesnt take it. Now Im asking how can I do this the easiest way?
    The String has only digits and a . betwenn them, like this: 12.02.1978 and I want to pass this into the Date.
    thx for helping :-)

    thx
    Now I got it so far, it looks like this:
    String datumVon = suchen_kriterien_datVon_JMaTextFeld.getText();
    String datumBis = suchen_kriterien_datBis_JMaTextFeld.getText();
    SimpleDateFormat formatter = new SimpleDateFormat ("dd.MM.yyyy");
    ParsePosition pos = new ParsePosition(0);
    Date datVon = formatter.parse(datumVon, pos);
    Date datBis = formatter.parse(datumBis, pos);
    System.out.println(datVon);
    System.out.println(datBis);
    The Problem is that he only makes the first print when both dates are given. If I only give him the first, so he prints the first. If I give him only the scond, so he prints the second. But when I give him both, he only prints the first!!! why?

  • How to send query string to OSB Business Service?

    Hi
    I need to call a Servlet which is accepting http get request.
    My system design is
    I have a web service interface that I need to expose to Front end application. I am using Proxy service for this.
    Then I have a servlet at end system and using Business service to send request to servlet.
    I need to pass username, password, jndi context and payload using url encoding.
    What all steps do I need to follow for this? How to create query string , which variable I need to play with inbound or outbound?
    I have gone through all the answers on this forum but could not understand much.
    Thanks
    Vibhor

    Hii
    I am still unable to send http get request to end service.
    In flow I have setted $outbound/transport/request-http/query-string too.
    But I have to send request with url encoding.
    How to encode query string and how can I check whether my request is going correctly or not, is there any variable in which complete url would be stored.
    Thanks
    Vibhor
    Edited by: Vibhor Rastogi on Sep 15, 2010 9:49 AM

  • Re: Encode THAI Language into BASE64 Format

    Hi  Guru's,
            Have a requirement  to encode particular IDOC text fields which are in  THAI language to BASE64 format . We are able to encode the same for english but not able to do the same for Thai language so can any one help with the coding to create custom UDF  which can convert.
    Regards
    Sathish Kumar K.C

    Hi ,
       Please find below my code...
    public class Base64a {
    //     Mapping table from 6-bit nibbles to Base64 characters.
    private static char[]    map1 = new char[64];
         static {
            int i=0;
            for (char c='A'; c<='Z'; c+) map1[i+] = c;
            for (char c='a'; c<='z'; c+) map1[i+] = c;
            for (char c='0'; c<='9'; c+) map1[i+] = c;
            map1[i+] = ''; map1[i++] = '/'; }
    //     Mapping table from Base64 characters to 6-bit nibbles.
    private static byte[]    map2 = new byte[128];
         static {
            for (int i=0; i<map2.length; i++) map2<i> = -1;
            for (int i=0; i<64; i++) map2[map1<i>] = (byte)i; }
    Encodes a string into Base64 format.
    No blanks or line breaks are inserted.
    @param s  a String to be encoded.
    @return   A String with the Base64 encoded data.
    public static String encode (String s) {
         return new String(encode(s.getBytes())); }
    Encodes a byte array into Base64 format.
    No blanks or line breaks are inserted.
    @param in  an array containing the data bytes to be encoded.
    @return    A character array with the Base64 encoded data.
    public static char[] encode (byte[] in) {
         int iLen = in.length;
         int oDataLen = (iLen*4+2)/3;       // output length without padding
         int oLen = ((iLen+2)/3)*4;         // output length including padding
         char[] out = new char[oLen];
         int ip = 0;
         int op = 0;
         while (ip < iLen) {
            int i0 = in[ip++] & 0xff;
            int i1 = ip < iLen ? in[ip++] & 0xff : 0;
            int i2 = ip < iLen ? in[ip++] & 0xff : 0;
            int o0 = i0 >>> 2;
            int o1 = ((i0 &   3) << 4) | (i1 >>> 4);
            int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
            int o3 = i2 & 0x3F;
            out[op++] = map1[o0];
            out[op++] = map1[o1];
            out[op] = op < oDataLen ? map1[o2] : '='; op++;
            out[op] = op < oDataLen ? map1[o3] : '='; op++; }
         return out; }
    Regards
    Sathish Kumar

  • How can I pass a String by reference in java?

    Hello!
    My question is how to pass a String by reference in java.
    I tried to declare my variable, instead of using "String xxx = "f";", I used "String xxx = new String ("f");" :
    public static void main (String []args)
    String xxx = new String("f");
    StatusEnum result2 = getErrorPointStr(xxx);
         public StatusEnum getErrorPointStr(String text)
              StatusEnum testStatus = StatusEnum.PASS;
              StringBuffer buffer = new StringBuffer();
    buffer.append("123");
              text = buffer.toString();
              return testStatus;
    After calling to getErrorPointStr(String text) function, xxx = "f"
    So it does not work.
    How can I solve this? It is very important, the function will receive String and not something else.
    Thanks!

    Tolls wrote:
    Which is why I said:
    Which is why you only managed to change what 'text' referred to in the methodExcept that's not why. Even if String was mutable, doing text = whatever; would have the same effect; it would change what that variable refers to in the method, but it would not change the object's state.
    I meant that, since there was no way to actually change the data (ie the char[] or whatever) within the object 'text' referred to, the OP was attempting to change what 'text' referred to and hoping it would be reflected outside the method...which we know won't happen as Java is pass-by-value.\Ah, now I see.
    These by-value/by-reference threads tend to get confusing, because usually the person is passing a String, so the immutability of String tends to get in the way and just muddy the waters.

  • How encode unicode string like that?

    Hi there, i have a problem about encode unicode string:
    - The browser encode unicode string "&#432;?&#7855;?&#7891;" like that:
    %c6%b0%c3%a0%e1%ba%af%c3%a2%e1%bb%93
    - I try but i can't find the way to do like this in Java
    - Anyone know how do that? Thanks.

    Have a look at the URLEncoder class.

  • How to encode a password ??

    Hi,
    How to encode (and decode after) a password, in Base64 for example ? Is it possible to do that automatically with Java ??
    Thanks in advance
    Steve

    I have finding how to encode but i don't know how to decode now !
    This is my code :
    sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
    encoder.encode(myJTextField.getText());
    It works very well but this don't work (decode) :
    sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
    decoder.decode(myPassword);
    the error : "the method decode with a String for parameter doesn't exist"
    And i don't know how to find the declaration of this method.
    Help plzzzzz
    Thanks
    Steve

  • How to put a String into a byte array

    How can i put a String into a byte array byte[]. So that i can send it to the serial port for output to an LCD display. Cheers David

    javadocs for String
    getBytes
    public byte[] getBytes()
    Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
    Returns:
    The resultant byte arraySince:
    JDK1.1

  • How to encode request url

    String szUsrName="venkat & ashique";
    <a href="javascript :
    window.open(../jsp/Customer.jsp?cust_name=<%=szUsrName%">)">
    </a>
    Request URL:=> Customer.jsp?cust_name=venkat & ashique
    --I think from ashique it is taking as another req parameter.
    but in Customer.jsp the request parameter value comming as '''venkat''' iwant to get whole String venkat & ashique. What is the problem i know.Problem is in the string '&' symbol is there.But the solution i dont know plz can u help me. How to encode that url</a>

    You need to escape non-alphanumeric characters with %XX where XX is the hexadecimal value for that character. For example:
    "venkat & ashique" => "venkat%20%26%20ashique"%20 is space and %26 is the &.

  • String - enc.Base64 - XML - dec.Base64 - String

    Well, I encrypt a string using the Base64 Class from sourceforge.net 'iharder'.
    Then I write it to an XML-file.
    That's working fine. But if I load the XML-file, parse it and want to decode my base64.encrypted String, the decoder produces only senseless characters... the string is not the same as before :-( ...
    what am I doing wrong?
    Here are some code snippets:
    encoding:
    String encryptedPassword = Base64.encodeString(Globals.password);decoding:
    String decryptedPassword = Base64.decode(password.getFirstChild().toString()).toString();I hope, someone can help me :-D

    You are assuming that
    "password.getFirstChild().toString()" returns the
    result of your "encryption", aren't you? If I use non-encrypted text instead of a encrypted string, it returns my plain-text password without any problems!
    And you are
    assuming that the Base64 encode and decode methods
    work correctly.Hmmm... I just decoded the password for printing it out on screen before writing the encrypted password to the xml-file:
    password (norm): test
    password (encrypted): dGVzdA==
    password (decrypted): [B@14ed577
    corresponding code:
    String encryptedPassword = Base64.encodeString(Globals.password);
    System.out.println("Passwort (norm): "+Globals.password);
    System.out.println("Passwort (encrypted): "+encryptedPassword);
    System.out.println("Passwort (decrypted): "+Base64.decode(encryptedPassword));That seems to me, that the decoder doesn't work properly.
    But I can't believe that... I chose iharder because it is recommended by many users on java.sun!
    If you want to debug something, don't try to debug two
    things at once. First test that decode() and encode()
    are really inverses. (And what's with that .toString()
    at the end of your decoding?) This decode-methode returns byte[]... the .toString()-method should generate a string from that byte[]. I know, it looks freaky :-D
    Second, find out whether
    that DOM calculation is getting the node you believe
    it is getting, instead of some other node.Well, the data -> xml -> data routines work fine, I wrote them using non-encrypted plain text. The encryption-decryption statements were added later.
    The xml-file's encoding is UTF-8. That's generated and loaded by DOM. I don't think, that DOM mixes up encodings of its own?!? (-> luis_m)

  • How to encode request parameters?

    Hi I'm running a small web application developed with JSP pages. But it turns out that it relies on cookies to maintain sessions, which is a limitation if the client's cookie setting disables cookies.
    I know that I could encode the request parameters and use GET method to communicate information between client and server, but have no idea how this is done.
    Can you give me some code, or recommend some tutorial to me? Thanks!

    1. If you don't want to use cookies, you could use URL rewriting to append the session ID. When you redirect to another page, do something like the following:
    a. first choose whether you want to forward or sendRedirect: (the following example is a redirect)
    //encode the parameter values to encode special characters, such as spaces
    String parameterOne = java.net.URLEncoder.encode("some value");
    String parameterTwo = java.net.URLEncoder.encode("some other value");
    //build the query string any way you want
    String queryString="?key1="+parameterOne+"&key2="+parameterTwo;
    /* Use response.encodeRedirectURL if running it through a sendRedirect.
       Doing so will rewrite the url with the session ID appended to the
       end. */
    response.sendRedirect(response.encodeRedirectURL("some.jsp"+queryString));This little code snippet demonstrates two things. It shows that URL rewriting can be used to append the session ID. It also shows you how to encode parameters (i.e. use URLEncoder.encode()).
    If you want to encode your string in the JSP, you could also do it using javascript:
    <script language="JavaScript">
    <!--
       //this is just an example javascript function
       function openPage() {
          var thisForm=document.formName;
          /* get your form element values (these are text boxes).
             Note: the javascript escape() function url encodes the values.
                   there are also other js functions to do this. */
          var paramOne=escape(thisForm.paramOne);
          var paramTwo=escape(thisForm.paramTwo);
          var queryString="?paramOne="+paramOne+"&paramTwo="+paramTwo;
          window.open("some.jsp"+queryString,"some_window_name");
       }//end openPage
    //-->
    </script>Or, you could build it using JSP expressions and scriptlets. Its really up to you. These are just rudimentary examples to help you get started.

  • Do any one kown how to encoder pcm to alaw if you use jmf?

    I'm have the problem about it how to encoder pcm to alaw?
    I find some code about it, but not work in jmf.
    A friend in forum tell me write it by myself , because jmf not support for alaw.
    But i'm new about this, so i want whether somebody could help me if you have the same code about this.
    code like this:
    capture.java
    * support : locator, datasource
    public class Capture extends MainFrame {
        private static final long serialVersionUID = 1L;
        private Processor cp = null;
        private Boolean isMix = false;
        private Boolean isUlaw = false;
        private MainFrame mf = null;
        public Capture(MainFrame mf, boolean useVideo) {
            this.isMix = useVideo;
            this.mf = mf;
        public Capture(MainFrame mf) {
            this.mf = mf;
        public Capture(boolean useVideo) {
            this.isMix = false;
        //get video MediaLocator
        public MediaLocator getVideoLocator() {
            MediaLocator VideoLocator = null;
            Vector VideoCaptureList = null;
            CaptureDeviceInfo VideoCaptureDeviceInfo = null;
            VideoFormat videoFormat = new VideoFormat(VideoFormat.YUV);
            VideoCaptureList = CaptureDeviceManager.getDeviceList(videoFormat);
            if (VideoCaptureList.size() > 0) {
                VideoCaptureDeviceInfo = (CaptureDeviceInfo) VideoCaptureList.elementAt(0);
                VideoLocator = VideoCaptureDeviceInfo.getLocator();
            } else {
    //--- Search video device
                VideoCaptureList = (Vector) CaptureDeviceManager.getDeviceList(null).clone();
                Enumeration getEnum = VideoCaptureList.elements();
                while (getEnum.hasMoreElements()) {
                    VideoCaptureDeviceInfo = (CaptureDeviceInfo) getEnum.nextElement();
                    String name = VideoCaptureDeviceInfo.getName();
                    if (name.startsWith("vfw:")) {
                        CaptureDeviceManager.removeDevice(VideoCaptureDeviceInfo);
                int nDevices = 0;
                for (int i = 0; i < 10; i++) {
                    String name = com.sun.media.protocol.vfw.VFWCapture.capGetDriverDescriptionName(i);
                    if (name != null && name.length() > 1) {
                        System.err.println("Found device" + name);
                        System.err.println("Querying device.Please wait....");
                        com.sun.media.protocol.vfw.VFWSourceStream.autoDetect(i);
                        nDevices++;
                VideoCaptureDeviceInfo = (CaptureDeviceInfo) CaptureDeviceManager.getDeviceList(videoFormat).elementAt(0);
                VideoLocator = VideoCaptureDeviceInfo.getLocator();
            return VideoLocator;
        //get audio MediaLocator
        public MediaLocator getAudioLocator() {
            MediaLocator AudioLocator = null;
            Vector AudioCaptureList = null;
            CaptureDeviceInfo AudioCaptureDeviceInfo = null;
            AudioFormat audioFormat = new AudioFormat(AudioFormat.LINEAR);
            AudioCaptureList = CaptureDeviceManager.getDeviceList(audioFormat);
            if (AudioCaptureList.size() > 0) {
                AudioCaptureDeviceInfo = (CaptureDeviceInfo) AudioCaptureList.elementAt(0);
                AudioLocator = AudioCaptureDeviceInfo.getLocator();
                System.out.println("get audio locator");
            } else {
                System.out.println("empty");
                AudioLocator = null;
            return AudioLocator;
        public DataSource getDataSource() {
            try {
                DataSource[] source = new DataSource[2];    //audio 0; video 1;
                source[0] = Manager.createDataSource(getAudioLocator());
                if (isMix) {
                    DataSource MixDataSource = null;
                    source[1] = Manager.createDataSource(getVideoLocator());
                    MixDataSource = Manager.createMergingDataSource(source);
                    return MixDataSource;
                } else {
                    return source[0];
            } catch (Exception ex) {
                System.out.println("---error0---" + ex);
                return null;
        public DataSource getDataSourceByProcessor() {
            StateHelper sh = null;
            DataSource OutDataSource = null;
            DataSource InputSource = null;
            InputSource = getDataSource();
            try {
                cp = Manager.createProcessor(InputSource);
            } catch (IOException ex) {
                System.out.println("---error1---" + ex);
            } catch (NoProcessorException ex) {
                System.out.println("---error2---" + ex);
            sh = new StateHelper(cp);
            if (!sh.configure(10000)) {
                System.out.println("Processor Configured Error!");
                System.exit(-1);
            ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
            cp.setContentDescriptor(cd);
            AudioFormat ulawFormat = new AudioFormat(AudioFormat.ULAW_RTP, 8000.0, 8, 1);
           // change encode to alaw here?
            TrackControl[] tracks = cp.getTrackControls();
            boolean encodingState = false;
            for (int i = 0; i < tracks.length; i++) {
                if (!encodingState && tracks[i] instanceof FormatControl) {
                    if (tracks.setFormat(ulawFormat) == null) {
    tracks[i].setEnabled(false);
    } else {
    encodingState = true;
    //---- ptime set
                   if (isUlaw) {
         try {
         System.out.println("Cambiando la lista de codecs...");
         Codec[] codec = new Codec[3];
         codec[0] = new com.ibm.media.codec.audio.rc.RCModule();
         codec[1] = new com.ibm.media.codec.audio.ulaw.JavaEncoder();
         //codec[2] = new com.ibm.media.codec.audio.ulaw.Packetizer();
         codec[2] = new com.sun.media.codec.audio.ulaw.Packetizer();
         ((com.sun.media.codec.audio.ulaw.Packetizer) codec[2]).setPacketSize(160);
         (tracks[i]).setCodecChain(codec);
         } catch (UnsupportedPlugInException ex) {
         } catch (NotConfiguredError ex) {
    } else {
    tracks[i].setEnabled(false);
    if (!encodingState) {
    System.out.println("Encode error");
    System.exit(-1);
    if (!sh.realize(10000)) {
    System.out.println("Processor Realized Error!");
    System.exit(-1);
    OutDataSource = cp.getDataOutput();
    return OutDataSource;
    //run
    public void start() {
    cp.start();
    //stop
    public void close() {
    cp.close();

    test.java (get outputDatasource form capture.java)
    package siphone.test;
    import java.io.IOException;
    import java.net.InetAddress;
    import javax.media.Format;
    import javax.media.Manager;
    import javax.media.Player;
    import javax.media.PlugInManager;
    import javax.media.control.BufferControl;
    import javax.media.format.UnsupportedFormatException;
    import javax.media.protocol.DataSource;
    import javax.media.protocol.PushBufferDataSource;
    import javax.media.protocol.PushBufferStream;
    import javax.media.rtp.InvalidSessionAddressException;
    import javax.media.rtp.Participant;
    import javax.media.rtp.RTPControl;
    import javax.media.rtp.RTPManager;
    import javax.media.rtp.ReceiveStream;
    import javax.media.rtp.ReceiveStreamListener;
    import javax.media.rtp.SendStream;
    import javax.media.rtp.SendStreamListener;
    import javax.media.rtp.SessionAddress;
    import javax.media.rtp.SessionListener;
    import javax.media.rtp.event.ByeEvent;
    import javax.media.rtp.event.NewParticipantEvent;
    import javax.media.rtp.event.NewReceiveStreamEvent;
    import javax.media.rtp.event.NewSendStreamEvent;
    import javax.media.rtp.event.ReceiveStreamEvent;
    import javax.media.rtp.event.RemotePayloadChangeEvent;
    import javax.media.rtp.event.SendStreamEvent;
    import javax.media.rtp.event.SessionEvent;
    import javax.media.rtp.rtcp.SourceDescription;
    import siphone.decode.AlawRtpDecoder;
    import siphone.device.Capture;
    import siphone.gui.MainFrame;
    * @author kaiser
    public class Dial implements SessionListener, ReceiveStreamListener, SendStreamListener {
        private String ip = null;
        private int TargetPort;
        private int LocalPort;
        private MainFrame mf = null;
        private Capture capture = null;
        private DataSource oDataSource = null;
        private RTPManager rtp = null;
        private SendStream stream = null;
        private Player play = null;
        private Boolean LogStatu = false;
        static private Format AlawRtpFormat;
        public Dial(String ip, String rport, int lport, MainFrame mf) {
            this.ip = ip;
            this.TargetPort = Integer.parseInt(rport);
            this.LocalPort = lport;
            this.mf = mf;
            capture = new Capture(false);
            oDataSource = capture.getDataSourceByProcessor();
        public static void main(String[] args) throws IOException {
            Dial dial = new Dial("192.168.200.40", "40000", 10000, null);
            dial.Init();
            System.in.read();
            dial.stop();
        public synchronized void Init() {
            PushBufferDataSource pushDataSource = (PushBufferDataSource) oDataSource;
            PushBufferStream pushStream[] = pushDataSource.getStreams();
            SessionAddress localAddress, targetAddress;
            try {
                rtp = RTPManager.newInstance();
                rtp.addReceiveStreamListener(this);
                rtp.addSendStreamListener(this);
                rtp.addSessionListener(this);
                //port: TargetPort or LocalPort;
                localAddress = new SessionAddress(InetAddress.getLocalHost(), TargetPort);
                targetAddress = new SessionAddress(InetAddress.getByName(ip), TargetPort);
                rtp.initialize(localAddress);
                rtp.addTarget(targetAddress);
                BufferControl bc = (BufferControl) rtp.getControl("javax.media.control.BufferControl");
                if (bc != null) {
                    bc.setBufferLength(100);
                stream = rtp.createSendStream(oDataSource, 0);
                stream.start();
                capture.start();
                System.out.println("voice starting...........\n");
            } catch (UnsupportedFormatException ex) {
                System.err.println("error0:\n" + ex);
            } catch (InvalidSessionAddressException ex) {
                System.err.println("error1:\n" + ex);
            } catch (IOException ex) {
                System.err.println("error2:\n" + ex);
        //stop
        public void stop() {
            capture.close();
            if (rtp != null) {
                rtp.removeTargets("close session");
                rtp.dispose();
                rtp = null;
            System.out.println("close session...........\n");
        public void update(SessionEvent evt) {
            if (evt instanceof NewParticipantEvent) {
                Participant sPart = ((NewParticipantEvent) evt).getParticipant();
                System.out.print("  - join: " + sPart.getCNAME());
        public void update(ReceiveStreamEvent rex) {
            ReceiveStream rStream = rex.getReceiveStream();
            Participant rPart = rex.getParticipant();
            if (rex instanceof NewReceiveStreamEvent) {
                try {
                    DataSource rData = rStream.getDataSource();
                    RTPControl rcl = (RTPControl) rData.getControl("javax.media.rtp.RTPControl");
                    if (rcl != null) {
                        System.out.print("  - receive RTPControl info | the AudioFormat: " + rcl.getFormat());
                    } else {
                        System.out.print("  - receive RTPControl info");
                    if (rPart == null) {
                        System.out.print(" UNKNOWN");
                    } else {
                        System.out.print("data form " + rPart.getCNAME());
                    play = Manager.createRealizedPlayer(rData);
                    if (play != null) {
                        play.start();
                } catch (Exception ex) {
                    System.out.print("NewReceiveStreamEvent Exception " + ex.getMessage());
                    return;
            } else if (rex instanceof ByeEvent) {
                System.out.print("  - receive bye message: " + rPart.getCNAME() + "   exit");
                stop();
                return;
    }Anyone can tell me how to do?
    Thank you very much!

Maybe you are looking for