Buffer.position throws IllegalArgumentException

Hi i tried the following code on linux using jdk1.4.2_05. on windows the
same code same jdk and successfully done. Only linux throws me a illegalArgumentException.
Anyone experience the same as i do.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.text.*;
import java.util.*;
public class Process{
     private static MappedByteBuffer mbb;
     private static LinkedList table;
     private static FileChannel fc;
     private String gl_record;
     private String gl_pathname;
     public Process(String pathname){
          gl_pathname = pathname;
          if(table == null){
               gl_record = "";
               if(initTable() != 0)
                    return ;
     public long enqueue(String record) {
          record = " " + record;
          if(!record.endsWith("\n"))
               record += "\n";
          try{
               ByteBuffer bb = ByteBuffer.wrap(record.getBytes());
               long pos = -1;
               RandomAccessFile raf = new RandomAccessFile(gl_pathname, "rws");
               FileChannel fc = raf.getChannel();
               pos = fc.size();
               fc.write(bb, pos);
               table.add(new Long(pos));
               createBuffer(gl_pathname);
               fc.close();
               return pos;
          }catch(IOException e){
               e.printStackTrace();
               return -1;
     public long dequeue(String record){
          if(table.size() > 0){
               Long obj = (Long)table.removeFirst();
               int pos = obj.intValue();
               try{                                      //<---------------------Error Occurs Here
                    mbb.position(pos);
               }catch(IllegalArgumentException e){
                    e.printStackTrace();
                    return -100;
               char c;
               String s = "";
               while(mbb.hasRemaining()){
                    c = (char)mbb.get();
                    s += c;
                    if(c == '\n'){
                         if(s.startsWith(" ")){
                              gl_record = s;
                              return pos;
                    s = "";
          return -1;
     public int comment_record(long record_pos) {
               ByteBuffer bb = ByteBuffer.wrap("#".getBytes());
               int position = mbb.position();
               mbb.position((int)record_pos);
               mbb.put(bb);
               mbb.force();
               mbb.position(position);
          return 0;
     private int initTable(){
          int result = createBuffer(gl_pathname);
          if(result != 0){
               return -1;
          table = new LinkedList();
          String line = "";
          while(mbb.hasRemaining()){
               char c = (char)mbb.get();
               line += c;
               if(c == '\n'){
                    char readAvailable = line.charAt(0);
                    if(" ".equals(String.valueOf(readAvailable))){
                         table.add(new Long(mbb.position() - line.length()));
                    line = "";
          return 0;
     private int createBuffer(String pathname){
          try{
               RandomAccessFile raf = new RandomAccessFile(pathname, "rws");
               FileChannel fc = raf.getChannel();
               mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size());
               fc.close();
          }catch(IOException e){
               return -1;
          return 0;
      public static void main(String[] args){
          Process proc = new Process("testing");
          for(int i = 0; i < 10000; i++){
               long res = proc.dequeue("");
               proc.enqueue("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA                   aaaaaaaaa");
               if(res >= 0){
                    proc.comment_record(res);
               }else if(res < -1)
                    break;
}

The
[url=http://java.sun.com/javase/6/docs/api/java/nio/Bu
ffer.html#position(int)]position method takesan int, but you're feeding it a long.
It's an int but may be negative?
OP's code:
Long obj = (Long)table.removeFirst();
               int pos = obj.intValue();
               try{                                      //<---------------------Error Occurs Here
                    mbb.position(pos);

Similar Messages

  • Throws IllegalArgumentException when use BufferedReader.readLine()

    hi
    when i use BufferedReader.readLine() to read a html file of Internet,it throws IllegalArgumentException like blow:
    java.lang.IllegalArgumentException
    at java.nio.Buffer.position(Buffer.java:218)
    at java.nio.charset.CharsetDecoder.decode(CharsetDecoder.java:575)
    at sun.nio.cs.StreamDecoder$CharsetSD.implRead(StreamDecoder.java:442)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:182)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    but it occured sometimes or occured never in a long time!
    Why?

    It does it because of this bit of code in java.nio.Buffer.position
    if ((newPosition < 0) || (newPosition > limit))
          throw new IllegalArgumentException ();So for some reason a bit of the java code has tried to set the position to either less than zero or greater than the limit of the buffer. Not a good idea in either case.
    Since this is not your code you can't really do much about it. Try catching the exception and handling it.

  • No need to add 'throws' when throwing IllegalArgumentException ?

    Why is it necessary to add throws/try catch when throwing Exception but not when throwing IllegalArgumentException :
      public void test(String a, String b)  {
        if(a.equals.b) {
              // Do stuff
        } else {
          throw new IllegalArgumentException("bla"); // Ok!
          // throw new Exception("bla");       NO GO!
      }

    Also, it is usually less than helpful to throw Exception. Try to find the correct subclass exception to provide better info the the poor schmuck who has to handle your exception. Write your own ... it is very easy.
    ¦ {Þ                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • JavaCard .cap file generation throws IllegalArgumentException

    Hi all,
    I'm trying to generate a .cap file for some applet source provided externally, and capgen/converter are throwing an IllegalArgumentException when I attempt to generate a .cap (either straight from .opt or using capgen on a pre-generated .jca file). I'm able to generate/run the .cap file from JCOP tools for eclipse, so I'm able to verify it's authenticity.
    The output I'm getting is pretty basic even in verbose mode:
    C:\projects\MWallet\src>converter -config .\com\schip_select\schip.opt
    Java Card 2.2.1 Class File Converter, Version 1.3
    Copyright 2003 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms.
    parsing C:\projects\MWallet\src\com\mycard\schip_select\Constants.class
    parsing C:\projects\MWallet\src\com\mycard\schip_select\schip.class
    parsing C:\projects\MWallet\src\com\mycard\schip_select\schip_pin.class
    parsing C:\projects\MWallet\src\com\mycard\schip_select\protected_array.class
    converting com.mycard.schip_select.Constants
    converting com.mycard.schip_select.schip
    parsing C:\JavaCardDevelopment\api_export_files\javacard\framework\javacard\framework.exp
    parsing C:\JavaCardDevelopment\api_export_files\java\lang\javacard\lang.exp
    parsing C:\gp211\org\globalplatform\javacard\globalplatform.exp
    parsing C:\JavaCardDevelopment\api_export_files\javacard\security\javacard\security.exp
    converting com.mycard.schip_select.schip_pin
    converting com.mycard.schip_select.protected_array
    parsing C:\JavaCardDevelopment\api_export_files\javacardx\crypto\javacard\crypto.exp
    writing C:\projects\MWallet\src\com\mycard\schip_select\javacard\schip_select.jca
    java.lang.IllegalArgumentException
    Cap file generation failed.
    conversion completed with 1 errors and 0 warnings.
    The opt file I've got should be fairly un-offensive:
    -out CAP
    -exportpath "c:\JavaCardDevelopment\api_export_files;C:\gp211;.\"
    -debug
    -i
    -v
    -noverify
    -applet 0xA0:0x00:0x00:0x00:0x04:0x10:0x10 com.schip_select.schip
    com.schip_select
    0xA0:0x00:0x00:0x00:0x04:0x10 1.0
    I've tried with or without the -noverify flag.
    I'm using Java JDK Standard Edition (build 1.4.1_07-b02) to run the converter, and compile the source files. And I've tried the converter in the Sun Java Card Development kit 2.2.1 and 2.2.2. I've also tried attaching the jdb.exe to converter to see whats going on, I can see that it fails in a function:
    com.sun.javacard.jcasm.cap.ReferenceLocationComponent.addTwoByteOffset()
    But can't get anymore information than that. Any pointers to what could be causing this (I frankly don't know where to start) would be greatly appreciated.
    Thanks,
    James

    6A80 is the error which says that there is mismatch between jc version of card and java version.
    For Javacard 2.2.1 java version is jdk.1.4.1
    But lets not focus on that
    I tried to recreate the problem. You were using GP classes to create a cap file so I downloaded GP exp files from
    [http://www.globalplatform.org/specificationform2.asp|http://www.globalplatform.org/specificationform2.asp].
    Compiled files as
    javac -g -classpath .\classes;..\lib\api.jar;..\lib\installer.jar;libs/gp211.jar;libs/jc221.jar {PACKAGE_DIR}\*.javaMy opt file is as
    -out EXP JCA CAP
    -exportpath C:\java_card2.2.1\java_card_kit-2_2_1\api_export_files;C:\GP211\GP_exportA00000015100
    -applet <APPLET_AID> <Applet_DIR>
    <PACKAGE>
    <PACKAGE_AID> 1.0and called converter command as
    converter -config {PATH_TO_EXPORT_FILE}\HelloWorld.optI was able to create the CAP file successfully.

  • Snapshot() throws IllegalArgumentException when invoked from ActionEvent

    I've got a program in which I need to create a snapshot of a Node in response to a button press. However, I always get the following Exception, even if I invoke it from a Platform.runLater() call instead of directly under the ActionEvent method. Does anybody know what causes this and how to get around it? I've had snapshot() work for me in other contexts.
    java.lang.IllegalArgumentException: Unrecognized image loader: null
        at javafx.scene.image.WritableImage.loadTkImage(WritableImage.java:230)
        at javafx.scene.image.WritableImage.access$000(WritableImage.java:44)
        at javafx.scene.image.WritableImage$1.loadTkImage(WritableImage.java:49)
        at javafx.scene.Scene.doSnapshot(Scene.java:1144)
        at javafx.scene.Node.doSnapshot(Node.java:1632)
        at javafx.scene.Node.snapshot(Node.java:1710)
        at highreseffecttest.HighResEffectTest$1.handle(HighResEffectTest.java:54)
        at highreseffecttest.HighResEffectTest$1.handle(HighResEffectTest.java:50)
        at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
        at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
        at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
        at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:28)
        at javafx.event.Event.fireEvent(Event.java:171)
        at javafx.scene.Node.fireEvent(Node.java:6867)
        at javafx.scene.control.Button.fire(Button.java:179)
        at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:193)
        at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:336)
        at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:329)
        at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:64)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
        at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
        at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
        at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:33)
        at javafx.event.Event.fireEvent(Event.java:171)
        at javafx.scene.Scene$MouseHandler.process(Scene.java:3311)
        at javafx.scene.Scene$MouseHandler.process(Scene.java:3151)
        at javafx.scene.Scene$MouseHandler.access$1900(Scene.java:3106)
        at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1563)
        at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2248)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:250)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:173)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:292)
        at com.sun.glass.ui.View.handleMouseEvent(View.java:530)
        at com.sun.glass.ui.View.notifyMouse(View.java:924)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
        at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
        at java.lang.Thread.run(Thread.java:744)

    A few ideas, none tried:
    Take multiple snapshots of the node setting snapshot parameters on each snapshot with different viewports set on the parameters, then stitch together the resultant snapshot images
    or reduce the image resolution prior to taking a snapshot
    or try a video card with more texture memory
    Also log a bug in Jira.

  • Currency: valid ISO 4217 codes still throw IllegalArgumentExceptions

    java.util.Currency is supposed to support ISO 4217 currency codes (as written in its javadoc). But I still get IllegalArgumentExceptions for the currency codes GHS, RSD, SDG that are still active as I read in wikipedia (http://en.wikipedia.org/wiki/ISO_4217). I also get this exception for some other currency codes that are obsolete but still valid (XEU, ZAL, ...).
    It seems that java.util.Currency only supports a subset of the ISO 4217 currency codes. That makes it unusable as I have to work with the currency codes (Strings) to also handle these other (valid) currency codes. What is this class good for if it only can handle a subset and you can't create your own (new) Currency objects?

    yup. I guess the Currency class was someone's idea of a bright idea at the time, like so many things.
    But someone (probably that same someone) didn't think about the consequences of implementing it the way they did and now Sun's stuck with it.
    Can't remove it because someone may depend on it, and maintenance is expensive and never fast enough for some yet always too quick for others (who have come to depend on the exact content).

  • Set output buffer position

    Bonjour,
    j'ai un problème de configuration de mon pod USB-4431:je souhaite mesurer une fonction de transfert entre un signal d'entrée (output) et une sortie capteur.
    Pour mon signal d'entrée, j'envoi en continue un chirp de 8192 samples (tâche output).
    Pour mon signal de sortie, j'acquiert (de façon synchronisée) 5x8192 samples.
    La première mesure: tout est parfait... 
    Les mesures suivante: ce n'est plus bon...
    Le problème que j'identifie: mon appel DAQmxStopTask à la fin de la première mesure n'est pas aligné avec la fin du buffer => Lorsque je relance DAQmxStartTask, la tâche redémarre à un sample qui n'est pas 0 => mon signal d'entrée a changé...
    J'ai essayé un DAQmxSetWriteRelativeTo puis un DAQmxSetWriteOffset sans succès...
    La seule solution qui semble corriger ce problème: DAQmxResetDevice puis reconfiguration, mais c'est trop long pour mon application.
    Quelqu'un aurait une idée?
    Merci d'avance

    pouvez vous mettre votre vi en ligne pour que l'on puisse trouver une solution à votre problème plus facilement. ensuite pourquoi voulez vous faire 5* 8192 en acquisition?
    Cordialement
    L.MICOU

  • [jdk1.4 Buffers] What's the difference between flip() and position(0) ?

    Hi all,
    as stated above, what's the difference between flipping the buffer with
    the method flip() and setting the position to 0 ? They seem to do the same
    thing, that is moving the pointer at the beginning of the buffer....
    Thanks
    Francesco

    the original sourcecode from java.noi.Buffer says:
        public final Buffer position(int newPosition) {
         if ((newPosition > limit) || (newPosition < 0))
             throw new IllegalArgumentException();
         position = newPosition;
         if (mark > position) mark = -1;
         return this;
        public final Buffer flip() {
         limit = position;
         position = 0;
         mark = -1;
         return this;
        }you see, both do the same thing. flip is only a convenience for position(0);

  • Problems with SocketChannel.write(ByteBuffer buff).

    I am using the following version of JDK on Red Hat Linux
    java version "1.4.2_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_01-b06)
    Java HotSpot(TM) Client VM (build 1.4.2_01-b06, mixed mode)
    I am using SocketChannel's write method mentioned above to write data to the SocketChannel. When data is being written on the SocketChannel via this write method and the underlying socket is closed by the receiving endpoint, I expect this method to throw an exception. This method does not throw any exception and returns me 0 as the value of number of bytes written out.
    The way my code is written out, it ends up going in an infinite loop. Now, I can very well fix my code to not run in an infinite loop, but is anybody else seeing this? Is this a valid behavior? Am I doing something wrong?
    Following is the code snippet that writes data to the SocketChannel. Note that writeBuffer is an instance of ByteBuffer and sc is an instance of SocketChannel. Both these variables are member variables in my class:
    public void write(byte[] buff, int offset, int length)
        throws IOException
        int toBeWritten = 0;
        while (length > 0)
            int writeOffset = offset;
            toBeWritten = writeBuffer.remaining();
            if (toBeWritten >= length)
                // All the bytes that are scheduled to be written will be
                // written.
                toBeWritten = length;
                length = 0;
            else
                // Only some of the bytes that are scheduled to be written will
                // be written.
                length -= toBeWritten;
                offset += toBeWritten;
            writeBuffer.put(buff, writeOffset, toBeWritten);
            // toBeWritten is the number of bytes that need to be written out.
            while (writeBuffer.position() != 0)
                // position = toBeWritten.
                writeBuffer.flip();
                // position = 0, limit = toBeWritten.
                int wrote = sc.write(writeBuffer);
                // position = wrote, limit = toBeWritten.
                // Compact the write buffer. It is very much possible that all
                // the bytes have not yet been written out.
                writeBuffer.compact();
                // The data that was written out, is now removed from the write
                // buffer. position = toBeWritten - wrote, limit = capacit
    }Thanks in advance!!

    When ByteBuffer.write(...) return 0, it means this
    socket is closed gracefully by another peer. the
    socket is need to re-connect again.Oh.. I forgot to mention, I am using non blocking SocketChannel. As per the Java docs for write(ByteBuffer src) method in WritableByteChannel:
    "Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer."
    So, I cannot assume that if the write method returns 0, the socket is closed by another peer.

  • Write RAW buffer (binary data) to OS file

    Hi there,
    It is easy to insert BLOB data into a BLOB-column of a table from a BFILE. But how can a do the other way around? That means:
    Read the BLOB (maybe into a variable 'buffer RAW(...)') and write it into a binary file? As I know, the UTL_FILE package only supports ascii files.
    The following demo example works to display the raw-data on the screen:
    CREATE OR REPLACE PROCEDURE displayLOB_proc IS
    Lob_loc BLOB;
    Buffer RAW(255);
    Amount BINARY_INTEGER := 255;
    Position INTEGER := 1;
    BEGIN
    /* Select the LOB: */
    SELECT Photo INTO Lob_loc
    FROM testblob WHERE id = 1;
    /* Opening the LOB is optional: */
    DBMS_LOB.OPEN (Lob_loc, DBMS_LOB.LOB_READONLY);
    LOOP
    DBMS_LOB.READ (Lob_loc, Amount, Position, Buffer);
    /* Display the buffer contents: */
    DBMS_OUTPUT.PUT_LINE(utl_raw.cast_to_varchar2(Buffer));
    Position := Position + Amount;
    END LOOP;
    /* Closing the LOB is mandatory if you have opened it: */
    DBMS_LOB.CLOSE (Lob_loc);
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('End of data');
    END;
    What should be inserted instead of DBMS_OUTPUT.PUT_LINE(...).
    Please help
    Peter

    >I have discovered that I just posted the same question.
    Please annote your other post as such.
    >Does DBMS_UTIL 9.2 run under Oracle 8i?
    UTL_FILE (not DBMS_UTIL), and 9.2 = Oracle9i Database Release 2. So, no. You will need to implement an external procedure via c or java to get you home with 8i. Search this forum (as best as you can) for the multitudes of such solutions.
    >Where can I locate some of the sameple code that you mention?
    I have none handy, yet. You can read all about it @ http://tahiti.oracle.com
    Michael O'Neill
    Publisher of the PigiWiki
    clever-idea.com

  • Custom Indirection Container throwing exception in constructor

    Hi I've following the how-to and implemented my own custom indirection container. However, when reading an object from the database I'm getting the following exception. I'm guessing that it could be related to having null references stored as 0 in id columns. Any help would be greatly appreciated.
    Thanks,
    Jon
    Exception thrown in main Exception [TOPLINK-152] (OracleAS TopLink - 10g (9.0.4.8) (Build 050712)):
    oracle.toplink.exceptions.DescriptorException
    Exception Description: The operation [buildContainer constructor (null) Failed: java.lang.NullPointe
    rException] is invalid for this indirection policy [oracle.toplink.internal.indirection.ContainerInd
    irectionPolicy@cc0e01].
    Mapping: oracle.toplink.mappings.OneToOneMapping[ryFromMail]
    Descriptor: Descriptor(com.peoplesoft.crm.omk.design.PsRyedocVar --> [DatabaseTable(PS_RYEDOC_VAR)])
    Local Exception Stack:
    Exception [TOPLINK-152] (OracleAS TopLink - 10g (9.0.4.8) (Build 050712)): oracle.toplink.exceptions
    .DescriptorException
    Exception Description: The operation [buildContainer constructor (null) Failed: java.lang.NullPointe
    rException] is invalid for this indirection policy [oracle.toplink.internal.indirection.ContainerInd
    irectionPolicy@cc0e01].
    Mapping: oracle.toplink.mappings.OneToOneMapping[ryFromMail]
    Descriptor: Descriptor(com.peoplesoft.crm.omk.design.PsRyedocVar --> [DatabaseTable(PS_RYEDOC_VAR)])
    at oracle.toplink.exceptions.DescriptorException.invalidIndirectionPolicyOperation(Descripto
    rException.java:669)
    at oracle.toplink.internal.indirection.ContainerIndirectionPolicy.buildContainer(ContainerIn
    directionPolicy.java:62)
    at oracle.toplink.internal.indirection.ContainerIndirectionPolicy.valueFromQuery(ContainerIn
    directionPolicy.java:254)
    at oracle.toplink.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java
    :898)
    at oracle.toplink.mappings.OneToOneMapping.valueFromRow(OneToOneMapping.java:1302)
    at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:876)
    at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder
    .java:164)
    at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:322)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:
    242)
    at oracle.toplink.queryframework.ReadObjectQuery.execute(ReadObjectQuery.java:368)
    at oracle.toplink.queryframework.DatabaseQuery.execute(DatabaseQuery.java:510)
    at oracle.toplink.queryframework.ReadQuery.execute(ReadQuery.java:125)
    at oracle.toplink.publicinterface.Session.internalExecuteQuery(Session.java:1962)
    at oracle.toplink.publicinterface.Session.executeQuery(Session.java:1086)
    at oracle.toplink.internal.indirection.NoIndirectionPolicy.valueFromQuery(NoIndirectionPolic
    y.java:254)
    at oracle.toplink.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java
    :898)
    at oracle.toplink.mappings.OneToOneMapping.valueFromRow(OneToOneMapping.java:1302)
    at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:876)
    at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder
    .java:164)
    at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:322)
    at oracle.toplink.queryframework.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:
    242)
    at oracle.toplink.queryframework.ReadObjectQuery.execute(ReadObjectQuery.java:368)

    Clients of your class might not like you throwing
    exceptions from the ctor. If they're checked
    exceptions it'll mean try/catch blocks. If there are
    LOTS of checked exceptions that'll mean lots of catch
    blocks. Could get messy fast. You could catch in the
    ctor and wrap in a subclass of
    java.lang.RuntimeException. Those are unchecked, like
    java.lang.IllegalArgumentException.I would strongly advise against making your checked exceptions unchecked just so that the caller's code will compile without try/catch blocks. Either way--checked or unchecked--if I do Foo foo = new Foo();
    foo.doStuff(); I won't get to doStuff() if the ctor threw an exception.
    You'd throw unchecked exceptions in those cases where it's appropriate--e.g., the caller passed you invalid args (bad code on the caller's part, appropriated for unchecked exception), or the VM couldn't get enough memory to create your object (probably not something the caller can do anything about, so, again, appropriate for unchecked).
    But if, for example, he's passing you database login parameters that an end user provided, and the password is wrong or the host is unreachable, then you'd want to throw a checked exception, because it's not bad code on the caller's part, and there might be something he can do to recover.
    Note that the example of the incorrect password above is quite different from the "invalid args" example in the previous paragraph. Your method would throw IllegalArgumentException if the caller passed args that violate your method's precondition--e..g. lie outside some range of numbers. That is, it's a value that your method simply can't use. A bad password for a db login, on the other hand, is legal as far as your method is concerned, it just failed authentication in the db.
    @%: I know you're aware of the proper use of checked/unchecked exceptions, but the way you worded you post kind of sounded like you were saying, "just use unchecked if you find the caller has too many try statements."
    &para;

  • Should I declare IllegalArgumentException in my method declaration

    Hi,
    I have a setter method which throws an IllegalArgumentException which is of type RuntimeException... It means that I need not declare it in my method declaration, but I should explicity describe in Javadoc.
    Is it a good practice to declare it in throws clause just to make it more readable? or is it superfluous and unnecessary because I am going to describe it in Javadoc anyway?
    I mean....
      * @throws IllegalArgumentException
    public void setterMethod() {
    vs
      * @throws IllegalArgumentException
    public void setterMethod() throws IllegalArgumentException {
    }Thank you,
    Srikanth

    I have a setter method which throws an
    IllegalArgumentException which is of type
    RuntimeException... It means that I need not declare
    it in my method declaration, but I should explicity
    describe in Javadoc.If you conclude that it is important that the other programmers know in which situation your method throws an IllegalArgumentException then go ahead and describe it in javadoc. If you think that it's not important, or it's not necessary, you don't need to describe it. But in general, the unchecked exception IllegalArgumentException, if it is used according to its purposes, deserves a javadoc description. Although I think you are not using this exception appropriately, because your method doesn't even have a parameter! I hope you are showing just an example, just to support your question.
    Is it a good practice to declare it in throws clause
    just to make it more readable? or is it superfluous
    and unnecessary because I am going to describe it in
    Javadoc anyway?No! It does not make it more readable. IllegalArgumentException is an unchecked exception, so you have to take advantage of this "uncheackability", that is, the advantage of not being needed to declare that the method throws it. In any case, you shouldn't declare the throws clause for any kind of unchecked exception. A description in javadoc is enough. But I see that you're just saying that the method can throw IllegalArgumentException, in the javadoc. Why don't you give more details? It is a good practice. See below an example:
      * @throws IllegalArgumentException if the parameter name passed is null,
      * or if it is equal to "".
    public void setterMethod(String name) {
    }

  • IllegalArgumentException:name

    Hi
    I am using jetty 6_1_8 for creating a Http Server Adapter. I am able to access it in linux but I am getting the following exception in windows
    java.lang.IllegalArgumentException: name
         at sun.misc.URLClassPath$Loader.findResource(URLClassPath.java:458)
         at sun.misc.URLClassPath.findResource(URLClassPath.java:145)
         at java.net.URLClassLoader$2.run(URLClassLoader.java:362)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findResource(URLClassLoader.java:359)
         at java.lang.ClassLoader.getResource(ClassLoader.java:978)
         at org.mortbay.jetty.webapp.WebAppClassLoader.getResource(WebAppClassLoader.java:258)
         at org.mortbay.resource.Resource.newSystemResource(Resource.java:202)I saw jetty code and it is like
    _parent.getResource(name);
    name is the location of webdefault.xml which is (E:\DEV_E\install_524_mssql_2008\install\noapp\etc\webdefault.xml) for windows
    and for windows it is /ais_local/share/alodha/52/gis_CATA_5241_18000/platform_core/install/noapp/etc/webdefault.xml
    I want to understand why it is throwing illegalArgumentException:name?
    Also when I dont use this custom webdefault.xml (using jetty provided default webdefault.xml) then it works fine.
    Edited by: 821458 on Dec 27, 2012 1:31 AM

    I want to know why and when ClassLoader.getResource(name) can give this exception.
    The below is the code for URLClassLoader which throws the exception. I just want to understand in what conditions it can throw MalformedURLException which ultimately throws IllegalArgumentException:name
    Resource getResource(final String name, boolean check) {
                    final URL url;
                    try {
                        url = new URL(base, ParseUtil.encodePath(name, false));
                    } catch (MalformedURLException e) {
                        throw new IllegalArgumentException("name");
                   }

  • IllegalArgumentException does not produce Web Service Fault

    Folks,
    I'm deploying an EJB 3.0 annotated to provide Web Services for Weblogic 10.3. One of the parameters to the EJB contains is a BigDecimal Value. When this parameter is created, we check to make sure it meets certain criteria. If it fails we throw an IllegalArgumentException. This Exception does not get propagated back to the client (a soap client) as a fault.The marshalling code just seems to ignore the exception.
    *1) Here's the code:*
    private void checkNum2( BigDecimal value ) throws IllegalArgumentException
    if ( value.scale() > 0 )
    throw new IllegalArgumentException(
    "Property ImportCalcCalculator.Num2 cannot be more than 0 fractional digits");
    *2) Here is the stack when the code is about to throw the fault:*
    SCalculatorImport$ImportCalcCalculator.checkNum2(BigDecimal) line: 607     
    SCalculatorImport$ImportCalcCalculator.setNum2(BigDecimal) line: 597     
    SCalculatorImport$ImportCalcCalculator$JaxbAccessorM_getNum2_setNum2_java_math_BigDecimal.set(Object, Object) line: 56     
    TransducedAccessor$CompositeTransducedAccessorImpl<BeanT,ValueT>.parse(BeanT, CharSequence) line: 241     
    LeafPropertyLoader.text(UnmarshallingContext$State, CharSequence) line: 61     
    UnmarshallingContext.text(CharSequence) line: 462     
    InterningXmlVisitor.text(CharSequence) line: 89     
    StAXStreamConnector.processText(boolean) line: 367     
    StAXStreamConnector.handleEndElement() line: 245     
    StAXStreamConnector.bridge() line: 214     
    UnmarshallerImpl.unmarshal0(XMLStreamReader, JaxBeanInfo) line: 358     
    BridgeImpl<T>.unmarshal(Unmarshaller, XMLStreamReader) line: 120     
    BridgeImpl<T>(Bridge<T>).unmarshal(XMLStreamReader, AttachmentUnmarshaller) line: 233     
    EndpointArgumentsBuilder$DocLit.readRequest(Message, Object[]) line: 517     
    EndpointMethodHandler.invoke(Packet) line: 243     
    SEIInvokerTube.processRequest(Packet) line: 93     
    Fiber.__doRun(Tube) line: 598     
    Fiber._doRun(Tube) line: 557     
    Fiber.doRun(Tube) line: 542     
    Fiber.runSync(Tube, Packet) line: 439     
    WSEndpointImpl$2.process(Packet, WebServiceContextDelegate, TransportBackChannel) line: 243     
    HttpAdapter$HttpToolkit.handle(WSHTTPConnection) line: 444     
    EJBDeployInfo$WLSEjbServletAdapterList$1(HttpAdapter).handle(WSHTTPConnection) line: 244     
    EJBDeployInfo$WLSEjbServletAdapterList$1(ServletAdapter).handle(ServletContext, HttpServletRequest, HttpServletResponse) line: 134     
    HttpServletAdapter$AuthorizedInvoke.run() line: 272     
    HttpServletAdapter.post(HttpServletRequest, HttpServletResponse) line: 185     
    JAXWSEjbServlet(JAXWSServlet).doPost(HttpServletRequest, HttpServletResponse) line: 180     
    JAXWSEjbServlet(HttpServlet).service(HttpServletRequest, HttpServletResponse) line: 727     
    JAXWSEjbServlet(JAXWSServlet).service(HttpServletRequest, HttpServletResponse) line: 64     
    JAXWSEjbServlet(HttpServlet).service(ServletRequest, ServletResponse) line: 820     
    StubSecurityHelper$ServletServiceAction.run() line: 227     
    StubSecurityHelper.invokeServlet(ServletRequest, HttpServletRequest, ServletRequestImpl, ServletResponse, HttpServletResponse, Servlet) line: 125     
    ServletStubImpl.execute(ServletRequest, ServletResponse, FilterChainImpl) line: 292     
    ServletStubImpl.execute(ServletRequest, ServletResponse) line: 175     
    WebAppServletContext$ServletInvocationAction.run() line: 3498     
    AuthenticatedSubject.doAs(AbstractSubject, PrivilegedAction) line: 321     
    SecurityManager.runAs(AuthenticatedSubject, AuthenticatedSubject, PrivilegedAction) line: not available     
    WebAppServletContext.securedExecute(HttpServletRequest, HttpServletResponse, boolean) line: 2180     
    WebAppServletContext.execute(ServletRequestImpl, ServletResponseImpl) line: 2086     
    ServletRequestImpl.run() line: 1406     
    ExecuteThread.execute(Runnable) line: 201     
    ExecuteThread.run() line: 173     
    Regards,
    Robert

    Hi,
    simply throw SOAPFaultException, that's all.
    What I recommend is following :
    - ejb method throws IllegalArgumentException
    - ws method - catch block converts exception to SOAPFaultException and throws it
    - client receives fault, e.g. .NET client receives fault, it works.
    Here is method converting Throwable to SOAPFaultException
         protected SOAPFaultException convertToSOAPException(final Throwable t)
         Detail detail = null;
         try
         SOAPFactory soapFactory = SOAPFactory.newInstance();
         detail = soapFactory.createDetail();
         catch (SOAPException e)
              Log.getLogger(this).error(e);
         QName faultCode = null;
         String faultString = t.getMessage();
         String faultActor = this.getClass().getName();
         if( AppProperties.getProperty("soap_exception_include_stack_trace", false) == true )
                   CharArrayWriter caw = new CharArrayWriter();
                   PrintWriter pw = new PrintWriter(caw);
                   t.printStackTrace(pw);
              faultString = caw.toString();
         SOAPFaultException sfe = new SOAPFaultException(faultCode, faultString, faultActor, detail);
         Log.getLogger(this).error(sfe);
         return sfe;
    Hope it helps
    Miro N.

  • How to restrict the size of Buffer data object

    Hi everyone.
    How do you restrict the size of the Buffer data object. The byte array that you get by calling getData(). I want to restrict the size to be at most X nbr of bytes. I'm 'filling' the buffer like this:
    Buffer readBuffer;
    PushBufferStream stream;
    stream.read(readBuffer);

    This is my code:
    class DataSourceHandler implements DataSink, BufferTransferHandler {
              private int MAX_DATA_PACKET_SIZE = 2000;
              private DataSource source;
              private PullBufferStream pullStrms[] = null;
              private PushBufferStream pushStrms[] = null;
              // Data sink listeners.
              private Vector listeners = new Vector(1);
              // Stored all the streams that are not yet finished (i.e. EOM
              // has not been received.
              private SourceStream unfinishedStrms[] = null;
              // Loop threads to pull data from a PullBufferDataSource.
              // There is one thread per each PullSourceStream.
              private Loop loops[] = null;
              private Buffer readBuffer;
               * Sets the media source this <code>MediaHandler</code> should use to
               * obtain content.
              public void setSource(DataSource source)
                        throws IncompatibleSourceException {
                   // Different types of DataSources need to handled differently.
                   if (source instanceof PushBufferDataSource) {
                        System.out.println("source instanceof PushBufferDataSource");
                        pushStrms = ((PushBufferDataSource) source).getStreams();
                        unfinishedStrms = new SourceStream[pushStrms.length];
                        // Set the transfer handler to receive pushed data from
                        // the push DataSource.
                        for (int i = 0; i < pushStrms.length; i++) {
                             pushStrms.setTransferHandler(this);
                             unfinishedStrms[i] = pushStrms[i];
                   } else if (source instanceof PullBufferDataSource) {
                        System.out.println("source instanceof PullBufferDataSource");
                        pullStrms = ((PullBufferDataSource) source).getStreams();
                        unfinishedStrms = new SourceStream[pullStrms.length];
                        // For pull data sources, we'll start a thread per
                        // stream to pull data from the source.
                        loops = new Loop[pullStrms.length];
                        for (int i = 0; i < pullStrms.length; i++) {
                             loops[i] = new Loop(this, pullStrms[i]);
                             unfinishedStrms[i] = pullStrms[i];
                   } else {
                        // This handler only handles push or pull buffer datasource.
                        throw new IncompatibleSourceException();
                   this.source = source;
                   readBuffer = new Buffer();
                   byte[] data = new byte[MAX_DATA_PACKET_SIZE];
                   readBuffer.setData(data);
              * For completeness, DataSink's require this method. But we don't need
              * it.
              public void setOutputLocator(MediaLocator ml) {
              public MediaLocator getOutputLocator() {
                   return null;
              public String getContentType() {
                   return source.getContentType();
              * Our DataSink does not need to be opened.
              public void open() {
              public void start() {
                   try {
                        source.start();
                   } catch (IOException e) {
                        System.err.println(e);
                   // Start the processing loop if we are dealing with a
                   // PullBufferDataSource.
                   if (loops != null) {
                        for (int i = 0; i < loops.length; i++)
                             loops[i].restart();
              public void stop() {
                   try {
                        source.stop();
                   } catch (IOException e) {
                        System.err.println(e);
                   // Start the processing loop if we are dealing with a
                   // PullBufferDataSource.
                   if (loops != null) {
                        for (int i = 0; i < loops.length; i++)
                             loops[i].pause();
              public void close() {
                   stop();
                   if (loops != null) {
                        for (int i = 0; i < loops.length; i++)
                             loops[i].kill();
              public void addDataSinkListener(DataSinkListener dsl) {
                   if (dsl != null)
                        if (!listeners.contains(dsl))
                             listeners.addElement(dsl);
              public void removeDataSinkListener(DataSinkListener dsl) {
                   if (dsl != null)
                        listeners.removeElement(dsl);
              protected void sendEvent(DataSinkEvent event) {
                   if (!listeners.isEmpty()) {
                        synchronized (listeners) {
                             Enumeration list = listeners.elements();
                             while (list.hasMoreElements()) {
                                  DataSinkListener listener = (DataSinkListener) list
                                            .nextElement();
                                  listener.dataSinkUpdate(event);

Maybe you are looking for

  • WebGate for OHS on Solaris?

    I cannot find a WebGate for OHS on Solaris. I can only find OHS2 on Solaris. Anyone know where to get it? Joost

  • Document or video tutorial for setting LiveCycle Collaboration Service in Flash Professional CS5

    Hello, I want to use Adobe LiveCycle Collaboration Service for my company, but the problem is, I work upon Flash Professional and i dont have grip towards Flex, the documentation that is provided with sdk is of Flex, so, I want 2 types of help, 1) If

  • VC issues or problems

    Here are some issues with Visual Composer faced by me : 1.Tool Bar for the Tabke View doesn't come up for WebDynPro app.Its there only for Flash run time. 2.Delete button doesn’t work for rename / edit buttons, you have to rely on Backspace button. 3

  • Using same chapter points for separate projects

    When I use the "Replace Asset" operation to replace one video asset on a timeline with another of the same format, the chapter points remain unchanged. This is a very useful feature, because often one needs to make some minor changes to a video asset

  • How to transfer R/3 transaction screen values to crm web client Identificat

    Hi   how to transfer Notification (iw52)  screen values BP, contract, Premise  to CRM webcleint 50 screen i.e to , when i click on identification tab my fields should populate into the screen. please guide. thanks ram