How to feed CharsetDecoder (nio Buffer problems)

Hi there,
I have no idea how to feed bytes into a CharsetDecoder in presence of multibyte sequences. I am trying something along the following lines.
If a multibyte char is being fed (I tried c3 +a4 = �), the first call to decode returns UNDERFLOW with bout.hasRemaining() == false as expected, but the 2nd call yields MALFORMED[1], no matter what rewind/flip method I throw in at // *1*
I probably "misgrok" something here with Buffers. Can someone point out what?
  ByteBuffer bin = ByteBuffer.allocate(3);
  CharBuffer bout = CharBuffer.allocate(1);
  Charset cs = Charset.forName("UTF-8");
  CharsetDecoder dec = cs.newDecoder();
  public void addChar( int ch ) throws Exception {
    bin.put((byte)ch);
    bin.flip();
    CoderResult res = dec.decode(bin,bout,false);
    bout.flip();
    if( bout.hasRemaining() ) {
      emit( bout.get() );
      bin.clear();
      bout.clear();
    } else {
      bout.flip();
      //bin.flip(); // *1*
  }

But the result character is already in the output buffer?! Applying my program code to ISO-8859-1, all character yield underflows and the data is successfully being converted.
Here is a complete test program:
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
public class DecoderTest {
  public static void main( String[] args ) throws Exception {
    dec = Charset.forName(args[1]).newDecoder();
    new DecoderTest().run(args[0]);
  ByteBuffer bin = ByteBuffer.allocate(3);
  CharBuffer bout = CharBuffer.allocate(1);
  static CharsetDecoder dec;
  public void run( String filename ) throws Exception {
    FileInputStream in = new FileInputStream(filename);
    int ch;
    while( (ch=in.read())>=0 ) {
      addChar(ch);
  public void addChar( int ch ) throws Exception {
    System.out.print( "byte "+(0xff & ch) + " => " );
    bin.put((byte)ch);
    bin.flip();
    CoderResult res = dec.decode(bin,bout,false);
    System.out.print( res + " => " );
    if( res.isError() ) {
      bin.clear();
      bout.clear();
    } else {
      bout.flip();
      if( bout.hasRemaining() ) {
        System.err.print( "char " + ((int)bout.get()) );
        bin.clear();
        bout.clear();
      } else {
        bout.flip();
       // what to do with bin here???
    System.err.println();
}Passing in iso latin code lopoks like this:
byte 98 => UNDERFLOW => char 98
byte 228 => UNDERFLOW => char 228
byte 104 => UNDERFLOW => char 104
byte 32 => UNDERFLOW => char 32
byte 98 => UNDERFLOW => char 98
byte 228 => UNDERFLOW => char 228
byte 104 => UNDERFLOW => char 104
byte 10 => UNDERFLOW => char 10Utf-code looks like this:
byte 98 => UNDERFLOW => char 98
byte 195 => UNDERFLOW =>
byte 164 => MALFORMED[1] =>
byte 104 => UNDERFLOW => char 104
byte 32 => UNDERFLOW => char 32
byte 98 => UNDERFLOW => char 98
byte 195 => UNDERFLOW =>
byte 164 => MALFORMED[1] =>
byte 104 => UNDERFLOW => char 104
byte 10 => UNDERFLOW => char 10Message was edited by:
HolgerK

Similar Messages

  • NIO - Selector problem - when using more than one in same application

    Hi,
    I'm developing a multiplayer-server, which shall be able to handle at least 2000 concurrent clients. To avoid the use of 4000 threads for 2000 clients (a thread for each stream), I would like to use NIO.
    Problem:
    The server has of course a ServerSocketChannel registered with a Selector, and when clients connects, the SocketChannel's is received. IF these channels is registered (OP_READ) with the same Selector-instance as the ServerSocketChannel, there is no problem and the Selector recognizes when a registered SocketChannel is ready for OP_READ - BUT when the received SocketChannels is registered with another Selector-instance than the one the ServerSocketChannel is registered with, the Selector NEVER recognizes, when a SocketChannel is ready for OP_READ - why not and how do I solve the problem? Only one thread can service the same Selector-instance, and when both receiving many connections and read/write, this could easily be a bottleneck
    Following is the used code; 2 classes: ClientListener (has a ServerSocketChannel registered with a Selector) and ClientHandler (has another Selector where the SocketChannels is registered and a thread-pool that services all the SocketChannels, when they are ready for read/write):
    public class ClientListener {
      private static final int BACKLOG = 32;
      private int port;
      private Thread internalThread;
      private volatile boolean noStopRequested;
      private ServerSocketChannel ssc;
      private static Selector selector;
      private ClientHandler clientHandler;
      public ClientListener(ClientHandler clientHandler, String bindAddress, int port) throws InternalErrorException {
        this.clientClass = clientClass;
        this.clientHandler = clientHandler;
        this.noStopRequested = true;
        this.port = port;
        try {
          InetAddress inetAddress;
          if (bindAddress.equals(""))
            inetAddress = InetAddress.getLocalHost();
          else
            inetAddress = InetAddress.getByName(bindAddress);
          ssc = ServerSocketChannel.open();
          ssc.socket().bind(new InetSocketAddress(inetAddress, port), BACKLOG);
          ssc.configureBlocking(false);
          Runnable r = new Runnable() {
            public void run() {
              try {
                start();
              } catch (Exception e) {
                Log.echoError("ClientListener: Unexpected error: "+e.getMessage());
          internalThread = new Thread(r, "ClientHandler");
          internalThread.start();
        } catch (Exception e) {
          throw new InternalErrorException(e.getMessage());
      public static Selector selector() {
        return selector;
      private void start() {
        Log.echoSystem("ClientListener: Listening started at port "+port);
        try {
          selector = Selector.open();
          SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);
          int keysAdded;
          while (noStopRequested) {
            SelectionKey key = null;
            keysAdded = selector.select(10000);
            if (keysAdded == 0)
              continue;
            Set readyKeys = selector.selectedKeys();
            Iterator i = readyKeys.iterator();
            while (i.hasNext()) {
              try {
                key = (SelectionKey)i.next();
                i.remove();
                if (key.isAcceptable()) {
                  ServerSocketChannel nextReady = (ServerSocketChannel)key.channel();
                  SocketChannel sc = nextReady.accept();
                  try {
                    clientHandler.registerClient(sc);
                  } catch (Exception e) { e.printStackTrace(); }
              } catch (CancelledKeyException cke) {
                System.out.println("ClientListener: CancelledKeyException");
        } catch (Exception e) {
          e.printStackTrace();
          try {
            ssc.close();
          } catch (IOException ioe) {/* Ignore */}
        Log.echoSystem("ClientListener: stopped");
      public void stop() {
    public class ClientHandler {
      private static final int INITIAL_WORKER_COUNT = 5;
      private int port;
      private Thread internalThread;
      private volatile boolean noStopRequested;
      private static Selector selector;
      private Manager manager;
      private WorkerPool pool;
      private ClientListener clientListener;
      public ClientHandler(Manager manager, String bindAddress, int port) throws InternalErrorException {
        this.manager = manager;
        this.noStopRequested = true;
        this.port = port;
        clientListener = new ClientListener(this, bindAddress, port);
        // initiating load-balanced worker-pool
        pool = new WorkerPool(INITIAL_WORKER_COUNT, (int)(manager.getMaxClients() * ClientWorker.CLIENT_FACTOR), 0.75f);
        for (int i=0; i < pool.getMinCount(); i++) {
          pool.addWorker(new ClientWorker(pool, manager));
        Runnable r = new Runnable() {
          public void run() {
            try {
              start();
            } catch (Exception e) {
              Log.echoError("ClientHandler: Unexpected error: "+e.getMessage());
        internalThread = new Thread(r, "ClientHandler");
        internalThread.start();
      public static Selector selector() {
        return selector;
      private void start() {
        Log.echoSystem("ClientHandler: Started");
        try {
          selector = Selector.open();
          int keysAdded;
          while (noStopRequested) {
            SelectionKey key = null;
            try {
              keysAdded = selector.select();
              Log.echoDebug("ClientHandler: out of select()");
              if (keysAdded == 0)
                continue;
              Set readyKeys = selector.selectedKeys();
              Iterator i = readyKeys.iterator();
              while (i.hasNext()) {
                try {
                  key = (SelectionKey)i.next();
                  i.remove();
                  if (key.isReadable()) {
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
                    ClientWorker worker = (ClientWorker)pool.getWorker();
                    worker.process(key);
                  } else if (key.isWritable()) {
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
                    ClientWorker worker = (ClientWorker)pool.getWorker();
                    worker.process(key);
                  } else {
                } catch (CancelledKeyException cke) {
                  Client client = (Client)key.attachment();
                  if (client != null) {
                    client.disconnect();
                    key.selector().wakeup();
            } catch (CancelledKeyException cke) {
              if (key != null) {
                Client client = (Client)key.attachment();
                if (client != null) {
                  client.disconnect();
                  key.selector().wakeup();
        } catch (Exception e) {
          e.printStackTrace();
        Log.echoSystem("ClientHandler: stopped");
      public void registerClient(SocketChannel sc) throws Exception {
        sc.configureBlocking(false);
        Client client = new Client(...);
        SelectionKey key = sc.register(selector, SelectionKey.OP_READ, client);
        key.selector().wakeup();
      public void stop() {
    }

    Ok, found the solution here: http://forum.java.sun.com/thread.jsp?forum=31&thread=282069
    "The select() method holds a lock on the selector that
    the register() method wants to acquire. The register()
    method cannot continue until the lock is relased and
    the select() method will not release it until some key
    is triggered. If this is the first key you're adding
    then select has nothing that will wake it up, ever.
    The result is, obviously, a deadlock.
    The solution is to have a queue of pending connections.
    You put your new connection in that queue. Then you
    wake up the selector and let that thread go through
    the queue, registering connections."

  • Re-executing a function in IP web: buffer problem

    Hello everybody,
    we have performed 2 changes to our application:
    1. for performance reasons we replaced a FOX function with an IP exit function and
    2. to limit the number of entires appearing in F4 (000's) in the web application when selecting mater data for filtering we inserted a new InfoObject for the selection with only a few (about 10) master data entries and then passed the variable values to the original infoobject
    Both changes work well but there is a nasty side effect.
    The INITIAL execution of the query (variable pop-up) and filtering in the web application works fine. The user enters data manually and executes a function performing some caluculations (was FOX, is now an IP exit function).
    After this initial execution of the function it is not possible to re-execute the function. If e.g. the user performs a few more manual changes and then tries to execute the function again nothing happens. Only be logging off and on again (i.e. a new session) the user can execute the function again.
    Cache mode for the query (in RSRT) is set to 0 (=inactive).
    It is obviously a  buffer problem (some sort of delta/plan buffer conflict) and I have had this before but I cannot recall how to solve it ... its the age!
    Grateful for any assistance
    Edited by: Martin Helmstein on Nov 10, 2010 11:07 AM
    Clarification: if the user repeats inputting data under the INITIAL filter selection state and executes the function again it works. The problem only occurs if the user changes the filters (drop down boxes in the web application), inputs data and attempts to execute the function with this new selection.

    Hi Martin,
    One easy way of solving is to include the WAD command TRANSFER_STATE at the end of all the Planning function / Sequence commands attached to the Button.
    This will refresh the WAD layout without having to reenter the variable values if any.
    The other Option is to reset all the variables associated with the execution of Planning function after every execution.
    This can be included under Web template Properties so this happens after every refresh of the layout.
    Hope this helps.
    Regards.
    Shafi.

  • GetBytes:range buffer problem

    Hi to all...here comes another problem.
    Then...i read the data ready in the socket, with [socket readData], ad store the data in a NSData object called header. Then, i need to controll the first two byte of my 'header' object and then compare them with a unsigned short number (something like 0x...) ...i suppose i need to use the method getBytes:range (i use range because after that, i will read the second four bytes, and then the third two bytes)...but now: the sintax is (void)getBytes:(void *) buffer range:(NSRange) range:
    buffer is the buffer into which to copy data... but, how do i initialize this buffer? How if i have to compare the content of the buffer with an unsigned short?
    Thank you!

    unsigned short magicNumber = 0xFFFF; // Or whatever your number is/should be.
    unsigned short buffer;
    [data getBytes: & buffer range: NSMakeRange(0, 2)];
    Now, before you can compare, you need to decide on a very important plot point. What is the endian format of the number in the stream? What is the endian format of the machine you are on? You will probably have to use one of the htons functions.

  • How do I fix a initializing problem with my macbook pro? I only get to the blank screen with the apple logo and the "processing something"sign... it just doesn't start the system....

    How do I fix a initializing problem with my macbook pro? I only get to the blank screen with the apple logo and the "processing something" sign... it just doesn't start the system....
    Please help
    Marcelo

    If there is no loading bar, it's usually a problem with a third party kext file in OS X itself.
    You can press the power button down to force a hardware shutdown, then reboot holding the shift key down on a wired or built in keyboard, this will disable them and you go around and update your third party software.
    Gray, Blue or White screen at boot, w/spinner/progress bar
    Also take this time to backup your users files off the machine if possible.
    Most commonly used backup methods
    Sometime that won't work and you need to do more
    ..Step by Step to fix your Mac

  • I am having a issue installing Adobe Acrobat XI.  I am running Windows 8.1. When  go to install it gets an error.  The error is with transform in registry and will not install product. I am looking at how I can fix this registry problem.

    I am having a issue installing Adobe Acrobat XI.  I am running Windows 8.1. When  go to install it gets an error.  The error is with transform in registry and will not install product. I am looking at how I can fix this registry problem.
    I have tried to uninstall all Abode Acrobat installations but one file remains and refuses to be uninstalled. It gives me this error : Error applying Transforms . Verify that specified paths are valid. It was installed on Sept 18 2014.  I have downloaded a Transform update but it tells I do not have a Adobe Acrobat product installed. 

    Hi all,
    Sylonious, did you manage to sort this problem out? I have been experiencing similar problems. I think my problem was because I had many different versions of JDKs. I have done a complete re-install. I would be really grateful to you (and anyone else) for help with this problem.
    I have re-installed JSDK1.4.2_03, set the "path" variable to "C:\JSDK1.4.2_03".
    When I compile using "javac" I get an error saying "javac" is not recognised.
    When I compile using "C:\j2sdk1.4.2_03\bin\javac Freq.java" no error is thrown.
    Every time I try to run a java file, I always get the NoClassDefFound error. When run with the -verbose option, files are loaded from C:\Program Files\Java\j2re1.4.2_03\bin - is this correct?
    I have removed all previous references to java in the registry editor.
    Please help !
    Regards,
    Vipul

  • HT5429 How long after you report a problem does it take for the fix to be picked up in maps?

    How long after you report a problem does it take for the fix to be picked up in maps? The street I live on is misspelled. It's shown as one word, but it should be two words. Maps cannot find the address when it is spelled correctly, so I have it purposely misspelled it as one word in my contacts, which helps for the most part, however it still tries to place my home on an entirely different street all together. Fortunately this new random street is at least close to where I live. When I used to spell my street correctly with two words, maps would try to send me to the next town over. So it kind of works, as long as I misspell my street, and ignore the fact that it is showing where I live to be a couple of streets down from where I actually live. I live in Connecticut - not in the most populated of areas, but not in the middle of nowhere either. Amazingly enough Google Maps will correctly find my address whether it's spelled with one words or two words. Google Maps also shows my apartment complex, which Apple Maps does not. I really wish Apple would just do a quick pass of the area to fix these issues. I’ve reported the problem several times, months ago. How long will it take for there to be a fix? I keep trying to use the Apple ecosystem, but Google is clearly the better solution for me.

    Apple does not do the GIS data for maps. That comes from 3rd party vendors like Tom Tom. I have read it takes some time to update map data. The only thing you can do is report it.
    Not to belittle your complaint, but on my end it is Apple that is clearly better. When looking at my house in Google, the satellite photo is more than 4 years old, and the Apple one is much newer. I can tell because of the condition of my home and the neighbor's. They had an above ground pool which was removed 4 years ago and it shows on the Google Map. I had remodeling and roof work done to my home that started 3 years ago and Apple's satellite view showed this work done, which took over a year to complete. I live in the middle of a block in a rural town. Both Apple and Google split the block into 100 parts and put my home close to the beginning of the block instead of where it actually sits. I've reported it to both Google and Apple and no one has changed. Just one of those things. But, keep your chin up, it will get corrected eventually.

  • How to feed data to generate a html file using XSLT?

    I need to implement email content generation in the hmtl format using XSLT. The document information is stored in a xsl file and the data is generated dynmically in the application. How to feed the data to have the file?
    Thanks,
    v.

    Thanks for your information. I, however, already thought about using string stream instand of a XML file to pass in data. I am looking for a more intelligent method. It doesn't seem to have one so far.

  • It says that "there was a problem connecting to the server". What's wrong with this, and how can I deal with this problem?

    I just got my new iPad Mini2, and when I choose "sign in with your apple ID", it says that "there was a problem connecting to the server". What's wrong with this, and how can I deal with this problem?

    1. Turn router off for 30 seconds and on again
    2. Settings>General>Reset>Reset Network Settings

  • I transferred my iTunes library from Window PC to MacBook pro and now I cant play songs that I purchased with an earlier ID and Password.  How can I get around this problem?'t

    I transferred my iTunes library from Window PC to MacBook pro and now I cant play songs that I purchased with an earlier ID and Password.  How can I get around this problem?

    Authorize the computer.
    iTunes Store: About authorization and deauthorization - http://support.apple.com/kb/HT1420 - and another helpful post: https://discussions.apple.com/message/17828050

  • I need to align the margins of my forms with those of my website, I have looked at all the options and unfortunately I am unable to do it with access to the Adobe.form.min.CSS file which I can't access as a consumer, how else can I fix my problem

    I need to align the margins of my forms with those of my website, I have looked at all the options and unfortunately I am unable to do it with access to the Adobe.form.min.CSS file which I can't access as a consumer, how else can I fix my problem

    I need to align the margins of my forms with those of my website, I have looked at all the options and unfortunately I am unable to do it with access to the Adobe.form.min.CSS file which I can't access as a consumer, how else can I fix my problem

  • HT4060 iPad will not charge if hooked by USB to pc or plugged into wall.  How do I know if the problem is with iPad, cable or power adapter.  I have a 12, 10 and 5W adapters no success with any.  Only one lightening cable so can't swap cables.

    iPad will not charge if hooked by USB to pc or plugged into wall.  How do I know if the problem is with iPad, cable or power adapter.  I have a 12, 10 and 5W adapters no success with any.  Only one lightening cable so can't swap cables.

    I'm sorry but this is too funny to pass up. 

  • I got a crash report that said the Flash plug in had crashed, but when the incident actually happened, the report said that "Silverlight" had crashed; how do I know where the problem is?

    Sorry. The crash report actually said that Quick Time had crashed, not Flash, but at the time the crash actually happened, the message said that "Silverlight" had crashed. I just want to know how I can tell where the problem is so that I can try to fix it.

    That is a legitimate Mozilla newsletter. As it says in the email:
    You're receiving this email because you subscribed to receive email newsletters and information from Mozilla. If you do not wish to receive these newsletters, please click the Unsubscribe link below.
    Unsubscribe https://www.mozilla.org/en-US/newsletter/existing/ad9febcf-65ac-41fd-810b-798945f448f3/
    Modify your preferences https://www.mozilla.org/en-US/newsletter/existing/ad9febcf-65ac-41fd-810b-798945f448f3/ "

  • Mac shut down due to problem; I rebooted fine. how do I determine what the problem was?

    mac shut down due to problem; I rebooted fine. how do I determine what the problem was?

    When shut down and rebooted, the Mac OS X does background maintenance on the system. That can solve minor issues.
    Beyond this, it is a good idea to run Disk Repair yourself just to make sure.
    Reboot with the option key held down. On the screen that comes up select the Recovery disk icon and Continue.
    On the next screen Clcik Disk Utility and Continue.
    In DU, in the list on the left select the drive to be repaired - click the item that is indented to the right, not an an item whose name starts on the far left.
    Click First Aid, then Repair Disk.
    After that is done, quit DU and restart as usual.

  • Ever since I was with my iPad in France, it goes to the French app store instead of to the Netherlands' one. As a consequence, I am unable to download any app. How to get rid of this problem? Iregularly travel from the Netherlands to France.

    Ever since I was with my iPad in France, it goes to the French app store instead of to the Netherlands' one. As a consequence, I am unable to download any app. Not in France, because my bank account number is Dutch (it says), not in the Nteherlands because I should buy in the Dutch app stoe.
    How to get rid of this problem? I regularly travel from the Netherlands to France.
    Thanks in advvance,
    Hans

    You can find out how to get service for your iPad on this web page:
    http://support.apple.com/kb/index?page=servicefaq&geo=Philippines&product=ipad
    Regards.

Maybe you are looking for

  • Querying LOV ....

    Hi, I am working on some screen in which there is Item Lov.Fot this I created VO and AM.Problem is in LovVO my query is like this: Select * from xxxxxxx where vendor_id=yy. So where do i need to mention where clause? I tried creating Controller on LO

  • How to match LR/ACR4.1 to Microsoft raw viewer

    I have been going through the forum and I've found threads explaining the difference that exists between the camera presets and the raw files, and that a raw file must be rendered regardless of that camera preset. I understand that. But what does the

  • Why won't time machine give me access to backups?

    My Macbook Pro wasn't working so I took it to an Apple store and they said the file system was corrupted and it needed be reformatted.  I had a time machine backup and they said I should restore the files from it but not the complete restore or I wou

  • Air-AP1242AG Versus Air-APLAP1242AG

    Hi All, We just got (2) Air-lap1242ag-a-k9 units here and i am also working on (2) air-ap1242ag-a-k9 units also. my question is this, do the lap units function the same as the air-ap1242ag units? if not, what will it take to make the lap units functi

  • Can I set up a password protected webpage within my site? CS4

    Can I set up a password protected webpage within my site? I'm using CS4 and would like to create an orphaned page for internal use only.  Is there any way you can set up a password protect on one page within an otherwise public website? Any help woul