Graphics.ROP throws IllegalArgumentException

I'm an IllegalArgumentException (with null backtrace and message) when I do the following in the paint for a custom field method:

g.ROP (Graphics.ROP_SRCMONOEXPAND_COPY, x, y, FONT_CHAR_WIDTH, FONT_CHAR_HEIGHT, font_, left, top);

However, the following works (though without the colorization, I want):

g.drawBitmap (x, y, FONT_CHAR_WIDTH, FONT_CHAR_HEIGHT, font_, left, top);

font_ is a Bitmap loaded from a custom PNG (a monospace font) file. I use the Eclipse plugin and a 4.5.0 Simulator. ROP() worked from 4.2 and 4.5 API documentation made no mention that he has changed since then. ROP_SRCMONOEXPAND_COPY is not obsolete, is it?

Does anyone have insight into this? Thanks in advance.

Never mind, you were right - the file PNG itself stores 1 bit per pixel, but for some reason Bitmap.getBitmapResource () that converts a bitmap with 16 bits per pixel. The documentation for Graphics.rop () does not indicate that there is a problem, and indeed it works when compiled with the 4.2 API on devices physical time 8830 and 9000. When I give a 1-bit Bitmap to Graphics.rop (), it works with ROP_SRCMONOEXPAND_COPY.

RIM, please update the documentation of the JDE to tell API Graphics.rop () is no longer can use any image, and it will throw an IllegalArgumentException if he dislikes the Bitmap image, he is given.

Tags: BlackBerry Developers

