Rectangle 27 55

Your best bet is to use a JDialog instead of a JFrame if you want to make the window modal. Check out details on the introduction of the Modality API in Java 6 for info. There is also a tutorial.

Here is some sample code which will display a JPanel panel in a JDialog which is modal to Frame parentFrame. Except for the constructor, this follows the same pattern as opening a JFrame.

final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);

Afraid that appears to be the only solution. I'm fighting this same problem with some inherited code. I've got a JFrame that I really need to be modal. Doing the work to convert it all to JDialog is really going to be ugly... :-(

Can you hack it through? Create an invisible, modal JDialog, make it instantiate the JFrame, and, when the JFrame is closed, capture the values if necessary, and close the JDialog

How to make a JFrame Modal in Swing java - Stack Overflow

java swing modal-dialog jframe
Rectangle 27 55

Your best bet is to use a JDialog instead of a JFrame if you want to make the window modal. Check out details on the introduction of the Modality API in Java 6 for info. There is also a tutorial.

Here is some sample code which will display a JPanel panel in a JDialog which is modal to Frame parentFrame. Except for the constructor, this follows the same pattern as opening a JFrame.

final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);

Afraid that appears to be the only solution. I'm fighting this same problem with some inherited code. I've got a JFrame that I really need to be modal. Doing the work to convert it all to JDialog is really going to be ugly... :-(

Can you hack it through? Create an invisible, modal JDialog, make it instantiate the JFrame, and, when the JFrame is closed, capture the values if necessary, and close the JDialog

How to make a JFrame Modal in Swing java - Stack Overflow

java swing modal-dialog jframe
Rectangle 27 55

Your best bet is to use a JDialog instead of a JFrame if you want to make the window modal. Check out details on the introduction of the Modality API in Java 6 for info. There is also a tutorial.

Here is some sample code which will display a JPanel panel in a JDialog which is modal to Frame parentFrame. Except for the constructor, this follows the same pattern as opening a JFrame.

final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);

Afraid that appears to be the only solution. I'm fighting this same problem with some inherited code. I've got a JFrame that I really need to be modal. Doing the work to convert it all to JDialog is really going to be ugly... :-(

Can you hack it through? Create an invisible, modal JDialog, make it instantiate the JFrame, and, when the JFrame is closed, capture the values if necessary, and close the JDialog

How to make a JFrame Modal in Swing java - Stack Overflow

java swing modal-dialog jframe
Rectangle 27 54

Your best bet is to use a JDialog instead of a JFrame if you want to make the window modal. Check out details on the introduction of the Modality API in Java 6 for info. There is also a tutorial.

Here is some sample code which will display a JPanel panel in a JDialog which is modal to Frame parentFrame. Except for the constructor, this follows the same pattern as opening a JFrame.

final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);

Afraid that appears to be the only solution. I'm fighting this same problem with some inherited code. I've got a JFrame that I really need to be modal. Doing the work to convert it all to JDialog is really going to be ugly... :-(

Can you hack it through? Create an invisible, modal JDialog, make it instantiate the JFrame, and, when the JFrame is closed, capture the values if necessary, and close the JDialog

How to make a JFrame Modal in Swing java - Stack Overflow

java swing modal-dialog jframe
Rectangle 27 8

  • Make constructor private and provide createInstance method with the same attributes as constructor or factory method ? How does it helps ?

Answer: making the constructor private and providing createInstance() (factory method) does not help by itself: it is one of few things you should do in order to allow users to actually use the class and its instances while you still have the control of the way instances are created.

  • Make attributes final - the post fails to explain this point and somewhere I read to avoid the modification accidentally. How can you modify accidentally, when there are no mutators and class is final ? How making an attribute final is helping ?

Answer: declaring a class as final means that the user can't extend it, so it "blocks" the user from this kind of "workaround". Declaring an attribute as final won't allow the user of the class to change it. It cannot be "modified accidentally", but it can be "modified viciously" using reflection. Let's see an example, say you have:

final public class SomeClass {
    final Integer i = 1;
}

from another class you can do as follows:

class AnotherClass {

    public static void main (String[] args) throws Exception {

        SomeClass p = new SomeClass();
        Field i =p.getClass().getDeclaredField("i");
        i.setAccessible(true);
        i.set(p, 5);
        System.out.println("p.i = " + p.i); // prints 5
    }
}

Answer: you can use the builder pattern or any pattern that helps you control the creation of instances of the class.

Further: If you want to make sure your class is immutable, make sure that any getter returns a deep-copy of the class member. This technique is called "protective/defensive copy". You can read more about it here

Good point about making class final. However if all fields are private subclasses cannot change the state of super class anyway. And (if it is relevant) making class final prevents us from mocking the class for tests and from creating proxies using libraries like CGLib or Javassist that can be a serious blocker. So, I personally think twice before making class final.

@AlexR good point; what's why it is recommendable to design against an interface rather than just a class

@morgano, typically we do not use interfaces when creating entity classes (like Person in my example). Although I agree with you that each class that contains business logic should implement interface that declares the contract.

@AlexR "However if all fields are private subclasses cannot change the state of super class anyway." - True! but... a malicious attacker may inherit your class and override the "getters" of the private members in order to provide his own "cooked" replacement-members which can be harmful (Joshua Bloch shows such an example with class Date in his book Effective Java). Of course that by declaring a class as final you're restricting yourself with Testing and such - that's part of the tradeof.

@alfasin, I see. Well, attacker can do everything. He can for example implement agent that removes final modifier from your class using byte code engineering technique (e.g. using ASM). But, you are right: this require much more serious effort.

immutability - How to make object immutable in java - Stack Overflow

java immutability
Rectangle 27 8

  • Make constructor private and provide createInstance method with the same attributes as constructor or factory method ? How does it helps ?

Answer: making the constructor private and providing createInstance() (factory method) does not help by itself: it is one of few things you should do in order to allow users to actually use the class and its instances while you still have the control of the way instances are created.

  • Make attributes final - the post fails to explain this point and somewhere I read to avoid the modification accidentally. How can you modify accidentally, when there are no mutators and class is final ? How making an attribute final is helping ?

Answer: declaring a class as final means that the user can't extend it, so it "blocks" the user from this kind of "workaround". Declaring an attribute as final won't allow the user of the class to change it. It cannot be "modified accidentally", but it can be "modified viciously" using reflection. Let's see an example, say you have:

final public class SomeClass {
    final Integer i = 1;
}

from another class you can do as follows:

class AnotherClass {

    public static void main (String[] args) throws Exception {

        SomeClass p = new SomeClass();
        Field i =p.getClass().getDeclaredField("i");
        i.setAccessible(true);
        i.set(p, 5);
        System.out.println("p.i = " + p.i); // prints 5
    }
}

Answer: you can use the builder pattern or any pattern that helps you control the creation of instances of the class.

Further: If you want to make sure your class is immutable, make sure that any getter returns a deep-copy of the class member. This technique is called "protective/defensive copy". You can read more about it here

Good point about making class final. However if all fields are private subclasses cannot change the state of super class anyway. And (if it is relevant) making class final prevents us from mocking the class for tests and from creating proxies using libraries like CGLib or Javassist that can be a serious blocker. So, I personally think twice before making class final.

@AlexR good point; what's why it is recommendable to design against an interface rather than just a class

@morgano, typically we do not use interfaces when creating entity classes (like Person in my example). Although I agree with you that each class that contains business logic should implement interface that declares the contract.

@AlexR "However if all fields are private subclasses cannot change the state of super class anyway." - True! but... a malicious attacker may inherit your class and override the "getters" of the private members in order to provide his own "cooked" replacement-members which can be harmful (Joshua Bloch shows such an example with class Date in his book Effective Java). Of course that by declaring a class as final you're restricting yourself with Testing and such - that's part of the tradeof.

@alfasin, I see. Well, attacker can do everything. He can for example implement agent that removes final modifier from your class using byte code engineering technique (e.g. using ASM). But, you are right: this require much more serious effort.

immutability - How to make object immutable in java - Stack Overflow

java immutability
Rectangle 27 0

this.v = new double[n];
this

this mean, current instance of NVector class. You can't assign a double array to any instance of NVector class.

this.v

java - How to make constructor initialize to all 0's? - Stack Overflow

java arrays constructor
Rectangle 27 0

public class Deck {

private String[] cards = new String[52];

       public Deck() {
         cards[0] = "AH";
         cards[1] = "2H";
         cards[2] = "3H";
         cards[3] = "4H";
         cards[4] = "5H";
         cards[5] = "6H";

            //and so on

       }
    }

You're constructing a local cards variable here, that's hiding the class member, so when the constructor completes, the class members cards element won't have changed.

It might help if the constructor initialises a class attribute instead of a variable with limited scope :-)

