InputStream.available()

Hi,
InputStream is = socket.getInputStream();
int n = is.available();
n don't return number of bytes available in the InputStream, it is always 0.
Why?
~Hill

available is not a good function to use because it's behavior is badly defined.
It is not implemented correctly in many input streams. This is because of the nature of the streams, they generally are not buffered very well in the lower systems. The InputStream api says that the available function SHOULD be overridden but is doesn't have to be.
Especially now with the new NIO classes, you don't need to use this functionality at all. This is one of the reasons that the NIO was created, as if this functionality actually worked correctly, one of the main reason for NIO ( the problem of one reader per thread ) would be eliminated.

Similar Messages

  • Unable to understand InputStream.available() method, need some help

    dear friends,
    The following is my doubt. please kindly help me in this. this will help me a lot in understanding some consepts.
    Environment: i am using jdk1.4.1_01 on windowsxp.
    i am using IE6.0 to make requets.
    My requirement:
    what i am actually trying to do is i want to see the raw material
    send by the browser when we made a request to the server
    by the browser.basically i want to see the request line
    and headers as it is that is send by the browser to the server.
    so i thought to code a server that can print the request send
    by the browser as it is on the command window.
    i had taken two examples and i am running Server2.java (look at the bottom for this code)and i made a 25 requests to the server2 program
    which is running on port 8080 by the browser. here only once or twice in 25
    times i was able to see the requests send by the browser.i tried hard and
    found that InputStream.available() method is returning 0 even though the
    request is sucessfully send to the port 8080 that is to the server2 program
    which is listening to port 8080.
    so in this process of experimenting i took Server3.java(i am sending this file
    also as an attachment) which is using multithreading. in this also i did modification
    as i did in Server2.java. the thing is here i am able to succed. here
    InputStream.available method is returning the correct number of bytes
    that are arrived on the port and are available to the InputStream.here
    when ever i made a request from the browser to Server3.java i am able to
    see the raw data send by the browser without failure.
    i could not understand why InputStream.available() is returning 0
    often(not all the time) and why it is giving the desired result when i
    used it in Server3.java ?
    i looked into the documentation and it says " InputStream.available() Returns the number of bytes that can be read (or skipped over) from this input stream without blocking
    by the next caller of a method for this input stream."
    so the thing i could not understand is what is blocking the InputStream
    in the first case.if i could undrstand the internals of how this
    method is working it will help me a lot.if i could understand this i
    will know what is the right situations to use this method.
    Thanking You.
    /*Shows how to develop a simple network server
    Author : Team -J
    Version : 1.0 */
    import java.net.*;
    import java.io.*;
    class Server2{
    static public void main(String[] args)throws Exception{
         // create a new Server Socket
         try{
              ServerSocket ss = new ServerSocket(8080,1);     
         while(true){// set queue length to 1
              // wait for the connections
              Socket s = ss.accept();
              // get the output stream associated with socket
              // to write something to the socket
              PrintStream ps =new PrintStream( s.getOutputStream());
              InputStream is = s.getInputStream();
              ps.println("I am ready to provide xxx Service");
    int len=is.available();
              if(len !=0)
              byte b [] = new byte[len];
              int k =is.read(b,0,(len-1));
              for(int i =0;i<k;i++)
                   char c = (char)b;
                   System.out.print(c);
              // close the connection
              is.close();
              s.close();
         }catch(Exception e){}
    /*Shows how to develop a simple network server
    Author : Team -J
    Version : 1.0 */
    import java.net.*;
    import java.io.*;
    class Server3{
    static public void main(String[] args)throws Exception{
         // create a new Server Socket
         try{
              ServerSocket ss = new ServerSocket(8080,1);
              while(true){
                   // wait for the connections
                   Socket s = ss.accept();
                   ServerThread st = new ServerThread(s);
                   st.start();
         }catch(Exception e){}
    class ServerThread extends Thread{
    Socket s;
         public ServerThread(Socket s){
         this.s = s;
         public void run(){
              try{
              PrintStream ps =new PrintStream( s.getOutputStream());
              InputStream is = s.getInputStream();
              int len=is.available();
              ps.println("I am ready to provide xxx Service");
              if(len!=0)
              byte b [] = new byte[len];
              int k =is.read(b,0,(len-1));
              for(int i =0;i<k;i++)
                   char c = (char)b[i];
                   System.out.print(c);
              is.close();
              s.close();
              }catch(Exception e){}

    so the thing i could not understand is what is
    t is blocking the InputStream
    in the first case.Blocking means the thread goes to sleep waiting for more data to arrive. InputStream.available() shows how many bytes have already arrived, not how many remain to be sent.

  • How to override InputStream.available()

    Hi,
    InputStream.available() always returns zero.
    now i have a requirement where I want to know total size of data in an InputStream.
    Note: I don't want to read all the data byte by byte into an byte[] etc etc.
    the reason is that data can be huge and i don't want to keep it in memory.
    Regards
    Apratim

    I'm glad you don't want to keep huge amounts of data in memory but I would consider 512Mb as huge myself.
    To override InputStream.available() all you have to do is override InputStream.available(). But if the information you want isn't available, tough.
    FileInputStream.available() returns the length of the unread portion of the file, although I don't rely on it personally. Various other implementations of available() return zero. For example, SSLSocket.getInputStream().available(), because the stream can't know without decrypting, and it mightn't have an entire cipher block to decrypt, and you wouldn't want it to block getting the rest of the cipher block so it could decrypt so it could tell you how much data was available without blocking, so what else can it do?

  • InputStream.available() doen't work always

    I have a remote HTTP resource of 11kb that I want to retrieve through InputStream obtained from HttpURLConnection (of J2SE) and HttpConnection (of J2ME).
    If I download it byte after byte with this code ("is" is InputStream instance from Http) :
    int ch;
    ByteArrayOutputStream f = new ByteArrayOutputStream();
    while ((ch = is.read()) != -1)
    f.write((byte)ch);
    it works fine on J2ME on my mobile phone (Nokia 6680), with WirelesseToolkit Emulator and also in my J2SE application.
    But if I try to fetch the resource with read(array) it works only on my Nokia 6680 and not in WIrelessToolkit Emulator and J2SE application.
    The code I used is this:
    int byteDisp = is.available();
    byte[] arraySwap = new byte[byteDisp];
    is.read(arraySwap);
    The problem is that is.available doesn't give me the actual value of bytes of my remote resource when I use the code on my desktop pc (with J2ME emulator or J2SE application). So I think that the problem is caused by Internet connection because it works fine on my mobile phone.
    Can you help me?
    I don't want to use the while with the byte read.
    Thanks you,
    ReX

    >
    Now it works fine everytime and everywhere, do you
    think that this solution could give me some
    problems?The loop means that the CPU is doing work it doesn't need to.
    You can solve this by doing something like the following pseudo code demonstrates.
        byte buffer = new byte[1];  // Note the '1'
       socket.ReadBlock(buffer) // Read only one byte and block till we get it
       AccumlateMessage(buffer)
       while(socket.available)
           buffer = new byte[socket.AvailableSize];
           socket.ReadBlock(buffer)
           AccumlateMessage(buffer)
    For the above you can choose a value besides '1' if it seems reasonable for the actual protocol that you are using and with the possible error cases taken into account.

  • InputStream available() variance in functionality

    We have a Webservice program which sends a SOAP request with OutputStream and captures the SOAP response with InputStream. We are using available() method of InputStream to fetch the input response. This method used to work correctly for the below OS and Java version
    [user2@HENDRIX ~]$ java -version
    java version "1.5.0_05"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_05-b05)
    Java HotSpot(TM) 32-Bit Server VM (build 1.5.0_05-b05, mixed mode
    We have upgraded the system to below version and the webservice program is stripping off the SOAP request to some extend and unable to fetch the full SOAP XML response
    [user1@HERMES ~]$ java -version
    java version "1.6.0_11"
    Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
    Java HotSpot(TM) 64-Bit Server VM (build 11.0-b16, mixed mode)
    But the same program without change in the code worked for earlier versions. Please let us know do we have any change in the available() method behaviour.

    Sounds like you are expecting available() to return the length of the stream. It cannot be reliably used for this process and should never have been used in the first place. [available()|http://java.sun.com/j2se/1.4.2/docs/api/java/io/InputStream.html#available%28%29] return the number of bytes that can be read without blocking and says nothing about how may bytes the stream contains.

  • InputStream available() question

    Crosspost
    Is it unusual for an input stream to say that there are X bytes available but when calling
      int foo = in.read(myArray, intstart, myArray.length);to read less than the available?
    foo = X - something?
    Thanks

    Thank you for the response. This is exactly what I'm
    seeing though. I find it puzzling.
    byte[] buffer = new byte[512];
    int MAX = in.available();  // This is returning 972
    bytes
    if(MAX > buffer.length) MAX = buffer.length;
    intTotal = in.read(buffer, 0, MAX);  // intTotal =
    155 ???Should I be looking elsewhere for the issue. The
    stream is from a data socket.can u try this
    int MIN = in.available();
    buffer = new byte[MIN];
    intTotal = in.read(buffer, 0, MIN);

  • InputStream keeps reading forever

    Hi,
    I have a 'little' problem with input stream. I have a Telnet connection established and I'm reading the input I receive. I read some input and then I send commands. I'm reading the input inside a while loop like this one:
    InputStream in = telnet.getInputStream();
    char ch = '';
    while (condition) {
        ch = (char)in.read();
    }The problem is that, when the input is over, in doesn't get out of read and it stays there forever. It doesn't event returns -1, the last char read, anything, it simply doesn't gets out of there. Is there a way to know when there's no more input to avoid this from happening? I can't use read(byte[]) because the input varies and I can't know how many data will be received. There's also no indicator of the end of data like: EOF or -1.
    I will appreciate any help.

    kazenofairy wrote:
    Nope, it's not the condition. And it's not a file what I'm reading, it's the input from a Telnet connection. My condition is:
    InputStream in = telnet.getInputStream();
    char ch = '';
    int chaux = 0;
    while (chaux != -1) {
    chaux = in.read();
    ch = (char)chaux;
    }I'm printing the values that chuax and ch are getting, but, when there's no more input, it just stops reading and the loop doesn't continues or breaks.Ah, ok, I missed that part on telnet; the stream obviously didn't hit an end of file condition then so you have to stop reading on another condition such as the end of the line or maybe
    the InputStream.available() method can be of any use. Interactive input streams can be messy.
    kind regards,
    Jos

  • InputStream hung from Runtime.getRuntime().exec

    Dear all,
    I am trying to use the following code to run a Runtime.getRuntime().exec("my_selection.exe") method and redirect all the output from the process to my JTextArea.
    My program is an executable called "my_selection.exe", which runs under DOS something like:
    My Selection Utilities:
    type the command -
    o : open an item
    l : list subitems
    q : exit
    Please select your options:But when I run my Test program, the above selection menu does not show in my JTextArea. Only after I type q (which is exit command in my_selection), will all the output shown in TextArea.
    I tested the inputstream.available(), but it always == 0.
    Anyone can help point me out what is wrong here?
    BTW, when I use the same program to run "copy a.txt a" by exec("cmd.exe"), it works ok, no matter whether it prompts for owerwrite the existing file or not.
    Many thanks!
    I tried the code,
    /* part of the code */
    public static void main(String[] args) {
         Test t = new Test();
         t.setTitle("Basic GUI");
         t.init(); // init GUI
         t.connect();
         t.show();
    private static void log(Object text) {
         getTextArea().setCaretPosition(getTextArea().getText().length());
         getTextArea().setText(getTextArea().getText() + text.toString() + "\n");
    private Thread getInputStreamListener() {
         if(listener == null) {
              Runnable runnable = new Runnable() {
                   public void run() {
                        try {
                             String text = "";
                             while (true) {
                                  while (inputStream.available()==0) {
                                       Thread.currentThread().sleep(100);
                                  byte[] bytes = new byte[inputStream.available()];
                                  inputStream.read(bytes);
                                  text = new String(bytes);
                                  log("> " + text);
                        catch(Exception e) {
                             handleException(e);
              listener = new Thread(runnable);
              listener.setName("out listener");
              listener.setPriority(2);
              listener.start();
         return listener;
    private Thread getErrorStreamListener() {
         if(listener == null) {
              Runnable runnable = new Runnable() {
                   public void run() {
                        try {
                             String text = "";
                             while (true) {
                                  while (errorStream.available()==0) {
                                       Thread.currentThread().sleep(100);
                                  byte[] bytes = new byte[errorStream.available()];
                                  errorStream.read(bytes);
                                  text = new String(bytes);
                                  log("> " + text);
                        catch(Exception e) {
                             handleException(e);
              listener = new Thread(runnable);
              listener.setName("out error listener");
              listener.setPriority(2);
              listener.start();
         return listener;
    private static void handleException(Throwable t) {
         log(t);
    private void connect() {
         try{
              process = Runtime.getRuntime().exec(new String[] {"my_selection.exe"});
              inputStream = new BufferedInputStream(process.getInputStream());
              outputStream = new BufferedOutputStream(process.getOutputStream());
              errorStream = new BufferedInputStream(process.getErrorStream());
              getInputStreamListener();
              getErrorStreamListener();
         catch(Exception e) {
              log(e);

    Note in the above code all "listener" variable in:
    private Thread getErrorStreamListener() method
    show be "listener1".
    Even I changed it, it does not work either.
    Please help.
    Thanks!

  • Available() - Don't use it!!!!!!

    I've seen a number of questions and replies recently where the InputStream.available() method, also inherited by many subclasses, is being used, or where the replies advise that it be used.
    So far, I haven't seen a single usage which is correct.
    Unless you're doing asynchronous I/O (java.nio...), it's very unlikely that this method is going to do what you want. All it tells you is how many bytes (not strings, or objects, or whatever, just bytes) can be read without the stream blocking (making the calling thread wait). It has nothing to do with the number of bytes that will ultimately be readable from the stream. It is not the size of the file.
    In short, unless you have a clear understanding of asynchronous I/O your use of this method is almost certainly going to be wrong.
    Sylvia.

    >>>
    Pretty obvious if the file is more then 2Gb.
    So if the file is more than 2 gigs than a read will
    block?
    I know I can write C code for files larger than that
    and the read will not block.
    So why does java have this limitation?I don't understand the point you're making. The
    available() method was never required to return a
    number such that an attempt to read more than that
    number would definitely block. That requirement would
    be absurd, because the read() must necessarily folllow
    the call to available() and in the mean time, more
    data may arrive, so that a read of more bytes that
    were supposedly available will still not block.
    So for a file greater than 2Gb, it would be reasonable
    for the available() method to return values lesss than
    2Gb. This would be in compliance with the
    specification.
    Nope. The docs state quite clearly that it returns the number of bytes that can be read before a block occurs.
    It doesn't say anything about returning a value less than what might be available before a block.
    And we are not discussing what is "reasonable" but rather exactly what the specification says.
    Of course if you wish to discuss what is reasonable then please provide an example of code that does not return the file size. Because I consider it reasonable (given my knowledge of how low level file systems work) that the only reasonable size to return is the size of the file.
    >>
    What about a file on a network file system?
    Irrelavent. All current file systems mount files at
    the OS level. The file size will be the same
    regardless of whether it is local or not.But the implication is that if available() returned
    the size of the file, then reads of that amount of
    data could block because the system has to wait while
    further data arrives over the network. In such
    situation, available() would not be conforming with
    its specification.And again that is not the point.
    The point is not whether blocks occur but rather whether any OS provides that information at the low level (much less high level) io calls for a file system read.
    As far as I know they do not.
    And unless a 'magic' interface has been added to java or it is replacing the OS itself then it is not going to have that information.
    >
    >>
    The documentation itself for available() in
    FileInputStream says :
    "Returns the number of bytes that can be read from
    this file input stream without blocking."
    And when the file is bigger than 2 gigs but it can
    read the file without blocking what does it return?
    It can't return 2 gigs because that is a lie.No - it's simply saying that you can read that many
    bytes without blocking.And as I already pointed out I can read more than that on any OS that I know of without blocking.
    >
    And it can't return more than that because the int is
    too small.
    And it can't return less than that because that would
    be a lie as well.
    So in the above case which of the following are you
    claiming?
    1. The documentation is wrong.
    2. Files bigger than 2 gigs are not allowed.Neither, for the reasons stated above.You are claiming that the value returned represents a blocked value. And I am specifically telling you that that does not happen at the OS level. So exactly what are you claiming is blocking?
    >
    >>
    It would be nonsense to talk about blocking if the
    only possible case for blocking was where an attempt
    was made to read more bytes than are in the file,
    because an attempt to read more bytes than that would
    still not block. It would read up to the end of file
    and return immediately.No idea what you are talking about.
    Whether I can produce an example is irrelevant. This
    is about specification, not about current
    implementations.So you claim that the documentation is now and always
    will be perfect?I claim that it is correct. And you know this because?
    I can only presume that either you have verified it in java or you have verified it with the low level io calls for a particular OS.
    Which one is it? And if the latter please provide the OS and hopefully a link so I can read about this low level io block.
    In view of this
    discussion, and other people's misunderstandings, I
    think the documentation could be improved to make it
    clear that it cannot be infered that an attempt to
    read more than available() returns will necessarily
    block. Although as I've argued, that should have been
    obvious.And as I was trying to make obvious, for the context I gave, it will not block and thus the only reasonable size that available can return, based on the documentation, is the size of the file.
    >>
    And whether you can produce an example is relevant to
    me.
    Because it is rather easy for me to produce an example
    of an InputStream that will block and thus your
    comment about InputStream.available() seems very
    relevant.
    However, I can't conceive of a situation (given the
    constraints that I suggested and that normally occur)
    where a file read will block. I know for a fact that
    OS file system implementations do not do that.
    Blockage does occur but that information is not
    available to the low level file io methods.This should be viewed as a limitation in current O/S
    implementations. There's no good reason for a system
    not to support asynchronous disk I/O, and certainly no
    such reason for a failure to support it on network
    file systems.There is a very good reason for it. The OS itself does not expect it. And given that every modern 32 bit and 64 bit system that I know of does it exactly that way I don't really expect it to change in the future.
    However, feel free though to provide a link to a research paper, or several, that demonstrate that we can expect to see this in the next wave of hard drives or file systems.

  • This is very important... It concerns topics of threads and sockets...

    Hey...
    This has been very complicating for me.
    I have tried so many solutions for the past
    few days but i have been stuck here with no
    no things to think of. I would really appreciate if someone
    can help me out in doing this or any suggestions.
    Now this is the case..
    My program runs a frame with an "OPEN" menuitem
    a connect button ,upload button, a porgress bar and a progress text label near it.... In the open u choose a file that u want to upload. In the connect u choose the IP address that u need to Upload the chosen file to. And in the upload, u start uploading u're file. Now i am using sockets to connect through my machine and the chosen IP address. The progress bar should note the process of uploading and accordingly get's updated...The progress text label should either say "No String" or "Uploading" when i'm uploading as well as blinking on and off....
    Now i got through almost all of the stuff above, i'm only stuck in updating the progress bar and the text. To make things more clearer i will include the upgrade method that i do the connection and start sending the stuff. In there i've also created a thread to update the bar but for now, i only set the value to 10.... The thing is it never updates the bar unless the whole process of downloading is done. The file chosen to be uploaded is about 1MG and it takes about 40secs to send the whole file to another machine.....
    I've also tried using seperate threads in different classes
    but it never worked..
    NOW THE PROGRESS BAR HAS BEEN DECLARED IN THE
    PROGRAM AS JProgressBar. What i'm suppose to do is
    read the file in 29 bytes. Then send 15 and then 14.
    Once i'm less than 29 bytes i send either 15 or 14 or
    the remainder... The sendMsg method is the one that
    handles sending the bytes and receiving the
    acknowledgment. The socket is created when i hit the
    connect button and choose the IP address...
    Please any extra suggestion is appreciated.
    /CODE/
    public void UpgradeActionPerformed(ActionEvent e)
    final Runnable doprogressValue = new Runnable()
    public void run()
    jProgressBar.setValue(10);
    Thread appThread = new Thread()
    public void run()
    try
    SwingUtilities.invokeAndWait(doprogressValue);
    catch (Exception ex)
    ex.printStackTrace();
    try
    DataInputStream inputStream = new DataInputStream(new FileInputStream(fileName));
    //Send Set to DownLoad Moad message
    byte[] msg = new byte[MaxMessageSize];
    msg[0]=(byte)((SystemSpecific<<4) | (DataCounter));
    msg[1]=FirmWareDNLMode;
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Set Progress Bar Max & Min values
    jProgressBar.setMinimum(0);
    jProgressBar.setMaximum(inputStream.available());
    while((inputStream.available()) >= MaxMessageRead)
    bytesRead = inputStream.read(mainBuffer,offset,MaxMessageRead);
    //Send First 15 Bytes
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Send Next 14 Bytes
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Send The 15 Bytes Left
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Send The 14 Bytes Left
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Send The Remainder Bytes
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    //Send Set to Reset Mode
    returnVal=sendMsg(msg, rcvMsg);
    if(returnVal == false)
    return;
    inputStream.close();
    socket.close();
    connectionStatus.setText("Not Connected");
    fileStatus.setText("Loading completed");
    upgradeButton.setEnabled(false);
    connectButton.setEnabled(false);
    catch(NullPointerException null_ex)
    JOptionPane.showMessageDialog(null,"Connection Not Created","Error",JOptionPane.ERROR_MESSAGE);
    catch(IOException IO_ex)
    IO_ex.printStackTrace();
    appThread.start();
    /CODE/

    Yeah... i dide finally figure out a way doing it.... This is how i did it....
    /CODE/
    // This is all going to be under the upload action...
    {//beggining of the uplaod action
    finally Runnable doProgressVal = new Runnable()
    public void run()
    time.start();//This is an instance of class timer that i
    // created. It actually sets the value of
    // of the progressBar to the latest upload
    Thread mainThread = new Thread()
    public void run()
    SwingUtilities.invokeAndWait(doprogressVal);
    do the uploading of the file to the specified server
    mainThread.start
    }//end of upload action
    /CODE/
    Hope this help if u want it for something. It works fine..

  • Email Integration Scenario - Issue with email body content

    Hi All,
    We have an Email to File Scenario. PI is connected to Outlook server using Sender Mail Channel using POP3. We are able to fetch and display emails correctly for most of the received emails.
    However we notice that for Email sent from few Mail server like Yahoo mail, Gmail, Hotmail, we are not getting the Email content correctly.
    Issue is happening with Emails sent in HTML/Rich text format (containing Formatting and without any attachments). In the receiver system we see the email is converted to Plain text format. If the same email is sent with some attachment / Embedded Image, we get all the Formatting correctly in Receiver System.
    A closer look at Pimon we found the following:
    1. When Email is sent with Formatting (without any attachment/ image) in Pimon we see that it creates 2 Payloads (screenshot attached)
    2. The First Payload - MainDocument contains the Email content in XML format, but is missing the Email formatting data in it.
    3. The other Payload - ([email protected]) contains the actual Formatted Email Content.
    Not sure why the formatting data is missing from MainDocument. Instead its coming in other payload. Due to this we are not able to display correct data at receiver end as we parse the MainDocument as our Input Payload Stream
    Note: We cannot use payload swap bean, as it will swap the data for all the incoming emails which we don't want.
    Anyone faced similar issue? Steps to get proper formatting data in MainDocument..
    Suggestions / Inputs will be highly appreciated.
    Thanks,
    Azhar

    Azhar,
    We cann't influence the behavior of Gmail, Hotmail. But have to get HTML as main payload, so we have to swap payload (not always, in some cases based on a condition). Please try below Java mapping. In Operational Mapping set "Read Attachments".
    package javaapplication1;
    import java.io.*;
    import com.sap.aii.mapping.api.*;
    import java.util.Collection;
    public class NewClass6 extends AbstractTransformation {
        @Override
        public void transform(TransformationInput transformationInput, TransformationOutput transformationOutput) throws StreamTransformationException {
            try {
                InputStream inputstream = transformationInput.getInputPayload().getInputStream();
                OutputStream outputstream = transformationOutput.getOutputPayload().getOutputStream();
                byte[] b = new byte[inputstream.available()];
                inputstream.read(b);
                //Loop over attachments and if attachment name starts with 'payload-' swap it with main payload. Edit below logic as needed.
                Collection<String> listAtt = transformationInput.getInputAttachments().getAllContentIds(true);
                for (String att : listAtt) {
                    if (att.startsWith("payload-")) {
                        b = transformationInput.getInputAttachments().getAttachment(att).getContent();
                outputstream.write(b);
            } catch (Exception exception) {
                getTrace().addDebugMessage(exception.getMessage());
                throw new StreamTransformationException(exception.toString());

  • Dynamic File and Directory Name without Mapping

    Hello Experts,
    We have following requirement:
    1) Files will be picked from R/3 AL11 directory and would be placed in corresponding folder in target system.
    2) On source side ,there would be only one folder for all types of files(around 20),but on target side,there would be one folder for each kind of file(20 folders)
    3) File name should be same on the target side but target directory should be selected based on file name.
    I have gone through a number of posts related to similar requirements and hence,sorry for a new post but I am not yet able to find a solution to this.
    I could understand,this can be achieved using DynamicConfiguration UDF .
    But I have no possibility to have mapping in my scenario.It would just be a pass through scenario.
    Can anyone please suggest a solution to this?
    Thanks.
    Regards,
    Shweta

    Hello,
    Thanks a lot for suggesting solution to this problem.
    I could achieve this using following Java mapping:
    import com.sap.aii.mapping.api.*;
    import java.io.*;
    import java.text.*;
    import java.util.*;
    public class GetDynamicConfiguration implements StreamTransformation {
        private Map param;
        public void setParameter(Map map1) {
            this.param = map1;
        public void execute(InputStream inputstream, OutputStream outputstream) throws StreamTransformationException {
            try {
                   AbstractTrace  trace = null;
                // a) Set ouput File name
                String directory=null;
                   trace = (AbstractTrace)param.get(StreamTransformationConstants.MAPPING_TRACE );
                param.put(DynamicConfigurationKey.create("http://sap.com/xi/XI/Dynamic", StreamTransformationConstants.DYNAMIC_CONFIGURATION), "");
                DynamicConfiguration conf = (DynamicConfiguration) param.get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
                DynamicConfigurationKey key = DynamicConfigurationKey.create("http://sap.com/xi/XI/System/File", "FileName");
                   DynamicConfigurationKey key1 = DynamicConfigurationKey.create("http://sap.com/xi/XI/System/File", "Directory");
                String filename =conf.get(key);
                conf.put(key, filename);
                   trace.addInfo("File name is "+filename);
                if(filename.equals("in.txt"))
                directory = "/home/ftpxi/in";
                   if(filename.equals("test.txt"))
                   directory = "/home/ftpxi/in/test";
                   if(filename.equals("shweta27.txt"))
                   directory = "/home/ftpxi/in/test";
                   trace.addInfo("Directory name is "+directory);
                   conf.put(key1, directory);
                // b) Just copy input file to output file
                byte[] b = new byte[inputstream.available()];
                inputstream.read(b);
                outputstream.write(b);
            } catch (Exception exception) {
                exception.printStackTrace();
    Thanks again.
    Regards,
    Shweta

  • Processing Schema Validation error in BPM?

    Hi all,
    We have a file to IDOC scenario where if the schema validation fails on the file adapter sender agreement, we want to pull the filename and send it in an error email. So, we are talking about the adapter specific message attribute "Filename".
    unfortunately, this does not seem to be available as a container element for alert catagories in ALRTCATDEF. So, we are starting to look into using BPM to send a email via the email adapter. However, since the validation happens prior to BPM being called I am at a bit of a loss. Any ideas on how to get the email with the filename out to the suport group would be appreciated.
    Thanks,
    Chris

    package com.validate;
    import com.sap.aii.mapping.api.*;
    import com.sap.aii.mappingtool.tf7.rt.Container;
    import java.io.*;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.*;
    public class ValidateXML extends AbstractTransformation {
        public void transform(TransformationInput transformationInput, TransformationOutput transformationOutput) throws StreamTransformationException {
            OutputStream outputstream = null;
            try {
                InputStream inputstream = transformationInput.getInputPayload().getInputStream();
                outputstream = transformationOutput.getOutputPayload().getOutputStream();
                byte[] b = new byte[inputstream.available()];
                inputstream.read(b);
                String XMLinputFileContent = new String(b);
                // define the type of schema - we use W3C:
                String schemaLang = "http://www.w3.org/2001/XMLSchema";
                // get validation driver:
                SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
                //Place XSD file in PI server same as http://help.sap.com/saphelp_nwpi711/helpdata/en/44/0bf1b3ec732d2fe10000000a11466f/frameset.htm
                //OR I think you can place any where on server.
                File XSDfile = new File("C:/xi/runtime_server/validation/schema/SchemaFile.xsd");
                // create schema by reading it from an XSD file:
                Schema schema = factory.newSchema(new StreamSource(XSDfile));
                Validator validator = schema.newValidator();
                // at last perform validation:
                validator.validate(new StreamSource(XMLinputFileContent));
                //If XML it not valid, exception will be thrown, if it is valid sent this PassOutputXML to output
                String PassOutputXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ns:MT_OutputXML xmlns:ns=\"http://sap.com/xi\"> <Name>FileName.txt</Name><Validation>Pass</Validation> </ns:MT_OutputXML>";
                outputstream.write(PassOutputXML.getBytes());
            } catch (Exception exception) {
                //Get File name using http://help.sap.com/saphelp_nwpi711/helpdata/en/43/03612cdecc6e76e10000000a422035/frameset.htm
                Container container = null;
                DynamicConfiguration conf = (DynamicConfiguration) container.getTransformationParameters().get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
                DynamicConfigurationKey key = DynamicConfigurationKey.create("http://sap.com/xi/XI/System/File", "FileName");
                String inputFileName = conf.get(key);
                String FailOutputXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ns:MT_OutputXML xmlns:ns=\"http://sap.com/xi\"> <Name>" + inputFileName + "</Name><Validation>Fail</Validation> </ns:MT_OutputXML>";
                try {
                    outputstream.write(FailOutputXML.getBytes());
                } catch (IOException ex) {
                    exception.printStackTrace();
                    ex.printStackTrace();

  • File adapter - How to pass File name and path at runtime

    Hi gurus,
    We want to use PI 7.0 as an ftp server and expose the config as a webservice where the service consumer can pass one or more file names and the path to pick them and drop them on a fixed ftp server.
    So precisely, I need to be able to set the file name, target directory parameters in both sender and receiver file/ftp adapters at runtime. is this possible at all ?
    I am aware of passing Adapter specific parameters from sender file adapter to receiver file adapter to create the same folder structure and file names. But my requirement is different. I hope I am clear.
    Could I please get some advise on this .
    Thanks & Kind Regards,
    Jhansi.

    Hi Jhansi,
    Either you can go ahead with dynamic configuration as said by other SDN'ers. Else can go with Java Mapping:
    Here is the code for Java Mapping:
    import com.sap.aii.mapping.api.*;
    import java.io.*;
    import java.text.*;
    import java.util.*;
    public class GetDynamicConfiguration implements StreamTransformation {
    private Map param;
    public void setParameter(Map map1) {
    this.param = map1;
    public void execute(InputStream inputstream, OutputStream outputstream) throws StreamTransformationException {
    try {
    AbstractTrace trace = null;
    // a) Set ouput File name
    String directory=null;
    trace = (AbstractTrace)param.get(StreamTransformationConstants.MAPPING_TRACE );
    param.put(DynamicConfigurationKey.create("http://sap.com/xi/XI/Dynamic", StreamTransformationConstants.DYNAMIC_CONFIGURATION), "");
    DynamicConfiguration conf = (DynamicConfiguration) param.get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
    DynamicConfigurationKey key = DynamicConfigurationKey.create("http://sap.com/xi/XI/System/File", "FileName");
    DynamicConfigurationKey key1 = DynamicConfigurationKey.create("http://sap.com/xi/XI/System/File", "Directory");
    String filename =conf.get(key);
    conf.put(key, filename);
    trace.addInfo("File name is "+filename);
    if(filename.equals("in.txt"))
    directory = "/home/ftpxi/in";
    if(filename.equals("test.txt"))
    directory = "/home/ftpxi/in/test";
    if(filename.equals("shweta27.txt"))
    directory = "/home/ftpxi/in/test";
    trace.addInfo("Directory name is "+directory);
    conf.put(key1, directory);
    // b) Just copy input file to output file
    byte[] b = new bytehttp://inputstream.available();
    inputstream.read(b);
    outputstream.write(b);
    } catch (Exception exception) {
    exception.printStackTrace();

  • Problem in reading input form files while parsing them in javacc

    I need to parse a language called DISP (delay insensitive sequential processes) using javacc. I need help with reading the input which we parse, eg for a matched brace example i dont want to just check if all the braces are matched, i also want to do something everytime i read a brace.
    Is declaring tokens and using token.image the only way?
    and can anyone explain what "parser object" "token manager" etc are and how the whole thing works, in simple words. The documents have details but i keep getting getting lost in them

    import java.io.*;
    import java.util.*;
    import javax.comm.*;
    public class SimpleRead implements Runnable, SerialPortEventListener {
    static CommPortIdentifier portId;
    static Enumeration portList;
    InputStream inputStream;
    SerialPort serialPort;
    Thread readThread;
    public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
    portId = (CommPortIdentifier) portList.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    if (portId.getName().equals("COM1")) {
    //if (portId.getName().equals("/dev/term/a")) {
    SimpleRead reader = new SimpleRead();
    public SimpleRead() {
    try {
    serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
    } catch (PortInUseException e) {}
    try {
    inputStream = serialPort.getInputStream();
    } catch (IOException e) {}
         try {
    serialPort.addEventListener(this);
         } catch (TooManyListenersException e) {}
    serialPort.notifyOnDataAvailable(true);
    try {
    serialPort.setSerialPortParams(9600,
    SerialPort.DATABITS_8,
    SerialPort.STOPBITS_1,
    SerialPort.PARITY_NONE);
    } catch (UnsupportedCommOperationException e) {}
    readThread = new Thread(this);
    readThread.start();
    public void run() {
    try {
    Thread.sleep(20000);
    } catch (InterruptedException e) {}
    public void serialEvent(SerialPortEvent event) {
    switch(event.getEventType()) {
    case SerialPortEvent.BI:
    case SerialPortEvent.OE:
    case SerialPortEvent.FE:
    case SerialPortEvent.PE:
    case SerialPortEvent.CD:
    case SerialPortEvent.CTS:
    case SerialPortEvent.DSR:
    case SerialPortEvent.RI:
    case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    break;
    case SerialPortEvent.DATA_AVAILABLE:
    byte[] readBuffer = new byte[20];
    try {
    while (inputStream.available() > 0) {
    int numBytes = inputStream.read(readBuffer);
    System.out.print(new String(readBuffer));
    } catch (IOException e) {}
    break;
    }

Maybe you are looking for

  • BusinessObjects Portal Integration - iView Template Missing

    Hello I have installed my BusinessObjects for Portal as follows: 1. We already have BI 7.0 on SQL 2005 on BIDEMOSER SERVER. 2. Installed BusinessObjects Enterprise 3.1 , Crystal Reports 2008, SAP GUI 7.1 and SAP Integration Kit on this new server nam

  • Cannot properly install windows 7 on OSX Lion

    i went through the whole process of making sure i have a working windows 7 disk, went through bootcamp. restarted my early 2011 mbp w/ osx lion. it goes tot he black screen with flashing cursor for a few seconds, then goes to the "Press any key to in

  • Allowing Spanish characters in PDF forms

    I'd like to develop a PDF form primarily for Spanish speaking users. Is it possible to allow Spanish characters in a PDF form? I know setting the "default locale" in LC has nothing to do with this, so is it a matter of system settings (ie. keyboard s

  • COM port from VISA alias

    I have a test fixture I am designing in LabVIEW that is composed of many independent instruments. For simplicity sake I gave all of these instruments a VISA alias (for instance Programmer rather than COM3) so I wouldn't have to guess at which COM por

  • Java heap space problem in SUN identity management

    Hi All, i am new to sun idm, i have installed netbeans 6.0.1 with tomcat 6.0.14 and then i have installed sun idm inside the web container(webapps/idm). When i stared my webserver manually using startup.batch file then I can easily go to inside admin