Using BigInteger as primarykey

Hi,
When I use BigInteger as primary key and use the sequence with it I get this exception
java.lang.ClassCastException: java.lang.Long
     at com.sleepycat.persist.impl.SimpleFormat$FBigInt.writeObject(SimpleFormat.java:767)
     at com.sleepycat.persist.impl.PersistKeyAssigner.assignPrimaryKey(PersistKeyAssigner.java:50)
     at com.sleepycat.persist.PrimaryIndex.assignKey(PrimaryIndex.java:487)
     at com.sleepycat.persist.PrimaryIndex.put(PrimaryIndex.java:338)
     at com.sleepycat.persist.PrimaryIndex.put(PrimaryIndex.java:314)
SimpleFormat is trying to cast the Long value to bigInteger and thats how the class cast
exception is raised.
My question is can we use bigInteger with the DPL sequence like
@PrimaryKey(sequence="seq_my_entity")
private BigInteger my_pk;
What my understanding is that BigInteger is included in the simple datatypes of the DPL, and it should support the autogeneration of BigInt keys.
One more thing what will happen when primary key having the type long runs out of value, like there are millions of record.
Thanks,
Shoaib

Hello Shoaib,
Primary key sequences are not currently allowed with BigInteger keys. See the javadoc for PrimaryKey.sequence:
http://www.oracle.com/technology/documentation/berkeley-db/je/java/com/sleepycat/persist/model/PrimaryKey.html#sequence()
To use a sequence, the type of the key field must be a primitive integer type (byte, short, int or long) or the primitive wrapper class for one of these types.
We do not currently support BigInteger sequences because (as you point out) JE sequences are limited to long values, and BigInteger can contain much larger values. This limitation is in the JE base API Sequence class, not the DPL.
However, you should have received a more informative error message, not a ClassCastException. We'll fix that in a future release.
If you need values larger than a long, and you would like to assign them from a sequence, you can use a BigInteger key and implement a sequence yourself. I suggesting implementing a singleton sequence class that increments the sequence in memory, in a synchronized method, for example:
private BigInteger lastValue;
synchronized BigInteger getNext() {
    lastValue = lastValue.add(BigInteger.ONE);
    return lastValue;
}When opening the store, initialize the sequence from the largest existing key; for example:
PrimaryIndex<BigInteger,MyData> priIndex = ...
EntityCursor<BigInteger> keys = priIndex.keys();
try {
   lastValue = keys.last();
} finally {
   keys.close();
if (lastValue == null) {
    lastValue = BigInteger.ONE;
}Does this help?
Mark

Similar Messages

  • Help using BigInteger

    hi ,
    can any one explain with a program how to use biginteger.baically this is used for taking a verbig number,but i got struck in using it so please help me using with a program of using it.

    > can any one explain with a program how to use
    biginteger.baically this is used for taking a verbig
    number,but i got struck in using it so please help me
    using with a program of using it.
    My crystal boll tells me that this is your answer:
    boolean b = (new BigInteger("666")).isProbablePrime(66);Correct?

  • Using BigInteger as type for JavaFX property

    Hello,
    Why is BigInteger not a legitimate type for a JavaFX property?
    Is there a way for me to use a java.math.BigInteger as shown below:
    class HomePhone
    BigInteger landLine1 = 0
    BigInteger landLine2 = 0
    } // end class HomePhone
    Thank you very much.

    Why is BigInteger not a legitimate type for a JavaFX property?Because it does not implement the JavaFX property interface:
    http://docs.oracle.com/javafx/2/api/javafx/beans/property/Property.html
    You could fit your phone numbers in an IntegerProperty or LongProperty, which have maxvalues of 2147483647 and 9223372036854775807 respectively or you could use a SimpleStringProperty.
    One could make a high quality BigIntegerProperty with a bit of work. To do a full implementation of property management for BigIntegers which handles expressions, type conversions, etc, requires quite a few classes. For example, you can see some of the hierarchy implemented to enable rich Double properties - something similar could be created for BigInteger - a feature request could be created at http://javafx-jira.kenai.com.
    java.lang.Object
    javafx.beans.binding.NumberExpressionBase
    javafx.beans.binding.DoubleExpression
    javafx.beans.property.ReadOnlyDoubleProperty
    javafx.beans.property.DoubleProperty
    javafx.beans.property.DoublePropertyBase
    javafx.beans.property.SimpleDoubleProperty

  • Unable to Create Insert page in OAF Using ROWID as primaryKey

    I have Taken RowID as primary Key in Entity Creation.I written following Code as follow in Process Request method
    OAViewObject vo=(OAViewObject)am.findviewObject("VONAME');
    if(!vo.ispreparedforexecution)
    vo.executequery();
    Row row=vo.createRow();
    vo.insertRow(row);
    row.setNewRowstate(Row.STATUS_ INITIALIZED);
    but
    i am getting an error like Entity Create Row Exception

    Hi,
    sorry, wrong forum. This is all about Oracle JDeveloper. OAF related questions are handled on the OAF forum
    Frank

  • BigInteger.parseBigInteger : help

    hi,
    everybody.
    i want to parse a string which is in number format to BigInteger.
    but i was enable to find any method for it in the java api
    so currently i am working on Long, and it is working fine.
    but in future if i get a number which is beyond the limit of Long than there can be a problem, so i want to use BigInteger.
    the number which i am getting is 68719478912.
    my current coding for Long is:-
         case 5:
              if((Long.parseLong(functionlevel1[1].trim()) & Long.parseLong(tokenstring[4].trim())) > 0)
              privilegeclassdetailsobj.functionsmodel.addElement(functionlevel1[i][0]);
              else
              privilegeclassdetailsobj.functionsmodel1.addElement(functionlevel1[i][0]);
              break;
    so now how can i do parsing on BigInteger.
    please reply as i am stucked with this problem.
    waiting for reply
    thanks in advance

    hi
    sabre150
    thanks for ur reply,
    but the reply which u gave is static declaration.
    i want it to make dynamic.
    because in my program i can get any value from the
    server
    and the reply which u gave is only for a specified
    value.
    hope u got my point.
    waiting for replyWhat am I missing?
    new BigInteger(theStringFromTheServerContainingTheDigitsOfTheNumber);

  • Recoding for J2ME - Replacing BigInteger

    Hi,
    I'm working on getting the TOTP class from http://www.ietf.org/id/draft-mraihi-totp-timebased-03.txt However - they use BigInteger to run some of the type conversions for the timestamp and key.
    I've tried all of yesterday, last night and today to get something that functions - but I never seem to get the right/working result....
    specifically the line is:
    bArray = new BigInteger(time,16).toByteArray()
    and then getting that same value but in a J2ME compatable way. any suggestions ?
    time is a string, as a base 16 representation of the timestamp.
    Thanks,
    PC_Nerd
    * This works when not compileing for J2ME - and just on a standard J2(SE or EE ?) compile. * I haven't worked on java for over a year.

    Hi,
    I'm working on getting the TOTP class from http://www.ietf.org/id/draft-mraihi-totp-timebased-03.txt However - they use BigInteger to run some of the type conversions for the timestamp and key.
    I've tried all of yesterday, last night and today to get something that functions - but I never seem to get the right/working result....
    specifically the line is:
    bArray = new BigInteger(time,16).toByteArray()
    and then getting that same value but in a J2ME compatable way. any suggestions ?
    time is a string, as a base 16 representation of the timestamp.
    Thanks,
    PC_Nerd
    * This works when not compileing for J2ME - and just on a standard J2(SE or EE ?) compile. * I haven't worked on java for over a year.

  • BigInteger, small problem

    String s = "hello";
    String i = "10";
    BigInteger s = new BigInteger(s);
    BigInteger i = new BigInteger(i);
    // so now i am using isProbablePrime(1) for both s and i
    i want to check that string entered is really a int like
    "i" string
    if s string is probed then exception occurs...
    HELP HELPthanks agents

    i want to check that string entered is really a intIf all you need to do is check whether a String can be an int then you can use...
    int value;
    try {
       value = Integer.parseInt(your_string);
    } catch(NumberFormatException nfe) {
       //do what you want if it is not an int
    }If you want to use BigInteger, the constructor that takes a String also throws a NumberFormatException like Integer.parseInt so you can use similar code.

  • Error While Deploying A CMP Entity Bean With A Composite Primary Key

    Hello all,
    I have a problem deploying CMP Entity beans with composite primary keys. I have a CMP Entity Bean, which contains a composite primary key composed of two local stubs. If you know more about this please respond to my post on the EJB forum (subject: CMP Bean Local Stub as a Field of a Primary Key Class).
    In the mean time, can you please tell me what following error message means and how to resolve it? From what I understand it might be a problem with Sun ONE AS 7, but I would like to make sure it's not me doing something wrong.
    [05/Jan/2005:12:49:03] WARNING ( 1896):      Validation error in bean CustomerSubscription: The type of non-static field customer of the key class
    test.subscription.CustomerSubscriptionCMP_1530383317_JDOState$Oid must be primitive or must implement java.io.Serializable.
         Update the type of the key class field.
         Warning: All primary key columns in primary table CustomerSubscription of the bean corresponding to the generated class test.subscription.CustomerSubscriptionCMP_1530383317_JDOState must be mapped to key fields.
         Map the following primary key columns to key fields: CustomerSubscription.CustomerEmail,CustomerSubscription.SubscriptionType. If you already have fields mapped to these columns, verify that they are key fields.Is it enough that a primary key class be serializable or all fields have to implement Serializable or be a primitive?
    Please let me know if you need more information to answer my question.
    Thanks.
    Nikola

    Hi Nikola,
    There are several problems with your CMP bean.
    1. Fields of a Primary Key Class must be a subset of CMP fields, so yes, they must be either a primitive or a Serializable type.
    2. Sun Application Server does not support Primary Key fields of an arbitrary Serializable type (i.e. those that will be stored
    as BLOB in the database), but only primitives, Java wrappers, String, and Date/Time types.
    Do you try to use stubs instead of relationships or for some other reason?
    If it's the former - look at the CMR fields.
    If it's the latter, I suggest to store these fields as regular CMP fields and use some other value as the PK. If you prefer that
    the CMP container generates the PK values, use the Unknown
    PrimaryKey feature.
    Regards,
    -marina

  • Generating RSA keys based on p, q, and public exponent

    Hi,
    The problem is the following. I need to generate an RSA key pair on the card based on pre-defined P, Q and public exponent. The KeyPair specs syas that if the public exponent is pre-initialized it will be retained. All other values are overwritten though (I checked with a test applet on jcop41). So two questions:
    1. Do you know of any card that can also retain p and q and generate (calculate) dp, dq, pq, and public modulus. This is contrary to the specification so I doubt there would be any, but it is always good to ask.
    2. Do any of you have a Java code that would do this (ie. calculate the missing key components) that can be run on Java Card, ie. does not use BigInteger or similar classes.
    Cheers,
    Woj

    That is exactly the point I was trying to make, I actually forgot about this thread, because the problem at hand went on the shelf for the moment. To reformulate:
    1. I have only certain parts of the RSA key, but enough parts to determine a valid private/public key pair.
    2. Now I want to generate the missing parts on the card. The JC API requires all the parts to be supplied, it is not possible to provide only partial (but determining the whole key) key information. The KeyPair class can only retain the public exponent during key generation, but not the other parts (according to the specs and my own tests).
    3. My wild guess is that it would probably be doable without too much hassle with host JCE, but it's not an option for me, it has to be done on the card.
    4. I could try to write my own Java Card code that would do this based on, say, openssl implementation, but now I am too lazy, so that's why I asked if somebody possibly has the code that does this.
    Cheers,
    Woj

  • Compare 2 Binary Numbers

    Hi all ,
    suppose I have two arbitrary lenght binary numbers (could be very large binaries).
    exple : 1000111 & 11111110001
    is it possible to compare them using only there 0s & 1s representations.
    i.e I don't want to convert them to base 10 & compare them (probably using BigInteger).
    what I'm looking for is an algorithm that compares 1000111 & 11111110001 only using there 0s & 1s sequences.
    If this is possible how can I implement it ?
    many thanks.

    boolean equal = true;
    for(inti = ar1.length, j=ar2.lenght; i >= 0 && j
    =
    0; i--, j--) {
    if(ar1[ i ]!=ar2[j]) {
    equal = false;
    break;
    } this code will tell you if ar1 & ar2 are equal but
    won't tell you if ar1 <ar2 or ar1>ar2
    how can we tell ar1 > ar2 for exple ?oh my bad.
    well then indeed one would hav to start at the highest bit and embed the "shorter" value with 0's.
    if the representation is in a primitive, eg. long, you cant simply write a < b since java doesnt know unsigned numbers. so either you are carefull enough and only store 31 bits in an int(like leave the highest bit alone) or you check the highest bit first, and then check the remaining.

  • Very Large Numbers Question

    I am a student with a question about how Java handles very large numbers. Regarding this from our teacher: "...the program produces values that
    are larger than Java can represent and the obvious way to test their size does not
    work. That means that a test that uses >= rather than < won?t work properly, and you
    will have to devise something else..." I am wondering about the semantics of that statement.
    Does Java "know" the number in order to use it in other types of mathematical expressions, or does Java "see" the value only as gibberish?
    I am waiting on a response from the teacher on whether we are allowed to use BigInteger and the like, BTW. As the given program stands, double is used. Thanks for any help understanding this issue!

    You're gonna love this one...
    package forums;
    class IntegerOverflowTesterator
      public static void main(String[] args) {
        int i = Integer.MAX_VALUE -1;
        while (i>0) {
          System.out.println("DEBUG: i="+i);
          i++;
    }You also need to handle the negative case... and that get's nasty real fast... A positive plus/times a positive may overflow, but so might a negative plus a negative.
    This is decent summary of the underlying problem http://mindprod.com/jgloss/gotchas.html#OVERFLOW.
    The POSIX specification also worth reading regarding floating point arithmetic standards... Start here http://en.wikipedia.org/wiki/POSIX I guess... and I suppose the JLS might be worth a look to http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html

  • Binary addition,subtraction and modulo operations.

    Query:
    Take two 512 bit numbers passed as strings. don't use biginteger!
    convert them to binary without using parseInt or toString functions.! you may use char array and byte arrays.
    then add these two binary numbers using binary addition logic.
    display the result in decimal format back again.
    Is it possible to perform this operation like this!!if yes,then please tell how should i approach with my existing code.
    thanks.
    package bytearrayopeations;
    import java.math.BigInteger;   
    public class binaryadding {
        public static void main(String[] args) {
            BigInteger a = new BigInteger("123456");
            BigInteger b = new BigInteger("5121");
            String bb1 = a.toString(2);
            String bb2 = b.toString(2);
            String ss1 = null;
            String ss2 = null;
            String result = "";
            String carry="0";
            System.out.println("first value=" +bb1);
            System.out.println("second value=" +bb2);
            int k=bb1.length();
            int h=bb2.length();
            System.out.println("length 1="+ k);
            System.out.println("length 2=" +h);
            int p=h-k;
            //System.out.println("difference=" +p);
            int q=k-h;
            //System.out.println("difference 2=" +q);
            if(h==k)
           else if(h>k)
                for(int i=0;i<p;i++)
                    bb1="0"+bb1;
                System.out.println("new value of first=" +bb1);   
        else if(h<k)
            for(int i=0;i<q;i++)
                bb2="0"+bb2;
            System.out.println("new value of second=" +bb2);
            StringBuffer sb1=new StringBuffer(bb1);
         StringBuffer sb2=new StringBuffer(bb2);
            bb1=sb1.reverse().toString();
         bb2=sb2.reverse().toString();
            //System.out.println("rev. buffer1=" +bb1);
            //System.out.println("rev. buffer2=" +bb2);
            for(int i=0;i<bb1.length();i++)
                ss1=bb1.substring(i,i+1);
                ss2=bb2.substring(i,i+1);
              System.out.println("value1=" + ss1 + "    " + "value2=" + ss2);
              if (ss1.equals("0") && ss2.equals("0")) 
                 if (carry.equals("0")) 
                     result+="0";
                        else
                            result+="1";
               else if (ss1.equals("1") && ss2.equals("1"))
                if (carry.equals("0")) 
                    result+="0";
              carry="1";
              else
                   result+="1";
                   carry="1";
        else if (ss1.equals("0") && ss2.equals("1"))
                     if (carry.equals("0")) 
                         result+="1";
                   carry="0";
                        else
                          result+="0";
                                    carry="1";
               else if (ss1.equals("1") && ss2.equals("0"))
                     if (carry.equals("0")) 
                        result+="1";
                        carry=" 0";
                   else
                                result+="0";
                                carry="1";
           System.out.println("sum=" +result + "         " + "carry" + carry);
                        result+=carry;
                        StringBuffer sb3=new StringBuffer(result);
                        result=sb3.reverse().toString();
                    System.out.println("result is " +result); 
                  System.out.println("Binary = "+ result + ", Decimal = "+Integer.parseInt(result,2));
    }

    bansal.s, you have been warned. I am now blocking your account for a month.

  • Check input  values are available in Hex

    how to check input values are available between 0x0000000000000001 to
    0xFFFFFFFFFFFFFFFE
    i am using following code. but error will come
    public boolean hexCheck16(String hex)
    String hex_min = "0x0000000000000001";
    String hex_max = "0xFFFFFFFFFFFFFFFE";
         int min1 = Integer.parseInt(hex_min.substring(2).toString(),16);
         int max2 = Integer.parseInt(hex_max.substring(2).toString(),16);
         int num = Integer.parseInt(hex.toString(), 16);
         if(num >= min1 & num <= max2)
         return true;
         else
         return false;
    Error is : java.lang.NumberFormatException: For input string: "FFFFFFFFFFFFFFFE"
    how to solve?

    Use BigInteger (and lose the "0x").

  • Creation of CMP bean for a Composite Primary key????

    Hi
    i am having a composite primary keys in one of my table in the database.
    I am trying to create a new entity bean for this table but i don't know how to create one in case when there is a composite primary key for a table.
    Can anybody let me know is it possible to do it.
    what is the procedure to be followed for the creation of the Entity bean in case of a composite primary key.
    I am using MySql as the database .Creating CMP type of Entity bean.
    Any help in this regard will be greatly useful to me as this is very urgent.
    Thanks & Regards
    Vikram K

    Hi Nikola,
    There are several problems with your CMP bean.
    1. Fields of a Primary Key Class must be a subset of CMP fields, so yes, they must be either a primitive or a Serializable type.
    2. Sun Application Server does not support Primary Key fields of an arbitrary Serializable type (i.e. those that will be stored
    as BLOB in the database), but only primitives, Java wrappers, String, and Date/Time types.
    Do you try to use stubs instead of relationships or for some other reason?
    If it's the former - look at the CMR fields.
    If it's the latter, I suggest to store these fields as regular CMP fields and use some other value as the PK. If you prefer that
    the CMP container generates the PK values, use the Unknown
    PrimaryKey feature.
    Regards,
    -marina

  • Converting a SecretKey

    Hi! can anyone help on how to convert a SecretKey format to an int then to String and back to int and String and lastly back to a SecretKey format?
    And, how to encrypt and decrypt a string instead of a file?

    A Key isn't an integer - it's a sequence of bytes, and it's often too big to fit into an int. Even if it does fit into one of the primitive types, in order to do things like encode it as a String and rebuild Key objects from it, you're going to want to treat it as a byte[].
    You could use BigInteger to do your operations on the Key. Try something like this:Key myKey = .....;
    byte[] myKeyBytes = myKey.getEncoded();
    BigInteger myKeyAsInt = new BigInteger( myKeybytes );
    // Do arithmetic on your key here
    String myKeyBase64 = Base64.encode( myKeyAsInt.toByteArray() );
    // send key elsewhere; upon receipt, do:
    byte[] newBigIntBytes = Base64.decode(myKeyBase64);
    BigInteger newKeyAsBigInt = new BigInteger(newBigIntBytes);
    // undo your arithmetic here
    byte[] newKeyBytes = newKeyAsBigInt.toByteArray();
    EncodedKeySpec newKeySpec = new EncodedKeySpec(newKeyBytes);
    Key myKey = KeyFactory.getInstance(myAlgorithm).generateSecret(newKeySpec);You need to fill in some blanks here, obviously - but this shows the approach. Note that "Base64" isn't a standard part of Java - do a web-search and you'l find a bunch of available implementations, tho.
    Note that you need to be REALLY CAREFUL doing math on keys. If you do something that isn't reversible, there's no way to get your original key back.
    Regarding this:
    i got the key from the DES algorithm, so it's in HEX form right?No - it's a stream of bytes. You can print it in hex, if you like. In Java, it's an Object (a SecretKey), and you need to use getEncoded() to get it in byte[] form.
    Good luck,
    Grant

Maybe you are looking for

  • Battery Doesn't Hold Charge: Less than Three Months Old!!

    I got an iPod touch on June 28. Everything was working fine up until yesterday. I was transferring a bunch of new music onto it on Friday night, around 7–8 PM. By the end of it, around 8–9 PM the iPod was fully charged. I unplugged it and went to sle

  • Rename custom list 2013 accessed by another custom list

    When I am working with 2 custom lists in SharePoint 2013, listb refers to select columns in lista by using a lookup column in lista. I accidently changed the name of custom list #1. Due to that fact, I went into the list settings and selected the col

  • Noobish "efficiency" question on DataOutputStream

    So, I currently have this: byte[] buf = some_bytes; DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeInt(buf.length); out.write(buf);I've always thought that calling write(byte[]) and any given OutputStream will be "eff

  • BC4J examples

    Hi, I've tried to start the BC4J order entry example. I'm working with JDeveloper 3.2.2 and Oracle DB 8.1.7. on NT. The deploying goes fine and locally it is possible to test. But when try to start the example under Middle Tier Server Type EJB I get

  • App Store for Mac

    Im running Leopard 10.5.8 on a Powerbook G4 and cannot get the app store update. Can anyone help?