But how do I use the instance variable?

cards

java - How do I shuffle a deck? How do I make a string array construct...

java arrays
Rectangle 27 0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using System.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;

namespace BouncyCastleProject
{
    public class DesExample
    {
        // Encrypting or decrypting ?
        private bool encrypt = true;

        // To hold the initialised DESede cipher
        private PaddedBufferedBlockCipher cipher = null;

        // The input stream of bytes to be processed for encryption
        private Stream inStr = null;

        // The output stream of bytes to be procssed
        private Stream outStr = null;

        // The key
        private byte[] key = null;

        /*
        * start the application
        */
        //////public static void Main(string[] args)
        //////{
        //////    bool encrypt = true;
        //////    string infile = null;
        //////    string outfile = null;
        //////    string keyfile = null;

        //////    if (args.Length < 2)
        //////    {
        //////        //    Console.Error.WriteLine("Usage: java " + typeof(DesExample).Name + " infile outfile [keyfile]");
        //////        Console.Error.WriteLine("Usage: " + typeof(DesExample).Name + " infile outfile [keyfile]");
        //////        Environment.Exit(1);
        //////    }

        //////    keyfile = "deskey.dat";
        //////    infile = args[0];
        //////    outfile = args[1];

        //////    if (args.Length > 2)
        //////    {
        //////        encrypt = false;
        //////        keyfile = args[2];
        //////    }

        //////    DesExample de = new DesExample(infile, outfile, keyfile, encrypt);
        //////    de.process();
        //////}

        // Default constructor, used for the usage message
        public DesExample()
        {
        }

        /*
        * Constructor, that takes the arguments appropriate for
        * processing the command line directives.
        */
        public DesExample(
            string infile,
            string outfile,
            string keyfile,
            bool encrypt)
        {
            /* 
            * First, determine that infile & keyfile exist as appropriate.
            *
            * This will also create the BufferedInputStream as required
            * for reading the input file.  All input files are treated
            * as if they are binary, even if they contain text, it's the
            * bytes that are encrypted.
            */
            this.encrypt = encrypt;
            try
            {
                inStr = File.OpenRead(infile);
            }
            catch (FileNotFoundException)
            {
                //Console.Error.WriteLine("Input file not found [" + infile + "]");
                Environment.Exit(1);
            }

            try
            {
                outStr = File.Create(outfile);
            }
            catch (IOException)
            {
                //Console.Error.WriteLine("Output file not created [" + outfile + "]");
                Environment.Exit(1);
            }

            if (encrypt)
            {
                try
                {
                    /*
                    * The process of creating a new key requires a 
                    * number of steps.
                    *
                    * First, create the parameters for the key generator
                    * which are a secure random number generator, and
                    * the length of the key (in bits).
                    */
                    SecureRandom sr = new SecureRandom();

                    KeyGenerationParameters kgp = new KeyGenerationParameters(
                        sr, 
                        DesEdeParameters.DesEdeKeyLength * 8);

                    /*
                    * Second, initialise the key generator with the parameters
                    */

                    DesEdeKeyGenerator kg = new DesEdeKeyGenerator();
                    kg.Init(kgp);

                    /*
                    * Third, and finally, generate the key
                    */
                    key = kg.GenerateKey();

                    /*
                    * We can now output the key to the file, but first
                    * hex Encode the key so that we can have a look
                    * at it with a text editor if we so desire
                    */
                    Stream keystream = File.Create(keyfile);
                    byte[] keyhex = Hex.Encode(key);
                    keystream.Write(keyhex, 0, keyhex.Length);
                    keystream.Flush();
                    keystream.Close();
                }
                catch (IOException)
                {
                    //Console.Error.WriteLine("Could not decryption create key file [" + keyfile + "]");
                    Environment.Exit(1);
                }
            }
            else
            {
                try
                {
                    // TODO This block is a bit dodgy

                    // read the key, and Decode from hex encoding
                    Stream keystream = File.OpenRead(keyfile);
                    //     int len = keystream.available();
                    int len = (int)keystream.Length;
                    byte[] keyhex = new byte[len];
                    keystream.Read(keyhex, 0, len);
                    key = Hex.Decode(keyhex);
                }
                catch (IOException)
                {
                    //Console.Error.WriteLine("Decryption key file not found, or not valid [" + keyfile + "]");
                    Environment.Exit(1);
                }
            }
        }

        public void process()
        {
            /* 
            * Setup the DESede cipher engine, create a PaddedBufferedBlockCipher
            * in CBC mode.
            */
            cipher = new PaddedBufferedBlockCipher(
                new CbcBlockCipher(new DesEdeEngine()));

            /*
            * The input and output streams are currently set up
            * appropriately, and the key bytes are ready to be
            * used.
            *
            */

            if (encrypt)
            {
                performEncrypt(key);
            }
            else
            {
                performDecrypt(key);
            }

            // after processing clean up the files
            try
            {
                inStr.Close();
                outStr.Flush();
                outStr.Close();
            }
            catch (IOException)
            {
            }
        }

        /*
        * This method performs all the encryption and writes
        * the cipher text to the buffered output stream created
        * previously.
        */
        private void performEncrypt(byte[] key)
        {
            // initialise the cipher with the key bytes, for encryption
            cipher.Init(true, new KeyParameter(key));

            /*
            * Create some temporary byte arrays for use in
            * encryption, make them a reasonable size so that
            * we don't spend forever reading small chunks from
            * a file.
            *
            * There is no particular reason for using getBlockSize()
            * to determine the size of the input chunk.  It just
            * was a convenient number for the example.  
            */
            // int inBlockSize = cipher.getBlockSize() * 5;
            int inBlockSize = 47;
            int outBlockSize = cipher.GetOutputSize(inBlockSize);

            byte[] inblock = new byte[inBlockSize];
            byte[] outblock = new byte[outBlockSize];

            /* 
            * now, read the file, and output the chunks
            */
            try
            {
                int inL;
                int outL;
                byte[] rv = null;
                while ((inL = inStr.Read(inblock, 0, inBlockSize)) > 0)
                {
                    outL = cipher.ProcessBytes(inblock, 0, inL, outblock, 0);

                    /*
                    * Before we write anything out, we need to make sure
                    * that we've got something to write out. 
                    */
                    if (outL > 0)
                    {
                        rv = Hex.Encode(outblock, 0, outL);
                        outStr.Write(rv, 0, rv.Length);
                        outStr.WriteByte((byte)'\n');
                    }
                }

                try
                {
                    /*
                    * Now, process the bytes that are still buffered
                    * within the cipher.
                    */
                    outL = cipher.DoFinal(outblock, 0);
                    if (outL > 0)
                    {
                        rv = Hex.Encode(outblock, 0, outL);
                        outStr.Write(rv, 0, rv.Length);
                        outStr.WriteByte((byte)'\n');
                    }
                }
                catch (CryptoException)
                {

                }
            }
            catch (IOException ioeread)
            {
               // Console.Error.WriteLine(ioeread.StackTrace);
            }
        }