Similar Questions

  • SimplePofContext::getClass C++ throws IllegalArgumentException

    Operating system: Win7 64-bit.
    Consistency: 3.7.1.1 (windows - x 86-vs2005) x 86 release

    We have created a number of classes serializable C++ consistency for our project which use the COH_REGISTER_MANAGED_CLASS mechanism in their respective folders in the CPP.

    These worked very well for months using 3.7.1.0 consistency, as has our unit test the application. The application of test device falls down since the upgrade of coherence 3.7.1.1 (or higher). This call starts.

    + / / Throws IllegalArgumentException with 3.7.1.1 and over it, works very well with 3.7.1.0 +
    const coherence::Class:View =::io::pof::SystemPofContext::getInstance()-> getClass consistency vClass (1003);


    coherence::lang:IllegalArgumentException: unknown user type: 1003
    class coherence::lang:TypedHandle < class coherence::lang: Class const > _
    coherence::io:pof:SimplePofContext:getClass (int) const (SimplePofCon _thiscall
    Text.cpp:176)
    ... debugger may have to obtain the stack frames

    The problem is not specific to this type id (1003) happens for all our courses.

    Switch back to 3.7.1.0 it works again and returned a valid Class::View.

    Is this a known bug? Solutions of workaround/suggestions?


    Thank you.

    Hi DonLonDon,

    I think that what you see is a side effect of a bug fix which came in 3.7.1.1. The bug in question related to when it was safe to run the initialization code associated with things like macros COH_. Prior to p1, this was done as part of the static initialization C++ which is found to be dangerous in some environments. Beginning with 3.7.1.1 defer us initialization and lazily do it according to the needs and complete then any remaining initialization when consistency is first consulted, for example, you start using CacheFactory. I understand that for unit tests that could be problematic as you can test things that have nothing to do with the caches and thus CacheFactory. However, you can trigger the complete initialization manually if you like by calling coherence::lang:System:loadLibrary (NULL).

    Mark
    The Oracle coherence

  • BlackBerryContact.getAttributes return IllegalArgumentException

    I need to retrieve the labels of each number in the contact card:

    BlackBerryContact objBBContact = (BlackBerryContact) context;

    PIMList objPIMList = objBBContact.getPIMList ();

    int intCounter = objBBContact.countValues (BlackBerryContact.TEL);

    for (int i = 0; i)< intcounter;="">
    {

    ...

    strLabel = objPIMList.getAttributeLabel (objBBContact.getAttributes (BlackBerryContact.TEL, i));

    ...

    }

    The getAttributes throw IllegalArgumentException on the 'Mobile 2' field

    Thanks in advance

    It works on the last Simulator 4.7.1 BB 9630, maybe it's a bug in the BB 9000 Simulator.

  • Paint size problem police

    The use of this class:

    package net.berrysoft.dib.fields;
    
    import net.rim.device.api.ui.DrawStyle;
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.Font;
    import net.rim.device.api.ui.Graphics;
    
    public class MultiColumnTextField extends Field {
    
        public int      getBuffer( )            { return buffer; }
        public void     setBuffer( int buffer )     { this.buffer = buffer; }
        public int[ ]       getSpaces( )            { return spaces; }
        public void     setSpaces( int[ ] spaces )  { this.spaces = spaces; }
        public String[]     getColText()            { return colText; }
        public void     setColText( String[] text ) { colText = text; }
    
        public MultiColumnTextField( Object[] data ) throws IllegalArgumentException {
            this( data, Field.FOCUSABLE );
        }
    
        public MultiColumnTextField( Object[] data, int buffer ) throws IllegalArgumentException {
            this( data, buffer, Field.FOCUSABLE );
        }
    
        public MultiColumnTextField( Object[] data, long style ) throws IllegalArgumentException {
            this( data, 2, style | Field.FOCUSABLE );
        }
    
        public MultiColumnTextField( Object[] data, int buffer, long style ) throws IllegalArgumentException {
            super( style );
    
            //setFont( Font.getDefault( ).derive( Font.PLAIN, 40 ));
    
            int n = data.length;
    
            if ((n % 2) != 0) {
                throw new IllegalArgumentException("Invalid number of elements");
            } else {
                spaces  = new int[n/2];
                colText = new String[n/2];
            }
    
            for( int i = 0; i < n ; i = i + 2 ) {
                colText[i/2] = (String)data[i];
                spaces[i/2]  = ( (Integer)data[i+1] ).intValue();
            }
            this.buffer = buffer;
        }
    
        public void layout(int width, int height) {
            Font font = this.getFont( );
    
            int fieldWidth = 0;
            for ( int i = 0; i < spaces.length; ++i ) {
                fieldWidth += spaces[i];
                if ( i < spaces.length-1 ) {
                    fieldWidth += buffer;
                }
            }
            setExtent( fieldWidth, font.getHeight() );
        }
    
        public void paint( Graphics g ) {
            int xpos = 0;
    
            for ( int i = 0; i < spaces.length; ++i ) {
                g.drawText( colText[i], xpos, 0, DrawStyle.ELLIPSIS, spaces[i] );
                xpos += spaces[i];
                if ( i < spaces.length-1 ) {
                    xpos += buffer;
                }
            }
        }
    
        // PRIVATE IMPLEMENTATION
    
        private int         buffer;         // Space between each column
        private int[]       spaces;         // Number of spaces allocated to column
        private String[]    colText;        // Array of column text
    
    }
    

    I have create a dialogue that, as one of these fields with the test code, like this:

          Object[] fieldData1 = {
                    "Buddah", new Integer(NAME_COLS),
                    "81", new Integer(SCORE_COLS),
            };
            dm.add( new MultiColumnTextField( fieldData1, 2, Field.FOCUSABLE ) );
    

    But while the field height resulting seems correct, the painted 'text' seems to be very tiny boxes (as the police is too small).  But even if I Uncomment the line in the constructor that explicitly defines a larger font, there is no effect.

    Can anyone see what I'm doing wrong?

    Patrick

    The value of width that you specify in the drawText method is too small and the text is be cropped.

    You can use the Font.getAdvance method to determine the width of a text string.

  • Plain AES using

    Hi all

    I have to use AESEncryptorEngine.encrypt () to encrypt data using the AES algorithm. But the times when I have try it, BB throws IllegalArgumentException. There is no detailed in the exception message and stacktrace.

    I've seen examples where CBCEncryptorEngine & operated PKCS5FormatterEngine with AESEncryptorEngine. It works fine, but I need to use only the AES and without fill.

    What is the wrokaround for this?

    Can you suggest me some third party encryption library. I tried the J2Me of Bouncy Castle version, it is not compiling in BB.

    Thank you.

    I think the problem here is plain and encrypted text must match the length of the block for the algorithm.  So do both these 16 bytes and do this test one another.

  • problem during decryption of password encrypted

    Hello to all that I am saving the password encrypted in the database. And decrypting the password attached to the url. But while I'm decrypting it gives me the Exception BadPadding exception. I used this class to encrypt and decrypt the password.

    public class CryptAes {
    
        // First create the AES key based on the bytes in secretKey using  keyLength bits as the length
        static AESKey keydec = new AESKey("A3$1E*81234567891111111111111111".getBytes() );
        static AESKey keyenc = new AESKey("A3$1E*81234567891111111111111111".getBytes() );
        static AESKey keyenc128 = new AESKey("A3Q1EF8123456789".getBytes());
        static AESKey keydec128 = new AESKey("A3Q1EF8123456789".getBytes());
    
        private static byte[] iv = { 0x0a, 0x01, 0x02, 0x03, 0x04, 0x0b, 0x0c,
            0x0d, 0x0a, 0x01, 0x02, 0x03, 0x04, 0x0b, 0x0c, 0x0d };
    
        public static byte[] plainText= new byte[10000];
    
     public static String AESEncryption(byte[] plainText) {
    
            String resultString = null;
    
            try {
    
                 AESEncryptorEngine engine = new AESEncryptorEngine( keyenc128 );
    
                 CBCEncryptorEngine cengine=new CBCEncryptorEngine(engine, new InitializationVector(iv));
                    PKCS5FormatterEngine fengine = new PKCS5FormatterEngine( engine );
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    BlockEncryptor encryptor = new BlockEncryptor( fengine, output );
    
                    encryptor.write(plainText);
                    encryptor.close();
                    byte[] encryptedData = output.toByteArray(); output.close();
                    String st=new String(encryptedData);
    
                    byte[] base64 = Base64OutputStream.encode(encryptedData, 0, encryptedData.length, false, false);
    
                          //Base64Coder.encodeString(Byte.toString(plainText));
                          resultString = new String(base64);
    
            } catch (CryptoException cryptoException) {
                // TODO: handle exception
                System.out.println("Exception is "+cryptoException.getMessage()+"And the exception is"+cryptoException.toString());
            }
            catch (CryptoTokenException e) {
                // TODO: handle exception
                System.out.println("Exception is "+e.getMessage()+"And the exception is"+e.toString());
            }catch (CryptoUnsupportedOperationException e) {
                // TODO: handle exception
                System.out.println("Exception is "+e.getMessage()+"And the exception is"+e.toString());
            }catch (IOException e) {
                // TODO: handle exception
                System.out.println("Exception is "+e.getMessage()+"And the exception is"+e.toString());
            }
            return resultString;
      }
    
        public static String AESDecryption(byte[] cipherText, int dataLength ) /*throws CryptoException, IOException, CryptoTokenException, CryptoUnsupportedOperationException*/ {      
    
            String reString = null;
            try {
    
                ByteArrayInputStream in = new ByteArrayInputStream( cipherText, 0, dataLength );
    
                // Now create the block decryptor and pass in a new instance
                // of an AES decryptor engine with the specified block length
                BlockDecryptor cryptoStream = new BlockDecryptor(new AESDecryptorEngine( keydec128 ), in );
                byte[] T = new byte[dataLength];
    
                // Read the decrypted text from the AES decryptor stream and
                // return the actual length read        
    
                int length = cryptoStream.read( T ); //Here i am getting exception BadPadding
                reString = new String(T);
                int i=reString.indexOf("");
                reString = reString.substring(0,i+6);      
    
            } catch (CryptoException e) {
                // TODO: handle exception
                System.out.println("Exception is ="+e.getMessage());
            }catch (CryptoTokenException e) {
                // TODO: handle exception
                System.out.println("Exception is ="+e.getMessage());
            }catch (CryptoUnsupportedOperationException e) {
                // TODO: handle exception
                System.out.println("Exception is ="+e.getMessage());
            }catch (IOException e) {
                // TODO: handle exception
                System.out.println("Exception is ="+e.getMessage()+"333333333333"+e.toString());
            }
            // Create the input stream based on the ciphertext        
    
            return reString;
    
        }
    

    Help me with this.

    I was trying to encrypt and decipher passing on it but only has failed, so I just change how to encrypt or to decrypt the password. I had just use Base64Coder class to achieve this. And thank you for your concern. And here is the Base64Coder class, if someone needs it.

    //Copyright 2003-2009 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
    //www.source-code.biz, www.inventec.ch/chdh
    //
    //This module is multi-licensed and may be used under the terms
    //of any of the following licenses:
    //
    //EPL, Eclipse Public License, http://www.eclipse.org/legal
    //LGPL, GNU Lesser General Public License, http://www.gnu.org/licenses/lgpl.html
    //AL, Apache License, http://www.apache.org/licenses
    //BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php
    //
    //Please contact the author if you need another license.
    //This module is provided "as is", without warranties of any kind.
    
    /**
    * A Base64
    * r/Decoder.
    *
    * 

    * This class is used to encode and decode data in Base64 format as described in RFC 1521. * *

    * Home page: http://www.source-code.biz">www.source-code.biz
    * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
    * Multi-licensed: EPL/LGPL/AL/BSD. * *

    * Version history:
    * 2003-07-22 Christian d'Heureuse (chdh): Module created.
    * 2005-08-11 chdh: Lincense changed from GPL to LGPL.
    * 2006-11-21 chdh:
    *   Method encode(String) renamed to encodeString(String).
    *   Method decode(String) renamed to decodeString(String).
    *   New method encode(byte[],int) added.
    *   New method decode(String) added.
    * 2009-07-16: Additional licenses (EPL/AL) added.
    * 2009-09-16: Additional license (BSD) added.
    */ public class Base64Coder { //Mapping table from 6-bit nibbles to Base64 characters. private static char[] map1 = new char[64]; static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } //Mapping table from Base64 characters to 6-bit nibbles. private static byte[] map2 = new byte[128]; static { for (int i=0; iin. * @return A character array with the Base64 encoded data. */ public static char[] encode (byte[] in, int iLen) { int oDataLen = (iLen*4+2)/3; // output length without padding int oLen = ((iLen+2)/3)*4; // output length including padding char[] out = new char[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++] & 0xff; int i1 = ip < iLen ? in[ip++] & 0xff : 0; int i2 = ip < iLen ? in[ip++] & 0xff : 0; int o0 = i0 >>> 2; int o1 = ((i0 & 3) << 4) | (i1 >>> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; } /** * Decodes a string from Base64 format. * @param s a Base64 String to be decoded. * @return A String containing the decoded data. * @throws IllegalArgumentException if the input is not valid Base64 encoded data. */ public static String decodeString (String s) { return new String(decode(s)); } /** * Decodes a byte array from Base64 format. * @param a Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException if the input is not valid Base64 encoded data. */ public static byte[] decode (String s) { return decode(s.toCharArray()); } /** * Decodes a byte array from Base64 format. * No blanks or line breaks are allowed within the Base64 encoded data. * @param in a character array containing the Base64 encoded data. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException if the input is not valid Base64 encoded data. */ public static byte[] decode (char[] in) { int iLen = in.length; if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iLen-1] == '=') iLen--; int oLen = (iLen*3) / 4; byte[] out = new byte[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++]; int i1 = in[ip++]; int i2 = ip < iLen ? in[ip++] : 'A'; int i3 = ip < iLen ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int o0 = ( b0 <<2) | (b1>>>4); int o1 = ((b1 & 0xf)<<4) | (b2>>>2); int o2 = ((b2 & 3)<<6) | b3; out[op++] = (byte)o0; if (op

  • BY buying getTransactionId() get set to zero

    Hello friends,

    I do to purchase the app. purchase of work id very well. but is problem when I use getTransactionId(). I get 0.

    my code is below.

    public boolean startPurchase() throws IllegalArgumentException,IllegalApplicationException,PaymentServerException, UserCancelException,PaymentException,AppWorldUpdateRequired  {
             PurchaseArgumentsBuilder arguments = new PurchaseArgumentsBuilder()
            .withDigitalGoodSku( digitalGoodSku )
            .withDigitalGoodName( digitalGoodName )
            .withMetadata( digitalGoodName )
            .withPurchasingAppName( "PushLegal" );
           System.out.println("***************startPurchase************************");
                 Purchase purchase= engine.purchase(arguments.build());
    
                 Dialog.alert("Transiction id:: "+purchase.getTransactionId());
                transactionId=purchase.getTransactionId();
                System.out.println("***************startPurchase retrn true************************");
                return true;
          }
    

    I get a value of 0 when I use the purchase.getTransactionID (); What should I do? like in years...

    Thank you and best regards,

    Ajay Patil.

    If indeed, you post your sales request, download from outside the sandbox and actually buy a digital camera, then you should receive a valid Transaction ID.

  • Insert Image in SQLite as ablob

    I have the database sqlite and work very well and I want to insert an Image in SQLite as ablob but I do not know how to insert and select anyone have any expline example or link this

    Thanks to advansed

    void createSongTablet()
            {
                 try
                 {
                     String DB_NAME = "SQLDatal";
                     String dbLocation = "/SDCard/databases/jaw/";
                     URI uri = URI.create(dbLocation + DB_NAME);
                     _db = DatabaseFactory.open(uri);
                     Statement st = _db.createStatement( "CREATE TABLE 'songd' ( " +
                                                       "'songId' INTEGER," +
                                                       "'songName' varchar(255), " +
                                                       "'songNameAr' varchar(255), " +
                                                       "'singerId' INTEGER," +
                                                       "'singerName' varchar(255), " +
                                                       "'singerNameAr' varchar(255), " +
                                                       "'albumId' INTEGER," +
                                                       "'albumName' varchar(255), " +
                                                       "'albumNameAr' varchar(255), " +
                                                       "'albumCategory' varchar(255)," +
                                                       "'albumCategoryAr' varchar(255)," +
                                                       "'albumcover' blob,"+
                                                       "'duration' varchar(255), " +
                                                       "'size' varchar(255)," +
                                                       "'byteSize' varchar(255)," +
                                                       "'videoClip' varchar(255)," +
                                                       "'price' varchar(255)," +
                                                       " 'orderDetailId' INTEGER," +
                                                       "'playlistId' INTEGER)" );
    
                     st.prepare();
                     st.execute();
                     st.close();
                     _db.close();
                 }
                 catch (final Exception e )
                 {         
    
                 }
            }
    
     void addSongD(int songId, String songName, String songNameAr, int singerId, String singerName, String singerNameAr,
                     int albumId, String albumName, String albumNameAr, String albumCategory, String albumCategoryAr,
                     byte[] albumCover, String duration, String trailer, String size, String byteSize, String videoClip, String lyrics, String price,
                     int orderDetailId,int playListId) throws IllegalArgumentException, MalformedURIException
            {
                 try
                    {
    
                        String DB_NAME = "SQLDatal";
                        String dbLocation = "/SDCard/databases/jaw/";
                        URI uri = URI.create(dbLocation + DB_NAME);
                        _db = DatabaseFactory.open(uri);
                        Statement statement = _db.createStatement("INSERT INTO songd VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                        statement.prepare();
                        statement.bind(1, songId);
                        statement.bind(2, songName);
                        statement.bind(3, songNameAr);
                        statement.bind(4, singerId);
                        statement.bind(5, singerName);
                        statement.bind(6, singerNameAr);
                        statement.bind(7, albumId);
                        statement.bind(8, albumName);
                        statement.bind(9, albumNameAr);
                        statement.bind(10, albumCategory);
                        statement.bind(11, albumCategoryAr); statement.bind(12, albumCover);
                        statement.bind(13, duration);
                        //statement.bind(14, trailer);
                        statement.bind(14, size);
                        statement.bind(15, byteSize);
                        statement.bind(16, videoClip);
                       // statement.bind(18, lyrics);
                        statement.bind(17, price);
                        statement.bind(18, orderDetailId);
                        statement.bind(19, playListId);
                        statement.execute();
                        statement.close();
                        _db.close();
                    }
                    catch(final DatabaseException dbe)
                    {   
    
                    }         
    
            }
    
  • the value of the digital inputs to change the field

    Hi all

    I have an edit field that has a digital text filter that only accepts phone numbers. Users have the choice to load these numbers from address book or direct entry.

    I used the digital filter to allow only numbers. .

    But when I tried to load these address book.  with editField.setText (phoneNum); It is to throw IllegalArgumentException.

    How to set digital inputs to the editField?

    Hi thanks for all your entries!

    My issued are resolved. I used BasicEditField aulieude EditField to solve this problem. the basicedit field allows the digital text and it solved the problem.

    Thanks for all your interest...

  • Format a decimal number (#, #. #)

    Hello

    I'm doing something pretty simple using the RIM Blackberry APIs - I have a "1000000" string, I want to put in the form of "1 000 000,00.

    I tried the two classes of the RIM API to do this, but none of them have what I actually need:

    1. javax.microedition.global.Formatter

    String value = "1000000";
    float floatValue = Float.parseFloat(value);
    Formatter f = new Formatter(); //also tried with locale specified - Formatter("en")
    String result = f.formatNumber(floatValue, 2);
    

    The result variable is "1000000.00" - there decimal and group separators (comma) is missing.

    2 net.rim.device.api.i18n.MessageFormat (claims to be compatible with in the standard Java edition java.text.MessageFormat)

    String value = "1000000";
    Object[] objs = {value};
    
    MessageFormat mfPlain = new MessageFormat("{0}");
    MessageFormat mfWithFormat = new MessageFormat("{0,number,###,###.##}");
    
    String result1 = mfPlain.format(objs)
    String result2 = mfWithFormat.format(objs)
    

    performance(1): (what mfWithFormat disabled) gives me just a simple '1000000' (as expected, but useless).

    Result2: throws IllegalArgumentException.

    At this point, I am out of options what to try next...

    Any suggestions?

    Thank you

    Mike



    This is a parser issue that I wrote, it was written rather quickly, so there may be a few bugs, but it's a start

    String parsedNumber = formatNumber(1000.8565857559583, 3, ",");
    

    the parsedNumber will be set to '1,000.857 '.

       public static String formatNumber(double number, int decimals, String digitGrouping){
            Formatter f = new Formatter("en");
            String rawNumber = f.formatNumber(number, decimals+1);
    
            String rawIntString = rawNumber.substring(0, rawNumber.indexOf(".")); //Basically intString without digit grouping
            StringBuffer intString = new StringBuffer();
            StringBuffer decString = new StringBuffer(rawNumber.substring(rawNumber.indexOf(".")+1));
            StringBuffer formattedNumber = new StringBuffer();
            int workingVal = 0;
            int newNum = 0;
            boolean roundNext;
    
            //Add digit grouping
            int grouplen = 0;
            int firstDigit;
            if(rawIntString.charAt(0) == '-'){
                firstDigit = 1;
            }else{
                firstDigit = 0;
            }
            for(int n=rawIntString.length()-1;n>=firstDigit;n--){
                intString.insert(0, rawIntString.substring(n, n+1));
                grouplen++;
                if(grouplen == 3 && n>firstDigit){
                    intString.insert(0, digitGrouping);
                    grouplen = 0;
                }
            }
    
            //First, check the last digit
            workingVal = Integer.parseInt(String.valueOf(decString.charAt(decString.length()-1)));
            if(workingVal>=5){
                roundNext = true;
            }else{
                roundNext = false;
            }
            //Get the decimal values, round if needed, and add to formatted string buffer
            for(int n=decString.length()-2;n>=0;n--){
                workingVal = Integer.parseInt(String.valueOf(decString.charAt(n)));
                if(roundNext == true){
                    newNum = workingVal + 1;
                    if(newNum == 10){
                        roundNext = true;
                        newNum = 0;
                    }else{
                        roundNext = false;
                    }
                    formattedNumber.insert(0, newNum);
                }else{
                    formattedNumber.insert(0, workingVal);
                }
            }
            //Now get the integer values, round if needed, and add to formatted string buffer
            formattedNumber.insert(0, ".");
            for(int n=intString.length()-1;n>=0;n--){
                try{
                    workingVal = Integer.parseInt(String.valueOf(intString.charAt(n)));
                }catch(Exception e){
                    formattedNumber.insert(0, intString.charAt(n));
                    continue;
                }
                if(roundNext == true){
                    newNum = workingVal + 1;
                    if(newNum == 10){
                        roundNext = true;
                        newNum = 0;
                    }else{
                        roundNext = false;
                    }
                    formattedNumber.insert(0, newNum);
                }else{
                    formattedNumber.insert(0, workingVal);
                }
            }
    
            //Just in case its a number like 9999.99999 (if it rounds right to the end
            if(roundNext == true){
                formattedNumber.insert(0, 1);
    
            }   
    
            //re-add the minus sign if needed
            if(firstDigit == 1) formattedNumber.insert(0, rawIntString.charAt(0));
    
            if(digitGrouping.length() > 0){
                if(formattedNumber.toString().indexOf(".") == -1){
                    //no decimal
                    if(formattedNumber.toString().indexOf(digitGrouping) > 3+firstDigit){
                        formattedNumber.insert(1+firstDigit, digitGrouping);
                    }
    
                    if(formattedNumber.toString().length() == 4+firstDigit){
                        formattedNumber.insert(1+firstDigit, digitGrouping);
                    }
                }else{
                    //no decimal
                    if(formattedNumber.toString().indexOf(digitGrouping) > 3+firstDigit){
                        formattedNumber.insert(1+firstDigit, digitGrouping);
                    }
    
                    String intportion = formattedNumber.toString().substring(0, formattedNumber.toString().indexOf("."));
                    if(intportion.length() == 4+firstDigit){
                        formattedNumber.insert(1+firstDigit, digitGrouping);
                    }
                }
            }
    
            //now remove trailing zeros
            String tmp = formattedNumber.toString();
            int newLength = tmp.length();
            for(int n=tmp.length()-1;n>=0;n--){
                if(tmp.substring(n, n+1).equalsIgnoreCase("0")){
                    newLength--;
                }else{
                    if(tmp.substring(n, n+1).equalsIgnoreCase(".")) newLength--;
                    break;
                }
            }
            formattedNumber.setLength(newLength);
    
            return formattedNumber.toString();
        }
    
  • EditField problem!

    Hi every1

    I was faced with a problem when adding a text field on screen.

    When I'm trying to add a field for a GridFieldmanager editing, I m getting an EXCEPTION 'ILLEGALARGUMENT' and ending of app.

    Here I m using the object persistent 2 store text in of editfield

    Infact I m error, when I m 2 access the same screen twice, by train, but not in the first attempt. Initially I m 2 can access screen with success, but in my second attempt I m get error at the particular point dat dat

    Help me... Urgent!

    Concerning

    Kiran

    http://www.BlackBerry.com/developers/docs/6.0.0api/NET/rim/device/API/UI/component/BasicEditField.ht...

    Throws:
    IllegalArgumentException - if the text cannot be entered in an edit field.

    My guess would be that you have a filter set on the field and try to define a text that is in conflict with it, but without more information, it is difficult to say.

  • Logging class and LoggingPermission

    I have a question on logging and the code generated by NetBeans code completion.

    When you need to surround a piece of code with a try-catch block (see below) and do you this by leaving NetBeans to generate, the catch block inserts code using the logging class.  By default, this action adds also the necessary authorization for the project.  I guess I have to assign java.util.logging.LoggingPermission, but I don't know what values to put in other areas (see below) of the dialog box.  They are not the same as the other permissions that we put in this category.  I would also like to know where it is established if you know.

    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    

            try {
                recordStore = RecordStore.openRecordStore(storeName, true);
            } catch (RecordStoreException ex) {
                Logger.getLogger(RMSPersistentStore.class.getName()).log(Level.SEVERE, null, ex);
            }
    

    Under the project - Application Descriptor-> API permissions properties

    Authorization: java.util.logging.LoggingPermission

    Protected the name of the resource:

    Action requested:

    I'm curious to see how this logging works vs using System.out.println () or System.out.format ()...

    Thank you


    Brent S

    Thanks Trinity!

    I had actually read it, but I didn't quite connect the dots.

    public LoggingPermission (String name, String actions) throws IllegalArgumentException

    Parameters: name -the name of the permission. Must be 'control '. actions-Must be null or an empty string.

    When you set permissions for logging I was looking for Permission:, name of the protected resource:, & shares: with this designation by the dialog box fields.  I should have read more closely and extrapolated a little better!

    Thanks again,

    Brent S

  • simple method of max

    Hello

    I'm doing a simple method that returns the maximum element of an array of int. (I got this question on an interview.)
    I want to do it properly, so my question is what do I do if the table is null? Is there a common solution, best practices for this?
    Can I use try-catch block for NullPointerException or just an if-else?

    Also please tell me if my method is correct otherwise.

    Thank you!
         public static int max(int[] arr) {
    
              if (arr == null) {
                   ????  //System.out.println("array is null");
                   ????  //return Integer.MIN_VALUE;
              } else {
                   int temp = Integer.MIN_VALUE;
                   for (int i : arr) {
                        if (i > temp)
                             temp = i;
                   }
                   return temp;
              }
         }

    lemonboston wrote:
    Hello

    I'm doing a simple method that returns the maximum element of an array of int. (I got this question on an interview.)
    I want to do it properly, so my question is what do I do if the table is null? Is there a common solution, best practices for this?

    It depends on the specific context, but have no other details, I'd throw an IllegalArgumentException or NullPointerExcecption. I'd also throw IllegalArgumentException if the array has zero element.

    I certainly would NOT return any value unless the requirements specifically said that this is the desired behavior.

    Also please tell me if my method is correct otherwise.

    The loop to find the max value in the case of a valid table looks good. The only things I would change are:

    (1) rename the temp into something more meaningful, such as max or result.

    2) put braces around the temp = i body of the if (I > temp) test. They are not strictly necessary, but I (and most of the people I know) feel better to always use. Avoids confusion, makes it clear that you really don't want only this line in the body and prevents the error from adding more lines later and forget to add the braces.

  • Java stored procedure

    Hello

    I tried to register with the Java stored procedure and created a Java class for it. I am quite successful in compiling and executing the code using the Java compiler in Windows CMD, but I meet below error when I try to do the same thing via Java stored proc.
    PRAZY@orcl> CREATE OR REPLACE  FUNCTION WINREGREAD(REGKEY VARCHAR2,REGVALUE VARCHAR2) RETURN VARCHAR2
      2  AS
      3  LANGUAGE JAVA NAME 'WindowsRegistry.readString(java.lang.String,java.lang.String) return java.lang.String';
      4  /
    
    Function created.
    PRAZY@orcl> call winregread('Software\\MyApps','Test') into :mystring;
    call winregread('Software\\MyApps','Test') into :mystring
    *
    ERROR at line 1:
    ORA-29532: Java call terminated by uncaught Java exception: java.lang.NullPointerException
    
    
    Elapsed: 00:00:00.01
    PRAZY@orcl>
    Here's the Java code and its put
    //Uncomment the below like while compiling Java source in DB
    //CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "WinRegistry" AS
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.prefs.Preferences;
    public class WindowsRegistry {
      public static final int HKEY_CURRENT_USER = 0x80000001;
      public static final int HKEY_LOCAL_MACHINE = 0x80000002;
      public static final int REG_SUCCESS = 0;
      public static final int REG_NOTFOUND = 2;
      public static final int REG_ACCESSDENIED = 5;
      private static final int KEY_ALL_ACCESS = 0xf003f;
      private static final int KEY_READ = 0x20019;
      private static Preferences userRoot = Preferences.userRoot();
      private static Preferences systemRoot = Preferences.systemRoot();
      private static Class<? extends Preferences> userClass = userRoot.getClass();
      private static Method regOpenKey = null;
      private static Method regCloseKey = null;
      private static Method regQueryValueEx = null;
      static {
        try {
          regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey",
              new Class[] { int.class, byte[].class, int.class });
          regOpenKey.setAccessible(true);
          regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey",
              new Class[] { int.class });
          regCloseKey.setAccessible(true);
          regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx",
              new Class[] { int.class, byte[].class });
          regQueryValueEx.setAccessible(true);
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
      private WindowsRegistry() {  }
    
      public static String readString(String key, String valueName)
       throws IllegalArgumentException, IllegalAccessException,
        InvocationTargetException 
      {
    
        int hkey = HKEY_LOCAL_MACHINE;
          return readString(systemRoot, hkey, key, valueName);
      }
    
    private static String readString(Preferences root, int hkey, String key, String value)
    throws IllegalArgumentException, IllegalAccessException,
        InvocationTargetException 
      {
        try
    {
        int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
            new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
    
        if (handles[1] != REG_SUCCESS) {
          return null;
        }
        byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {
            new Integer(handles[0]), toCstr(value) });
        regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
        return (valb != null ? new String(valb).trim() : null);
    }
    catch (NullPointerException e)
    { 
    return e.getMessage();
    }
      }
    // utility
      private static byte[] toCstr(String str) {
        byte[] result = new byte[str.length() + 1];
        for (int i = 0; i < str.length(); i++) {
          result[i] = (byte) str.charAt(i);
        }
        result[str.length()] = 0;
        return result;
      }
    
    //Begin - Remove the following lines while compiling Java source in DB
    public static void main(String[] args) throws Exception 
      {
    String value = "";
    value = WindowsRegistry.readString("Software\\MyApps","Test");
        System.out.println("Reg key Value is: " +value);
      }
    //End
    
    };
    
    //Output
    d:\Java_Test>javac WindowsRegistry.java
    
    d:\Java_Test>java WindowsRegistry
    Reg key Value is: TEST VALUE
    
    -----------------------------------------------------------------------------
    
    Env. Details:
    =======
    Windows Vista 32 bit
    
    DB:
    ====
    BANNER
    --------------------------------------------------------------------------------
    Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production
    As you can see, I get my results when I run the same command prompt class, but encounter an error when it is executed from the DB.

    Also, I have granted permission to the runtime using DBMS_JAVA. Is there an any other permission problem?

    Kindly help and let me know if you need another entry.

    Thank you!

    Kind regards
    Prazy

    The Pref class is not supported in Oracle. So I used Java SP for BACK orders executed and calling in turn REG QUERY command.
    Tested with Windows 2003, Win XP and Win Vista (32-bit).

    PRAZY@orcl> select banner from v$version;
    
    BANNER
    --------------------------------------------------------------------------------
    Oracle Database 11g Release 11.1.0.6.0 - Production
    PL/SQL Release 11.1.0.6.0 - Production
    CORE     11.1.0.6.0     Production
    TNS for 32-bit Windows: Version 11.1.0.6.0 - Production
    NLSRTL Version 11.1.0.6.0 - Production                                                                                                                                                                                                                    
    
    Elapsed: 00:00:00.00
    PRAZY@orcl> CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "WindowsRegistry" AS
      2  import java.io.*;
      3  import java.lang.*;
      4
      5  public class WindowsRegistry {
      6
      7  public static String ReadKey(String key,String valueName)
      8  {
      9       String finalVal=null;
     10       String curVal=null;
     11       String command="reg query " + key + " /v " + valueName;
     12         try {
     13             // get runtime environment and execute child process
     14             Runtime systemShell = Runtime.getRuntime();
     15             Process output = systemShell.exec(command);
     16             // open reader to get output from process
     17             BufferedReader br = new BufferedReader (new InputStreamReader(output.getInputStream()));
     18             String line = null;
     19              while((line = br.readLine()) != null )
     20                  {
     21                 finalVal = curVal;
     22                      curVal = line;
     23                  }
     24                 output.waitFor();
     25            //get the value by calling findkeyval method
     26            finalVal=findKeyVal(finalVal.trim(),valueName);
     27             return finalVal;
     28             }
     29          catch (IOException ioe){ return "";}
     30          catch (Throwable t) { return "";}
     31  }
     32
     33  //Method to split the output and retrieve key value
     34  public static String findKeyVal(String keyLine,String valName)
     35  {
     36       String retVal="";
     37       String [] temp = null;
     38       temp = keyLine.split("\\s+");
     39       if (temp[0].equals(valName)) {
     40            for (int i=2; i CREATE OR REPLACE FUNCTION WinRegRead(keyPath varchar2,keyName varchar2) RETURN VARCHAR2
      2  AS
      3  LANGUAGE JAVA NAME 'WindowsRegistry.ReadKey(java.lang.String,java.lang.String) return java.lang.String';
      4  /
    
    Function created.
    
    Elapsed: 00:00:00.01
    PRAZY@orcl> var keyVal varchar2(50)
    PRAZY@orcl> print
    
    KEYVAL
    --------------------------------------------------------------------------------------------------------------------------------                                                                                                                          
    
    PRAZY@orcl> call WinRegRead('HKLM\Software\Oracle','inst_loc') into :keyVal;
    
    Call completed.
    
    Elapsed: 00:00:00.04
    PRAZY@orcl> print
    
    KEYVAL
    --------------------------------------------------------------------------------------------------------------------------------
    C:\Program Files (x86)\Oracle\Inventory                                                                                                                                                                                                                   
    

    Fact!

    I hope this might help someone!

    Kind regards
    Prazy

  • BUG + PATCH: SecondaryKeyCreator went from partial data

    If you put a DatabaseEntry containing only partial in a main database data, and this primary database has an associated secondary database, then when the secondary key is be recalculated the SecondaryKeyCreator is given to the same object of DatabaseEntry partial instead of a 'merged' new DatabaseEntry containing the new value of entire data updated.

    This is obviously unacceptable, because as a general rule, the secondary key may rely on all or part of the primary data, and the SecondaryKeyCreator must be able to see it all.

    The patch below fixes this (including some refactoring in order to eliminate duplication of code):
    diff -ur bdb/com/sleepycat/je/DatabaseEntry.java src/java/com/sleepycat/je/DatabaseEntry.java
    --- bdb/com/sleepycat/je/DatabaseEntry.java     2008-06-10 10:52:08.000000000 -0500
    +++ src/java/com/sleepycat/je/DatabaseEntry.java        2009-02-24 14:25:42.073159061 -0600
    @@ -470,4 +471,48 @@
             }
             return hash;
         }
    +
    +    /**
    +     * Merge this DatabaseEntry's partial data into the given existing data,
    +     * truncating or extending it as required.
    +     *
    +     * @param origdata buffer containing the original data; will not be modified by this method
    +     * @param origoffset offset of the original data in the origdata buffer
    +     * @param origlen length of the original data in the origdata buffer
    +     * @return the merge of the given data and this entry in a newly allocated buffer
    +     * @throws NullPointerException if origdata is null
    +     * @throws IllegalArgumentException if this entry is not partial
    +     */
    +    public byte[] mergeInto(byte[] origdata, int origoffset, int origlen) {
    +
    +        /* Check we're partial */
    +        if (!partial)
    +            throw new IllegalArgumentException("data is not partial");
    +
    +        /* Compute old and new lengths and allocate new buffer */
    +        int oldlen = (doff + dlen > origlen) ? doff + dlen : origlen;
    +        int len = oldlen - dlen + size;
    +        byte[] newData = new byte[len];
    +
    +        /* Keep 0..doff of the old data (truncating if doff > length) */
    +        int pos = 0;
    +        int slicelen = (doff < origlen) ? doff : origlen;
    +        if (slicelen > 0)
    +            System.arraycopy(origdata, origoffset, newData, pos, slicelen);
    +        pos += doff;
    +
    +        /* Copy in the new data */
    +        slicelen = size;
    +        System.arraycopy(data, offset, newData, pos, slicelen);
    +        pos += slicelen;
    +
    +        /* Append the rest of the old data (if any). */
    +        slicelen = origlen - (doff + dlen);
    +        if (slicelen > 0)
    +            System.arraycopy(origdata, origoffset + doff + dlen, newData, pos, slicelen);
    +
    +        /* Done */
    +        return newData;
    +    }
     }
    +
    diff -ur bdb/com/sleepycat/je/SecondaryDatabase.java src/java/com/sleepycat/je/SecondaryDatabase.java
    --- bdb/com/sleepycat/je/SecondaryDatabase.java 2008-06-10 10:52:08.000000000 -0500
    +++ src/java/com/sleepycat/je/SecondaryDatabase.java    2009-02-24 14:25:09.712446250 -0600
    @@ -713,6 +713,24 @@
                 return;
             }
    
    +        /*
    +         * Make sure we don't give partial data to the key creator.
    +         * Assume old data is not partial, but new data might be.
    +         */
    +        assert oldData == null || !oldData.getPartial();
    +        if (newData != null && newData.getPartial()) {
    +            if (oldData == null) {
    +                newData = new DatabaseEntry(newData.getData(),
    +                                            newData.getOffset(),
    +                                            newData.getSize());
    +            } else {
    +                byte[] buf = newData.mergeInto(oldData.getData(),
    +                                               oldData.getOffset(),
    +                                               oldData.getSize());
    +                newData = new DatabaseEntry(buf);
    +            }
    +        }
    +
             SecondaryKeyCreator keyCreator = secondaryConfig.getKeyCreator();
             if (keyCreator != null) {
                 /* Each primary record may have a single secondary key. */
    diff -ur bdb/com/sleepycat/je/dbi/CursorImpl.java src/java/com/sleepycat/je/dbi/CursorImpl.java
    --- bdb/com/sleepycat/je/dbi/CursorImpl.java    2008-05-20 11:27:34.000000000 -0500
    +++ src/java/com/sleepycat/je/dbi/CursorImpl.java       2009-02-24 14:38:38.524268376 -0600
    @@ -1275,50 +1275,17 @@
                 byte[] newData;
    
                 /* Resolve partial puts. */
    -            if (data.getPartial()) {
    -                int dlen = data.getPartialLength();
    -                int doff = data.getPartialOffset();
    -                int origlen = (foundDataBytes != null) ?
    -                    foundDataBytes.length : 0;
    -                int oldlen = (doff + dlen > origlen) ? doff + dlen : origlen;
    -                int len = oldlen - dlen + data.getSize();
    -
    -                if (len == 0) {
    -                    newData = LogUtils.ZERO_LENGTH_BYTE_ARRAY;
    -                } else {
    -                    newData = new byte[len];
    -                }
    -                int pos = 0;
    -
    -                /*
    -                 * Keep 0..doff of the old data (truncating if doff > length).
    -                 */
    -                int slicelen = (doff < origlen) ? doff : origlen;
    -                if (slicelen > 0)
    -                    System.arraycopy(foundDataBytes, 0, newData,
    -                                     pos, slicelen);
    -                pos += doff;
    -
    -                /* Copy in the new data. */
    -                slicelen = data.getSize();
    -                System.arraycopy(data.getData(), data.getOffset(),
    -                                 newData, pos, slicelen);
    -                pos += slicelen;
    -
    -                /* Append the rest of the old data (if any). */
    -                slicelen = origlen - (doff + dlen);
    -                if (slicelen > 0)
    -                    System.arraycopy(foundDataBytes, doff + dlen, newData, pos,
    -                                     slicelen);
    +            if (data.getPartial() && foundDataBytes != null) {
    +                newData = data.mergeInto(foundDataBytes, 0, foundDataBytes.length);
                 } else {
                     int len = data.getSize();
                     if (len == 0) {
                         newData = LogUtils.ZERO_LENGTH_BYTE_ARRAY;
                     } else {
                         newData = new byte[len];
    +                    System.arraycopy(data.getData(), data.getOffset(),
    +                                     newData, 0, len);
                     }
    -                System.arraycopy(data.getData(), data.getOffset(),
    -                                 newData, 0, len);
                 }
    
                 if (databaseImpl.getSortedDuplicates()) {

    You are right that it is a bug. Thank you for this comment! We will fix it in a future release.

    In the meantime I suggest to work around this by using only not a partial DatabaseEntry for methods put (), when secondary are associated with the primary database.

    Please note that using a partial DatabaseEntry for a method put () has the performance advantage very little and is very rarely used. This feature is included primarily for compatibility with the original edition of the BDB product C.

    -mark

Maybe you are looking for

  • T500 does not work - boot hangs on ThinkPad screen

    Hello, I have a thinkpad T500 T550 and was off for a few weeks and now I tried to turn it on, but it is in the first thinkpad screen (to interrupt normal startup...) does not start, but he isn't. I tried to start with the battery and battery, but the

  • Code of the product placed on the wrong profile

    I bought a game for windows live for myself, but I don't have a profile so I put it in the profile of my husband (who was his Xbox profile). When I realized that I could set up my own profile on windows live free, he wouldn't let me play the game on

  • OfficeJet 6500 a have MAC OS 10.5.8 - only prints in color.

    I just installed Officejet 6500 all-in-one has w / MAC OS 10.5.8.  All (MS Office 2008, Safari, Firefox, etc) print in color only.  Called support tech HP that does not support anything but text editing (there IS an option "print in black only" in th

  • What is the IP address of my IPS?

    I'm all new to this, thank you for reading my silly questions: p I have access to the cli of my asa5512. How do I access the my connected IPS cli? How to find the IP address of the IPS? # See the worms ... IPS module: Activated perpetual ...

  • Visual Studio Ultimate to 2012

    I downloaded Visual Studio Ultimate 2012 and installation ended at 1 a.m., but in the end, he confirmed that the "installation program. However, not all the features installed correctly. ' and 'Microsoft Web Deploy 3.0 - a certificate chain could not