        /*
        * This method performs all the decryption and writes
        * the plain text to the buffered output stream created
        * previously.
        */
        private void performDecrypt(byte[] key)
        {
            // initialise the cipher for decryption
            cipher.Init(false, new KeyParameter(key));

            /* 
            * As the decryption is from our preformatted file,
            * and we know that it's a hex encoded format, then
            * we wrap the InputStream with a BufferedReader
            * so that we can read it easily.
            */
            //   BufferedReader br = new BufferedReader(new StreamReader(inStr));
            StreamReader br = new StreamReader(inStr); // 'inStr' already buffered

            /* 
            * now, read the file, and output the chunks
            */
            try
            {
                int outL;
                byte[] inblock = null;
                byte[] outblock = null;
                string rv = null;
                while ((rv = br.ReadLine()) != null)
                {
                    inblock = Hex.Decode(rv);
                    outblock = new byte[cipher.GetOutputSize(inblock.Length)];

                    outL = cipher.ProcessBytes(inblock, 0, inblock.Length, outblock, 0);
                    /*
                    * Before we write anything out, we need to make sure
                    * that we've got something to write out. 
                    */
                    if (outL > 0)
                    {
                        outStr.Write(outblock, 0, outL);
                    }
                }

                try
                {
                    /*
                    * Now, process the bytes that are still buffered
                    * within the cipher.
                    */
                    outL = cipher.DoFinal(outblock, 0);
                    if (outL > 0)
                    {
                        outStr.Write(outblock, 0, outL);
                    }
                }
                catch (CryptoException)
                {

                }
            }
            catch (IOException ioeread)
            {
                //Console.Error.WriteLine(ioeread.StackTrace);
            }
        }

    }
}

That's DES not AES...

c# - Documentation for Bouncy Castle AES 256 encryption in .Net? - Sta...

c# .net vb.net bouncycastle aes
Rectangle 27 0

/*
Fixed Point Arithmatic structure and relevant methods. Simple fixed point structure included as well.

Created from information and code gathered here: http://stackoverflow.com/questions/605124/fixed-point-math-in-c

May be used for anything without permission.

To quote the original author (x4000 of stackoverflow.com):
"The accuracy of these functions as they are coded here is more than enough for my purposes, but if you need more you can increase the SHIFT AMOUNT on FInt.
Just be aware that if you do so, the constants on [trigonomic] functions will then need to be divided by 4096 and then multiplied by whatever your new SHIFT AMOUNT requires.
You're likely to run into some bugs if you do that and aren't careful, so be sure to run checks against the built-in Math functions to make sure that your results aren't
being put off by incorrectly adjusting a constant."

Code credit: x4000 of stackoverflow.com

Compiled into a usable source file by: Paul Bergeron

Date: 7/1/2009

More fixed point functions can be found written in Java here: http://home.comcast.net/~ohommes/MathFP/

*/

public struct FInt
{
    public long RawValue;
    public const int SHIFT_AMOUNT = 12; //12 is 4096

    public const long One = 1 << SHIFT_AMOUNT;
    public const int OneI = 1 << SHIFT_AMOUNT;
    public static FInt OneF = new FInt( 1, true );

    #region Constructors
    public FInt( long StartingRawValue, bool UseMultiple )
    {
        this.RawValue = StartingRawValue;
        if ( UseMultiple )
            this.RawValue = this.RawValue << SHIFT_AMOUNT;
    }
    public FInt( double DoubleValue )
    {
        DoubleValue *= (double)One;
        this.RawValue = (int)Math.Round( DoubleValue );
    }
    #endregion

    public int IntValue
    {
        get { return (int)( this.RawValue >> SHIFT_AMOUNT ); }
    }

    public int ToInt()
    {
        return (int)( this.RawValue >> SHIFT_AMOUNT );
    }

    public double ToDouble()
    {
        return (double)this.RawValue / (double)One;
    }

    public FInt Inverse
    {
        get { return new FInt( -this.RawValue, false ); }
    }

    #region FromParts
    /// <summary>
    /// Create a fixed-int number from parts.  For example, to create 1.5 pass in 1 and 500.
    /// </summary>
    /// <param name="PreDecimal">The number above the decimal.  For 1.5, this would be 1.</param>
    /// <param name="PostDecimal">The number below the decimal, to three digits.
    /// For 1.5, this would be 500. For 1.005, this would be 5.</param>
    /// <returns>A fixed-int representation of the number parts</returns>
    public static FInt FromParts( int PreDecimal, int PostDecimal )
    {
        FInt f = new FInt( PreDecimal );
        if ( PostDecimal != 0 )
            f.RawValue += ( new FInt( PostDecimal ) / 1000 ).RawValue;

        return f;
    }
    #endregion

    #region *
    public static FInt operator *( FInt one, FInt other )
    {
        return new FInt( ( one.RawValue * other.RawValue ) >> SHIFT_AMOUNT, false );
    }

    public static FInt operator *( FInt one, int multi )
    {
        return one * (FInt)multi;
    }

    public static FInt operator *( int multi, FInt one )
    {
        return one * (FInt)multi;
    }
    #endregion

    #region /
    public static FInt operator /( FInt one, FInt other )
    {
        return new FInt( ( one.RawValue << SHIFT_AMOUNT ) / ( other.RawValue  ), false );
    }

    public static FInt operator /( FInt one, int divisor )
    {
        return one / (FInt)divisor;
    }

    public static FInt operator /( int divisor, FInt one )
    {
        return (FInt)divisor / one;
    }
    #endregion

    #region %
    public static FInt operator %( FInt one, FInt other )
    {
        return new FInt( ( one.RawValue ) % ( other.RawValue ), false );
    }

    public static FInt operator %( FInt one, int divisor )
    {
        return one % (FInt)divisor;
    }

    public static FInt operator %( int divisor, FInt one )
    {
        return (FInt)divisor % one;
    }
    #endregion

    #region +
    public static FInt operator +( FInt one, FInt other )
    {
        return new FInt( one.RawValue + other.RawValue, false );
    }

    public static FInt operator +( FInt one, int other )
    {
        return one + (FInt)other;
    }

    public static FInt operator +( int other, FInt one )
    {
        return one + (FInt)other;
    }
    #endregion

    #region -
    public static FInt operator -( FInt one, FInt other )
    {
        return new FInt( one.RawValue - other.RawValue, false );
    }

    public static FInt operator -( FInt one, int other )
    {
        return one - (FInt)other;
    }

    public static FInt operator -( int other, FInt one )
    {
        return (FInt)other - one;
    }
    #endregion

    #region ==
    public static bool operator ==( FInt one, FInt other )
    {
        return one.RawValue == other.RawValue;
    }

    public static bool operator ==( FInt one, int other )
    {
        return one == (FInt)other;
    }

    public static bool operator ==( int other, FInt one )
    {
        return (FInt)other == one;
    }
    #endregion

    #region !=
    public static bool operator !=( FInt one, FInt other )
    {
        return one.RawValue != other.RawValue;
    }

    public static bool operator !=( FInt one, int other )
    {
        return one != (FInt)other;
    }

    public static bool operator !=( int other, FInt one )
    {
        return (FInt)other != one;
    }
    #endregion

    #region >=
    public static bool operator >=( FInt one, FInt other )
    {
        return one.RawValue >= other.RawValue;
    }

    public static bool operator >=( FInt one, int other )
    {
        return one >= (FInt)other;
    }

    public static bool operator >=( int other, FInt one )
    {
        return (FInt)other >= one;
    }
    #endregion

    #region <=
    public static bool operator <=( FInt one, FInt other )
    {
        return one.RawValue <= other.RawValue;
    }

    public static bool operator <=( FInt one, int other )
    {
        return one <= (FInt)other;
    }

    public static bool operator <=( int other, FInt one )
    {
        return (FInt)other <= one;
    }
    #endregion

    #region >
    public static bool operator >( FInt one, FInt other )
    {
        return one.RawValue > other.RawValue;
    }

    public static bool operator >( FInt one, int other )
    {
        return one > (FInt)other;
    }

    public static bool operator >( int other, FInt one )
    {
        return (FInt)other > one;
    }
    #endregion

    #region <
    public static bool operator <( FInt one, FInt other )
    {
        return one.RawValue < other.RawValue;
    }

    public static bool operator <( FInt one, int other )
    {
        return one < (FInt)other;
    }

    public static bool operator <( int other, FInt one )
    {
        return (FInt)other < one;
    }
    #endregion

    public static explicit operator int( FInt src )
    {
        return (int)( src.RawValue >> SHIFT_AMOUNT );
    }

    public static explicit operator FInt( int src )
    {
        return new FInt( src, true );
    }

    public static explicit operator FInt( long src )
    {
        return new FInt( src, true );
    }

    public static explicit operator FInt( ulong src )
    {
        return new FInt( (long)src, true );
    }

    public static FInt operator <<( FInt one, int Amount )
    {
        return new FInt( one.RawValue << Amount, false );
    }

    public static FInt operator >>( FInt one, int Amount )
    {
        return new FInt( one.RawValue >> Amount, false );
    }

    public override bool Equals( object obj )
    {
        if ( obj is FInt )
            return ( (FInt)obj ).RawValue == this.RawValue;
        else
            return false;
    }

    public override int GetHashCode()
    {
        return RawValue.GetHashCode();
    }

    public override string ToString()
    {
        return this.RawValue.ToString();
    }

    #region PI, DoublePI
    public static FInt PI = new FInt( 12868, false ); //PI x 2^12
    public static FInt TwoPIF = PI * 2; //radian equivalent of 260 degrees
    public static FInt PIOver180F = PI / (FInt)180; //PI / 180
    #endregion

    #region Sqrt
    public static FInt Sqrt( FInt f, int NumberOfIterations )
    {
        if ( f.RawValue < 0 ) //NaN in Math.Sqrt
            throw new ArithmeticException( "Input Error" );
        if ( f.RawValue == 0 )
            return (FInt)0;
        FInt k = f + FInt.OneF >> 1;
        for ( int i = 0; i < NumberOfIterations; i++ )
            k = ( k + ( f / k ) ) >> 1;

        if ( k.RawValue < 0 )
            throw new ArithmeticException( "Overflow" );
        else
            return k;
    }

    public static FInt Sqrt( FInt f )
    {
        byte numberOfIterations = 8;
        if ( f.RawValue > 0x64000 )
            numberOfIterations = 12;
        if ( f.RawValue > 0x3e8000 )
            numberOfIterations = 16;
        return Sqrt( f, numberOfIterations );
    }
    #endregion

    #region Sin
    public static FInt Sin( FInt i )
    {
        FInt j = (FInt)0;
        for ( ; i < 0; i += new FInt( 25736, false ) ) ;
        if ( i > new FInt( 25736, false ) )
            i %= new FInt( 25736, false );
        FInt k = ( i * new FInt( 10, false ) ) / new FInt( 714, false );
        if ( i != 0 && i != new FInt( 6434, false ) && i != new FInt( 12868, false ) &&
            i != new FInt( 19302, false ) && i != new FInt( 25736, false ) )
            j = ( i * new FInt( 100, false ) ) / new FInt( 714, false ) - k * new FInt( 10, false );
        if ( k <= new FInt( 90, false ) )
            return sin_lookup( k, j );
        if ( k <= new FInt( 180, false ) )
            return sin_lookup( new FInt( 180, false ) - k, j );
        if ( k <= new FInt( 270, false ) )
            return sin_lookup( k - new FInt( 180, false ), j ).Inverse;
        else
            return sin_lookup( new FInt( 360, false ) - k, j ).Inverse;
    }

    private static FInt sin_lookup( FInt i, FInt j )
    {
        if ( j > 0 && j < new FInt( 10, false ) && i < new FInt( 90, false ) )
            return new FInt( SIN_TABLE[i.RawValue], false ) +
                ( ( new FInt( SIN_TABLE[i.RawValue + 1], false ) - new FInt( SIN_TABLE[i.RawValue], false ) ) /
                new FInt( 10, false ) ) * j;
        else
            return new FInt( SIN_TABLE[i.RawValue], false );
    }

    private static int[] SIN_TABLE = {
        0, 71, 142, 214, 285, 357, 428, 499, 570, 641,
        711, 781, 851, 921, 990, 1060, 1128, 1197, 1265, 1333,
        1400, 1468, 1534, 1600, 1665, 1730, 1795, 1859, 1922, 1985,
        2048, 2109, 2170, 2230, 2290, 2349, 2407, 2464, 2521, 2577,
        2632, 2686, 2740, 2793, 2845, 2896, 2946, 2995, 3043, 3091,
        3137, 3183, 3227, 3271, 3313, 3355, 3395, 3434, 3473, 3510,
        3547, 3582, 3616, 3649, 3681, 3712, 3741, 3770, 3797, 3823,
        3849, 3872, 3895, 3917, 3937, 3956, 3974, 3991, 4006, 4020,
        4033, 4045, 4056, 4065, 4073, 4080, 4086, 4090, 4093, 4095,
        4096
    };
    #endregion

    private static FInt mul( FInt F1, FInt F2 )
    {
        return F1 * F2;
    }

    #region Cos, Tan, Asin
    public static FInt Cos( FInt i )
    {
        return Sin( i + new FInt( 6435, false ) );
    }

    public static FInt Tan( FInt i )
    {
        return Sin( i ) / Cos( i );
    }

    public static FInt Asin( FInt F )
    {
        bool isNegative = F < 0;
        F = Abs( F );

        if ( F > FInt.OneF )
            throw new ArithmeticException( "Bad Asin Input:" + F.ToDouble() );

        FInt f1 = mul( mul( mul( mul( new FInt( 145103 >> FInt.SHIFT_AMOUNT, false ), F ) -
            new FInt( 599880 >> FInt.SHIFT_AMOUNT, false ), F ) +
            new FInt( 1420468 >> FInt.SHIFT_AMOUNT, false ), F ) -
            new FInt( 3592413 >> FInt.SHIFT_AMOUNT, false ), F ) +
            new FInt( 26353447 >> FInt.SHIFT_AMOUNT, false );
        FInt f2 = PI / new FInt( 2, true ) - ( Sqrt( FInt.OneF - F ) * f1 );

        return isNegative ? f2.Inverse : f2;
    }
    #endregion

    #region ATan, ATan2
    public static FInt Atan( FInt F )
    {
        return Asin( F / Sqrt( FInt.OneF + ( F * F ) ) );
    }

    public static FInt Atan2( FInt F1, FInt F2 )
    {
        if ( F2.RawValue == 0 && F1.RawValue == 0 )
            return (FInt)0;

        FInt result = (FInt)0;
        if ( F2 > 0 )
            result = Atan( F1 / F2 );
        else if ( F2 < 0 )
        {
            if ( F1 >= 0 )
                result = ( PI - Atan( Abs( F1 / F2 ) ) );
            else
                result = ( PI - Atan( Abs( F1 / F2 ) ) ).Inverse;
        }
        else
            result = ( F1 >= 0 ? PI : PI.Inverse ) / new FInt( 2, true );

        return result;
    }
    #endregion

    #region Abs
    public static FInt Abs( FInt F )
    {
        if ( F < 0 )
            return F.Inverse;
        else
            return F;
    }
    #endregion

}

public struct FPoint
{
    public FInt X;
    public FInt Y;

    public FPoint( FInt X, FInt Y )
    {
        this.X = X;
        this.Y = Y;
    }

    public static FPoint FromPoint( Point p )
    {
        FPoint f = new FPoint();
        f.X = (FInt)p.X;
        f.Y = (FInt)p.Y;
        return f;
    }

    public static Point ToPoint( FPoint f )
    {
        return new Point( f.X.IntValue, f.Y.IntValue );
    }
}

Thanks for code, but how to use that class, and why it so huge, in article which i commented: In binary arithmetic this can be accomplished using bit shifts is there any more shortest solution.

How to make multiplication with bit shift in C# - Stack Overflow

c# multiplication bit-shift
Rectangle 27 0

This is very easy to do with JMockit:

public class ClassUnderTestTest {
    interface SomeService { int doWork(); }

    class ClassUnderTest {
        private final SomeService service;

        ClassUnderTest() {
            service = new SomeService() {
                @Override public int doWork() { return -1; }
            };
        }

        int useTheService() { return service.doWork(); }
    }

    // This annotation is a variation on @Mocked, which extends
    // mocking to any implementation classes or subclasses of
    // the mocked base type.
    @Capturing SomeService mockService;

    @Test
    public void shouldBeAbleToMaskVariousNumbers() {
        new Expectations() {{ mockService.doWork(); result = 123; }};

        int n = new ClassUnderTest().useTheService();

        assertEquals(123, n);
    }
}

That was very easy indeed. Thank you very much for your inputs. I also learn the correct usage of the Capturing annotation. When I read the tutorial I havent paid much attention to this in the first place as I thought it may be used for capturing invocation data such as method parameters, etc. It seems to me I need to have another, this time more carefully, read of the jMockit tutorial. As for the exception I was getting, my silly mistake was I was setting an expectation on the ClassUnderTest constructor which was obviously wrong.

java - jMockit - How make constructor invocation to return a mock - St...

java mocking testng jmockit
Rectangle 27 0

<html>
  <head>
    <title>Test</title>
    <g:javascript src="jquery.js"/>
    <script type="text/javascript">
           $(function(){
            var fontSize = 16;

            // cannot store img.position().top or .left here because it is
            // before the browser has re-flowed the columns, therefore the
            // positions will be incorrect
            var imageTops = new Array;
            var imageLefts = new Array;

            $('#fontUp').click(function() {
                reflow(1);
            });

            $('#fontDown').click(function() {
                reflow(-1);
            });

            function reflow(fontSizeStep) {
                storeImagePositions();
                var fontLimitReached = changeFont(fontSizeStep);
                if (!fontLimitReached) {
         //           moveImages();
                }
                return false;
            }

            function changeFont(step) {
                fontSize += step;

                var fontSizeLimitReached = true;

                if (fontSize > 30) {
                    fontSize = 30;
                } else if (fontSize < 16) {
                    fontSize = 16;
                } else {
                    fontSizeLimitReached = false;
                }

                if (!fontSizeLimitReached) {
            //      alert(fontSize)
                    $('p').css({fontSize: fontSize + 'px'});
                }

                return fontSizeLimitReached;
            }

            // initialize store of img top and left positions
            function storeImagePositions() {
                if (imageTops.length == 0) { // only do it once
                    $('img').each(function() {
                        var imgPosition = $(this).position();

                        imageTops.push(imgPosition.top);
                        imageLefts.push(imgPosition.left);
                    });
                }
            }

            function moveImages() {
                // bye bye images
                var images = $('img').detach();

                // clear any existing marginTop added on the images
                images.each(function() {
                    $(this).css('marginTop', 0);
                });


                // spanify paragraphs
                $('#column > p').each(function() {
                    $(this).html('<span>' + $(this).html().replace(/\s\s+/g).replace(/(\s)/g,'</span>$1<span>') + '</span>');
                });

                var imageIndex = 0;

                // iterate words, working out where we can move the img to in the flow and if
                // we find a match, increment the index so that as we continue the each()
                // the next image is evaluated for replacement
                $('#column > p span').each(function() {
                    var wordPosition = $(this).position();
                    var wordLeft = wordPosition.left;

                    if (wordLeft >= imageLefts[imageIndex]) {
                        var wordBottom = wordPosition.top + $(this).height();

                        if (wordBottom > imageTops[imageIndex]) {
                            $(this).before(images[imageIndex]); // move img before this word
                            var newImgTop = $(images[imageIndex]).position().top;
                            $(images[imageIndex]).css({marginTop: imageTops[imageIndex] - newImgTop + 'px'});
                            imageIndex++; // increment index so remainder spans are being evaluated against the next image
                        }
                    }
                });

                // reverse the "spanification"
                $('#column > p').each(function() {
                    $(this).html($(this).html().replace(/<\\?span>/g, '').trim());
                });
            }
        });
    //]]>
    </script>
    <style type="text/css">
      div#column {
        margin-left:20px;
        -moz-column-width: 250px;
        -moz-column-gap: 20px;
        -webkit-column-width: 250px;
        -webkit-column-gap: 20px;
        height: 850px;
      }

      p {
        margin:0;
        clear:left;
        font-size:16px;
        text-align:justify;
      }

      img {
        float:left;
        margin-top: 2px;
        margin-right: 10px;
        position:fixed;
      }
    </style>
  </head>
  <body>
    <div><a href="#" id="fontUp" style="margin-right:10px">Font +</a><a href="#" id="fontDown">Font -</a></div>
    <div><img src="${createLinkTo(dir:'images',file:'Winter.jpg')}" height="250" width="660" id="image" title="yoda" alt="yoda"/></div>
          <div id="column" style="margin-top: 255px;">
            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            <p>The change of name from  LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion,  giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language. It has also been claimed that the language's name is the result of a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>
            <p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>
            <p>Java EE includes several API specifications, such as JDBC, RMI, e-mail, JMS, web services, XML, etc., and defines how to coordinate them. Java EE also features some specifications unique to Java EE for components. These include Enterprise JavaBeans, Connectors, servlets, portlets (following the Java Portlet specification), JavaServer Pages and several web service technologies. This allows developers to create enterprise applications that are portable and scalable, and that integrate with legacy technologies.  A Java EE application server can handle transactions, security, scalability, concurrency and management of the components that are deployed to it, in order to enable developers to concentrate more on the business logic of the components rather than on infrastructure and integration tasks.</p>
            <p>Java (Indonesian: Jawa) is an island of Indonesia. With a population of 136 million, it is the world's most populous island, and one of the most densely populated regions in the world. It is home to 60% of Indonesia's population. The Indonesian capital city, Jakarta, is in west Java.  Much of Indonesian history took place on Java; it was the centre of powerful Hindu-Buddhist empires, Islamic sultanates, the core of the colonial Dutch East Indies, and was at the centre of Indonesia's campaign for independence. The island dominates Indonesian social, political and economic life.</p>
            <p>Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. It can be used as a scripting language for the Java Platform.
              Groovy uses a Java-like bracket syntax. It is dynamically compiled to Java Virtual Machine (JVM) bytecode and interoperates with other Java code and libraries. Most Java code is also syntactically valid Groovy.</p>
            <p>Scala runs on the Java platform (Java Virtual Machine) and is compatible with existing Java programs. It also runs on Android smartphones. An alternative implementation exists for the .NET platform, but it has not been kept up to date.
              Scala has the same compilation model as Java and C# (separate compilation, dynamic class loading), so Scala code can call Java libraries (or .NET libraries in the .NET implementation).Scala's operational characteristics are the same as Java's. The Scala compiler generates byte code that is nearly identical to that generated by the Java compiler. In fact, Scala code can be decompiled to readable Java code, with the exception of certain constructor operations. To the JVM, Scala code and Java code are indistinguishable.</p>
          </div>
  </body>
</html>

Could you please post this as a new question, rather than an answer to the question above. It really is a separate question. Also, I'm not sure if there is a comment limit on a question but the comments section on my answer is getting very long and is in danger of being too long for anyone to bother reading.

jquery - Increase font size with JavaScript around fixed floated image...

javascript jquery html css ipad
Rectangle 27 0

There are lots of ways to handle this. Here's one way:

I don't care too much for the "Slot" class. This does nothing to help with the intersections between the clues.

When you look at a crossword puzzle, what do you see? I see a board of empty squares. Some have little numbers in the corners. I also see dark blocks I know I can't write in. I see a list of "down" clues, and a list of "across" clues.

No matter what I do, I write on that board of empty squares. So I'd make a grid-like class called Board that would allow me to write on it. The little number in some squares would be how specific words are indexed. The contents of each cell could be a space, a letter, or a -1 if the square isn't writable.

You might choose to implement a Square (or Cell) class. It would include a flag stating the instance's ability to be written to. It could include a number signifying the cell to which a clue applies. There are more elegant ways to do this. Implement this, and we can discuss more advanced class hierarchies.

The Board class would contain an NxN structure (probably an array) of Cell instances.

Another class would be called something like "Clues" that corresponds to the down or across list of clues. Clues includes a list of Clue instances.

Finally I'd have a Clue class where each instance includes an ID (the 15 in "15 down" for example), and the clue text to be displayed.

I think once you initialize the Board, you'll have all you need to make a nice crossword program.

I already know how to do all that, I was actually asking specifically about making a reference attribtues in each object (Square, Board) that changes when either reference attribute changes.

I suppose my answer is "don't do that". Select the entity that owns the value, and require all other entities to talk to this one to change the value.

Can you give me an example of how to do that though? Is that something an interface would do? Or do I have to use global/static variables?

I can help you through it. First, create the Cell or Square class. Per what I wrote above, methods should include "isWritable()" and "write(char letter)" at the very least. Note write() should fail if a value has been assigned that is different than letter - that would be a bogus intersection. Once you have this class, you'll them need a 2-D array of them. The array should live inside the Board class. A method in Board could be write(int id, char direction, String text). An example could would be aBoard.write(12, "down", "FROG");

And let Board figure out where "12 down" is located. So Board manages the placement of the text, and Square manages the actual value of one letter.

constructor - How to make multiple references to same object in Java -...

java constructor copy clone
Rectangle 27 0

If you don't specify a constructor in base class B and C, you will get the default constructor. This is a no parameter constructor provided by the runtime, and you can use it for any Object without an explicit constructor defined.

If you want to access a superclass constructor, you can do something like.

public A(String str, String str2, int num)
{
    super(str, str2, num);
}

Actually super was exactly what I was looking for at that thime

inheritance - Do I have to make constructors for all inherited classes...

java inheritance constructor
Rectangle 27 0

Generally, no, the constructors are not inherited. You'll have to redefine them in every subclass.

The exception to this is the implicit parameterless constructor that calls the parameterless constructor of the superclass, which is present if no other constructor is explicitly defined.

inheritance - Do I have to make constructors for all inherited classes...

java inheritance constructor
Rectangle 27 0

public class Deck {

private String[] cards = new String[52];

       public Deck() {
         cards[0] = "AH";
         cards[1] = "2H";
         cards[2] = "3H";
         cards[3] = "4H";
         cards[4] = "5H";
         cards[5] = "6H";

            //and so on

       }
    }

You're constructing a local cards variable here, that's hiding the class member, so when the constructor completes, the class members cards element won't have changed.

It might help if the constructor initialises a class attribute instead of a variable with limited scope :-)

But how do I use the instance variable?

cards

java - How do I shuffle a deck? How do I make a string array construct...

java arrays
Rectangle 27 0

This is very easy to do with JMockit:

public class ClassUnderTestTest {
    interface SomeService { int doWork(); }

    class ClassUnderTest {
        private final SomeService service;

        ClassUnderTest() {
            service = new SomeService() {
                @Override public int doWork() { return -1; }
            };
        }

        int useTheService() { return service.doWork(); }
    }

    // This annotation is a variation on @Mocked, which extends
    // mocking to any implementation classes or subclasses of
    // the mocked base type.
    @Capturing SomeService mockService;

    @Test
    public void shouldBeAbleToMaskVariousNumbers() {
        new Expectations() {{ mockService.doWork(); result = 123; }};

        int n = new ClassUnderTest().useTheService();

        assertEquals(123, n);
    }
}

That was very easy indeed. Thank you very much for your inputs. I also learn the correct usage of the Capturing annotation. When I read the tutorial I havent paid much attention to this in the first place as I thought it may be used for capturing invocation data such as method parameters, etc. It seems to me I need to have another, this time more carefully, read of the jMockit tutorial. As for the exception I was getting, my silly mistake was I was setting an expectation on the ClassUnderTest constructor which was obviously wrong.

java - jMockit - How make constructor invocation to return a mock - St...

java mocking testng jmockit
Rectangle 27 0

//BrowserField is available for 4.5 OS. RIM provide sample app for BrowserField Demo. you can find the sample example and run it.

    /*
 * BrowserFieldDemo.java 
 * 
 * Copyright  1998-2010 Research In Motion Ltd.
 * 
 * Note: For the sake of simplicity, this sample application may not leverage
 * resource bundles and resource strings.  However, it is STRONGLY recommended
 * that application developers make use of the localization features available
 * within the BlackBerry development platform to ensure a seamless application
 * experience across a variety of languages and geographies.  For more information
 * on localizing your application, please refer to the BlackBerry Java Development
 * Environment Development Guide associated with this release.
 */

package com.rim.samples.device.blackberry.browser;

import java.io.IOException;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.browser.field.*;
import net.rim.device.api.io.http.HttpHeaders;
import net.rim.device.api.system.Application;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.system.*;

/**
 * This sample application demonstrates how to create a web browser using the
 * net.rim.device.api.browser.field package.
 */
public final class BrowserFieldDemo extends UiApplication implements RenderingApplication 
{

    private static String REFERER = "referer";  

    private RenderingSession _renderingSession;   
    private HttpConnection  _currentConnection;
    private MainScreen _mainScreen;


    /**
     * Entry point for application
     * @param args Command line arguments (not used)
     */
    public static void main(String[] args) 
    {
        BrowserFieldDemo app = new BrowserFieldDemo();

        // Make the currently running thread the application's event
        // dispatch thread and begin processing events.
        app.enterEventDispatcher();
    }

    // Constructor
    public BrowserFieldDemo() 
    {       
        _mainScreen = new MainScreen();        
        pushScreen(_mainScreen);
        _renderingSession = RenderingSession.getNewInstance();

        // Enable javascript
        //_renderingSession.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID, RenderingOptions.JAVASCRIPT_ENABLED, true);                        

        PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread("http://www.google.com", null, null, null, this);
        thread.start();            
    }

    /**
     * Processes an http connection
     * 
     * @param connection The connection to the web content
     * @param e The event triggering the connection
     */
    void processConnection(HttpConnection connection, Event e) 
    {
        // Cancel previous request
        if (_currentConnection != null) 
        {
            try 
            {
                _currentConnection.close();
            } 
            catch (IOException e1) 
            {                
            }
        }

        _currentConnection = connection;

        BrowserContent browserContent = null;

        try 
        {
            browserContent = _renderingSession.getBrowserContent(connection, this, e);

            if (browserContent != null) 
            {
                Field field = browserContent.getDisplayableContent();

                if (field != null) 
                {
                    synchronized (Application.getEventLock()) 
                    {
                        _mainScreen.deleteAll();
                        _mainScreen.add(field);
                    }
                }

                browserContent.finishLoading();
            }

        } 
        catch (RenderingException re) 
        {
            Utilities.errorDialog("RenderingSession#getBrowserContent() threw " + re.toString());
        } 
        finally 
        {
            SecondaryResourceFetchThread.doneAddingImages();
        }

    }    

    /**
     * @see net.rim.device.api.browser.RenderingApplication#eventOccurred(net.rim.device.api.browser.Event)
     */
    public Object eventOccurred(Event event) 
    {
        int eventId = event.getUID();

        switch (eventId) 
        {
            case Event.EVENT_URL_REQUESTED : 
            {
                UrlRequestedEvent urlRequestedEvent = (UrlRequestedEvent) event;    

                PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(urlRequestedEvent.getURL(),
                                                                                         urlRequestedEvent.getHeaders(), 
                                                                                         urlRequestedEvent.getPostData(),
                                                                                         event, this);
                thread.start();

                break;

            } 
            case Event.EVENT_BROWSER_CONTENT_CHANGED: 
            {                
                // Browser field title might have changed update title.
                BrowserContentChangedEvent browserContentChangedEvent = (BrowserContentChangedEvent) event; 

                if (browserContentChangedEvent.getSource() instanceof BrowserContent) 
                { 
                    BrowserContent browserField = (BrowserContent) browserContentChangedEvent.getSource(); 
                    String newTitle = browserField.getTitle();
                    if (newTitle != null) 
                    {
                        synchronized (getAppEventLock()) 
                        { 
                            _mainScreen.setTitle(newTitle);
                        }                                               
                    }                                       
                }                   

                break;                

            } 
            case Event.EVENT_REDIRECT : 
            {
                RedirectEvent e = (RedirectEvent) event;
                String referrer = e.getSourceURL();

                switch (e.getType()) 
                {  
                    case RedirectEvent.TYPE_SINGLE_FRAME_REDIRECT :
                        // Show redirect message.
                        Application.getApplication().invokeAndWait(new Runnable() 
                        {
                            public void run() 
                            {
                                Status.show("You are being redirected to a different page...");
                            }
                        });

                    break;

                    case RedirectEvent.TYPE_JAVASCRIPT :
                        break;

                    case RedirectEvent.TYPE_META :
                        // MSIE and Mozilla don't send a Referer for META Refresh.
                        referrer = null;     
                        break;

                    case RedirectEvent.TYPE_300_REDIRECT :
                        // MSIE, Mozilla, and Opera all send the original
                        // request's Referer as the Referer for the new
                        // request.
                        Object eventSource = e.getSource();
                        if (eventSource instanceof HttpConnection) 
                        {
                            referrer = ((HttpConnection)eventSource).getRequestProperty(REFERER);
                        }

                        break;
                    }

                    HttpHeaders requestHeaders = new HttpHeaders();
                    requestHeaders.setProperty(REFERER, referrer);
                    PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(e.getLocation(), requestHeaders,null, event, this);
                    thread.start();
                    break;

            } 
            case Event.EVENT_CLOSE :
                // TODO: close the appication
                break;

            case Event.EVENT_SET_HEADER :        // No cache support.
            case Event.EVENT_SET_HTTP_COOKIE :   // No cookie support.
            case Event.EVENT_HISTORY :           // No history support.
            case Event.EVENT_EXECUTING_SCRIPT :  // No progress bar is supported.
            case Event.EVENT_FULL_WINDOW :       // No full window support.
            case Event.EVENT_STOP :              // No stop loading support.
            default :
        }

        return null;
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#getAvailableHeight(net.rim.device.api.browser.BrowserContent)
     */
    public int getAvailableHeight(BrowserContent browserField) 
    {
        // Field has full screen.
        return Display.getHeight();
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#getAvailableWidth(net.rim.device.api.browser.BrowserContent)
     */
    public int getAvailableWidth(BrowserContent browserField) 
    {
        // Field has full screen.
        return Display.getWidth();
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#getHistoryPosition(net.rim.device.api.browser.BrowserContent)
     */
    public int getHistoryPosition(BrowserContent browserField) 
    {
        // No history support.
        return 0;
    }


    /**
     * @see net.rim.device.api.browser.RenderingApplication#getHTTPCookie(java.lang.String)
     */
    public String getHTTPCookie(String url) 
    {
        // No cookie support.
        return null;
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#getResource(net.rim.device.api.browser.RequestedResource,
     *      net.rim.device.api.browser.BrowserContent)
     */
    public HttpConnection getResource( RequestedResource resource, BrowserContent referrer) 
    {
        if (resource == null) 
        {
            return null;
        }

        // Check if this is cache-only request.
        if (resource.isCacheOnly()) 
        {
            // No cache support.
            return null;
        }

        String url = resource.getUrl();

        if (url == null) 
        {
            return null;
        }

        // If referrer is null we must return the connection.
        if (referrer == null) 
        {
            HttpConnection connection = Utilities.makeConnection(resource.getUrl(), resource.getRequestHeaders(), null);

            return connection;

        } 
        else 
        {
            // If referrer is provided we can set up the connection on a separate thread.
            SecondaryResourceFetchThread.enqueue(resource, referrer);
        }

        return null;
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#invokeRunnable(java.lang.Runnable)
     */
    public void invokeRunnable(Runnable runnable) 
    {       
        (new Thread(runnable)).start();
    }
}

/**
 * A Thread class to fetch content using an http connection
 */
final class PrimaryResourceFetchThread extends Thread 
{    
    private BrowserFieldDemo _application;
    private Event _event;
    private byte[] _postData;
    private HttpHeaders _requestHeaders;
    private String _url;

    /**
     * Constructor to create a PrimaryResourceFetchThread which fetches the web
     * resource from the specified url.
     * 
     * @param url The url to fetch the content from
     * @param requestHeaders The http request headers used to fetch the content
     * @param postData Data which is to be posted to the url
     * @param event The event triggering the connection
     * @param application The application requesting the connection
     */
    PrimaryResourceFetchThread(String url, HttpHeaders requestHeaders, byte[] postData, Event event, BrowserFieldDemo application) 
    {
        _url = url;
        _requestHeaders = requestHeaders;
        _postData = postData;
        _application = application;
        _event = event;
    }

    /**
     * Connects to the url associated with this object
     * 
     * @see java.lang.Thread#run()
     */
    public void run() 
    {
        HttpConnection connection = Utilities.makeConnection(_url, _requestHeaders, _postData);
        _application.processConnection(connection, _event);        
    }
}

    /////////////////////////////////////////////////////////////////

    /*
 * SecondaryResourceFetchThread.java
 *
 * Copyright  1998-2010 Research In Motion Ltd.
 * 
 * Note: For the sake of simplicity, this sample application may not leverage
 * resource bundles and resource strings.  However, it is STRONGLY recommended
 * that application developers make use of the localization features available
 * within the BlackBerry development platform to ensure a seamless application
 * experience across a variety of languages and geographies.  For more information
 * on localizing your application, please refer to the BlackBerry Java Development
 * Environment Development Guide associated with this release.
 */

package com.rim.samples.device.blackberry.browser;

import java.util.Vector;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.browser.field.BrowserContent;
import net.rim.device.api.browser.field.RequestedResource;


/**
 * This class provides the ability to set up an http connection if a referrer 
 * exists (a browser making the request).
 */
class SecondaryResourceFetchThread extends Thread 
{

    /**
     * Callback browser field.
     */
    private BrowserContent _browserField;

    /**
     * Images to retrieve.
     */
    private Vector _imageQueue;

    /**
     * True is all images have been enqueued.
     */
    private boolean _done;

    /**
     * Sync object.
     */
    private static Object _syncObject = new Object();

    /**
     * Secondary thread.
     */
    private static SecondaryResourceFetchThread _currentThread;


    /**
     * Enqueues secondary resource for a browser field.
     * 
     * @param resource - resource to retrieve.
     * @param referrer - call back browsr field.
     */
    static void enqueue(RequestedResource resource, BrowserContent referrer) 
    {
        if (resource == null) 
        {
            return;
        }

        synchronized( _syncObject ) 
        {

            // Create new thread.
            if (_currentThread == null) 
            {
                _currentThread = new SecondaryResourceFetchThread();
                _currentThread.start();
            } 
            else 
            {
                // If thread alread is running, check that we are adding images for the same browser field.
                if (referrer != _currentThread._browserField) 
                {  
                    synchronized( _currentThread._imageQueue) 
                    {
                        // If the request is for a different browser field,
                        // clear old elements.
                        _currentThread._imageQueue.removeAllElements();
                    }
                }
            }   

            synchronized( _currentThread._imageQueue) 
            {
                _currentThread._imageQueue.addElement(resource);
            }

            _currentThread._browserField = referrer;
        }
    }

    /**
     * Constructor
     *
     */
    private SecondaryResourceFetchThread() 
    {
        _imageQueue = new Vector();        
    }

    /**
     * Indicate that all images have been enqueued for this browser field.
     */
    static void doneAddingImages() 
    {
        synchronized( _syncObject ) 
        {
            if (_currentThread != null) 
            {
                _currentThread._done = true;
            }
        }
    }

    /**
     * Connects to the requested resource
     * 
     * @see java.lang.Runnable#run()
     */
    public void run() 
    {
        while (true) 
        {
            if (_done) 
            {
                // Check if we are done requesting images.
                synchronized( _syncObject ) 
                {
                    synchronized( _imageQueue ) 
                    {
                        if (_imageQueue.size() == 0) 
                        {
                            _currentThread = null;   
                            break;
                        }
                    }
                }
            }

            RequestedResource resource = null;

            // Request next image.
            synchronized( _imageQueue ) 
            {
                if (_imageQueue.size() > 0) 
                {
                    resource = (RequestedResource)_imageQueue.elementAt(0);
                    _imageQueue.removeElementAt(0);
                }
            }

            if (resource != null) 
            {

                HttpConnection connection = Utilities.makeConnection(resource.getUrl(), resource.getRequestHeaders(), null);
                resource.setHttpConnection(connection);

                // Signal to the browser field that resource is ready.
                if (_browserField != null) 
                {            
                    _browserField.resourceReady(resource);
                }
            }
        }       
    }   

}

    ///////////////////////////////////////////////////////////////////

    /*
 * Utilities.java
 *
 * Copyright  1998-2010 Research In Motion Ltd.
 * 
 * Note: For the sake of simplicity, this sample application may not leverage
 * resource bundles and resource strings.  However, it is STRONGLY recommended
 * that application developers make use of the localization features available
 * within the BlackBerry development platform to ensure a seamless application
 * experience across a variety of languages and geographies.  For more information
 * on localizing your application, please refer to the BlackBerry Java Development
 * Environment Development Guide associated with this release.
 */

package com.rim.samples.device.blackberry.browser;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.http.HttpHeaders;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.util.StringUtilities;


/**
 * This class provides common functions required by the 
 * BrowserContentManagerDemo and BrowserFieldDemo. This class allows the
 * aforementioned classes to make a connection to a specified url.
 */
class Utilities 
{
    /**
     * Connect to a web resource
     * @param url The url of the resource
     * @param requestHeaders The request headers describing the connection to be made
     * @param postData The data to post to the web resource
     * @return The HttpConnection object representing the connection to the resource, null if no connection could be made
     */
    static HttpConnection makeConnection(String url, HttpHeaders requestHeaders, byte[] postData) 
    {
        HttpConnection conn = null;
        OutputStream out = null;

        try 
        {
            conn = (HttpConnection) Connector.open(url);           

            if (requestHeaders != null) 
            {
                // From
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3
                //
                // Clients SHOULD NOT include a Referer header field in a (non-secure) HTTP 
                // request if the referring page was transferred with a secure protocol.
                String referer = requestHeaders.getPropertyValue("referer");
                boolean sendReferrer = true;

                if (referer != null && StringUtilities.startsWithIgnoreCase(referer, "https:") && !StringUtilities.startsWithIgnoreCase(url, "https:")) 
                {             
                    sendReferrer = false;
                }

                int size = requestHeaders.size();
                for (int i = 0; i < size;) 
                {                    
                    String header = requestHeaders.getPropertyKey(i);

                    // Remove referer header if needed.
                    if ( !sendReferrer && header.equals("referer")) 
                    {
                        requestHeaders.removeProperty(i);
                        --size;
                        continue;
                    }

                    String value = requestHeaders.getPropertyValue( i++ );
                    if (value != null) 
                    {
                        conn.setRequestProperty( header, value);
                    }
                }                
            }                          

            if (postData == null) 
            {
                conn.setRequestMethod(HttpConnection.GET);
            } 
            else 
            {
                conn.setRequestMethod(HttpConnection.POST);

                conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(postData.length));

                out = conn.openOutputStream();
                out.write(postData);

            }
        } 
        catch (IOException e1) 
        {
            errorDialog(e1.toString());
        } 
        finally 
        {
            if (out != null) 
            {
                try 
                {
                    out.close();
                } 
                catch (IOException e2) 
                {
                    errorDialog("OutputStream#close() threw " + e2.toString());
                }
            }
        }    

        return conn;
    }

    /**
     * Presents a dialog to the user with a given message
     * @param message The text to display
     */
    public static void errorDialog(final String message)
    {
        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
            public void run()
            {
                Dialog.alert(message);
            } 
        });
    }
}

user interface - Embedded HTML control for Blackberry? - Stack Overflo...

html user-interface blackberry java-me custom-controls
Rectangle 27 0

public class NVector
{

Vector<Double> v = new Vector<Double>();

public Vector<Double> NVector(int n)
{

    for(int i = 0; i<n; i++)
    {
        v.add(i);

    }
    return v;

}

java - How to make constructor initialize to all 0's? - Stack Overflow

java arrays constructor
Rectangle 27 0

This is very easy to do with JMockit:

public class ClassUnderTestTest {
    interface SomeService { int doWork(); }

    class ClassUnderTest {
        private final SomeService service;

        ClassUnderTest() {
            service = new SomeService() {
                @Override public int doWork() { return -1; }
            };
        }

        int useTheService() { return service.doWork(); }
    }

    // This annotation is a variation on @Mocked, which extends
    // mocking to any implementation classes or subclasses of
    // the mocked base type.
    @Capturing SomeService mockService;

    @Test
    public void shouldBeAbleToMaskVariousNumbers() {
        new Expectations() {{ mockService.doWork(); result = 123; }};

        int n = new ClassUnderTest().useTheService();

        assertEquals(123, n);
    }
}

That was very easy indeed. Thank you very much for your inputs. I also learn the correct usage of the Capturing annotation. When I read the tutorial I havent paid much attention to this in the first place as I thought it may be used for capturing invocation data such as method parameters, etc. It seems to me I need to have another, this time more carefully, read of the jMockit tutorial. As for the exception I was getting, my silly mistake was I was setting an expectation on the ClassUnderTest constructor which was obviously wrong.

java - jMockit - How make constructor invocation to return a mock - St...

java mocking testng jmockit