Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, October 29, 2018

JVM languages

  • Domain-specific language
A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains.The line between general-purpose languages and domain-specific languages is not always sharp, as a language may have specialized features for a particular domain but be applicable more broadly, or conversely may in principle be capable of broad application but in practice used primarily for a specific domain. For example, Perl was originally developed as a text-processing and glue language, for the same domain as AWK and shell scripts, but was mostly used as a general-purpose programming language later on.
    http://en.wikipedia.org/wiki/Domain-specific_language
    • Apache Groovy is a powerful, optionally typed and dynamic language, with static-typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax. It integrates smoothly with any Java program, and immediately delivers to your application powerful features, including scripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming
    http://groovy-lang.org/
    • What is Scala 

    Scala is an object-oriented and functional programming language.
    Scala is a general-purpose programming language. It supports object-oriented, functional and imperative programming approaches.
    It is a strong static type language.
    In Scala, everything is an object whether it is a function or a number. It does not have the concept of primitive data.
    https://www.javatpoint.com/scala-tutorial


    • Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. 

    Scala smoothly integrates the features of object-oriented and functional languages.

    Scala, short for Scalable Language, is a hybrid functional programming language.
    Scala smoothly integrates the features of object-oriented and functional languages.
    Scala is compiled to run on the Java Virtual Machine.
    Many existing companies, who depend on Java for business critical applications, are turning to Scala to boost their development productivity, applications scalability and overall reliability.
    Scala is a pure object-oriented language in the sense that every value is an object.
    Classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritances.
    Scala is also a functional language in the sense that every function is a value and every value is an object so ultimately every function is an object.
    Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying.
    Scala, unlike some of the other statically typed languages (C, Pascal, Rust, etc.), does not expect you to provide redundant type information.
    You don't have to specify a type in most cases, and you certainly don't have to repeat it.
    Scala is compiled into Java Byte Code which is executed by the Java Virtual Machine (JVM).
    This means that Scala and Java have a common runtime platform.
    You can easily move from Java to Scala.
    Scala enables you to use all the classes of the Java SDK and also your own custom Java classes, or your favorite Java open source projects.
    It reduces the number of lines and helps the programmer to code in a type-safe way.
    It allows you to write codes in an immutable manner, which makes it easy to apply concurrency and parallelism (Synchronize).

    Scala vs Java
    Scala has a set of features that completely differ from Java

        All types are objects
        Type inference
        Nested Functions
        Functions are objects
        Domain-specific language (DSL) support
        Traits
        Closures
        Concurrency support inspired by Erlang

    https://www.tutorialspoint.com/scala/

    • Scala
    Scala is a general-purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive. Code sizes are typically reduced by a factor of two to three when compared to an equivalent Java application.
    http://www.scala-lang.org/
    • Clojure

    Clojure is a dynamic programming language that targets the Java Virtual Machine (and the CLR, and JavaScript).
    It is designed to be a general-purpose language, combining the approachability and interactive development of a scripting language with an efficient and robust infrastructure for multithreaded programming.
    Clojure is a compiled language
    http://clojure.org/

    • Statically typed programming language for modern multiplatform applications 

    https://kotlinlang.org/


    • Akka 
    Akka is a toolkit and runtime for building highly concurrent, distributed, and fault tolerant event-driven applications on the JVM.
    Where does the name Akka come from?
    It is the name of a beautiful Swedish mountain up in the northern part of Sweden called Laponia
    Akka is also the name of a goddess in the Sámi (the native Swedish population) mythology
    http://akka.io/
    • Because Lift applications are written in Scala, an elegant JVM language, you can still use your favorite Java libraries and deploy to your favorite Servlet Container and app server. Use the code you've already written and deployed to the container you've already configured!

    https://liftweb.net/


    • The High-Velocity Web Framework For Java and Scala 

    Built on Akka, Play provides predictable and minimal resource consumption (CPU, memory, threads) for highly-scalable applications.
    https://www.playframework.com/


    • The Bowler Quickstart is a Skeleton sbt project and Bowler app that gets you up and running with a minimal Bowler app that you can adapt in no time.

    https://github.com/bowler-framework/bowler-quickstart

    Monday, June 20, 2016

    Manually creating a shortcut for the Web Start client

    • Manually creating a shortcut for the Web Start client
    On Windows, the Web Start executable file for the default Java™ JVM is copied to a Windows system directory. When you let Web Start create a short cut for launching the desktop client, it uses the file in the system directory as the target. You can create a shortcut manually.
    http://www.ibm.com/support/knowledgecenter/SSATHD_7.7.0/com.ibm.itm.doc_6.3/install/webstart_shortcut.htm

    Sunday, March 20, 2016

    JVM (Java Virtual Machine) vs CLR (Common Language Runtime)

    We present empirical evidence to demonstrate that there is
    little or no difference between the Java Virtual Machine and
    the .NET Common Language Runtime, as regards the compilation
    and execution of object-oriented programs

    The JVM . . .
    • is stack-based
    • is secure—type safety is guaranteed by preventing explicit
    pointer manipulation
    • has automatic memory management (garbage collection)
    • is object-oriented, with primitive instructions for creating
    objects, accessing object members

    https://www.cs.utah.edu/~asbill/jsinger.pdf



    • Application virtualization software refers to both application virtual machines and software responsible for implementing them. Application virtual machines are typically used to allow application bytecode to run portably on many different computer architectures and operating systems. The application is usually run on the computer using an interpreter or just-in-time compilation (JIT).

    https://en.wikipedia.org/wiki/Comparison_of_application_virtualization_software

    Thursday, July 10, 2014

    Static Import in Java


    • import static java.lang.Math.PI;
    double r = cos(PI * theta);

    http://viralpatel.net/blogs/static-import-java-example-tutorial/

    • Static import can reduce code size and allow you to freely use static field of external class without prefixing class name on that
    http://javarevisited.blogspot.com/2012/10/what-is-static-import-in-java-5-example-tutorial.html#ixzz370mlCrPP

    BigDecimal

    • How to Use Java BigDecimal
    Ability to specify a scale, which represents the number of digits after the decimal place
    Ability to specify a rounding method
    The java.math.BigDecimal class handles both of these considerations.

    suppose we have a product which costs 10.00 in a given currency and the local sales tax is 0.0825, or 8.25%. If we work it out on paper, the tax amount is,
    10.00 * 0.0825 = 0.825
    Because our precision for the currency is two digits after the decimal, we need to round the 0.825 figure. Also, because this is a tax, it is good practice to always round up to the next highest cent. That way when the accounts are balanced at the end of the day, we never find ourselves underpaying taxes.
    0.825 -> 0.83
    so the total we charge to the customer is 10.83 in the local currency and pay 0.83 to the tax collector. Note that if we sold 1000 of these, we would have overpaid the collector by this much,
    1000 * (0.83 - 0.825) = 5.00

    http://www.opentaps.org/docs/index.php/How_to_Use_Java_BigDecimal:_A_Tutorial


    • The java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.
    Two types of operations are provided for manipulating the scale of a BigDecimal:

        scaling/rounding operations
        decimal point motion operations.
    http://www.tutorialspoint.com/java/math/java_math_bigdecimal.htm

    CamelCase Java Naming Convention

    CamelCase Java Naming Convention
    CamelCase (also known as Upper CamelCase) is where each new word begins with a capital letter (e.g., CamelCase, CustomerAccount, PlayingCard).
    http://java.about.com/od/javasyntax/a/nameconventions.htm

    Monday, May 26, 2014

    New features in Java 1.8

    •     Lambda expressions
        Remove the Permanent Generation
        Small VM
        Parallel Array Sorting
        Bulk Data Operations for Collections
        Define a standard API for Base64 encoding and decoding
        New Date & Time API
        Provide stronger Password-Based-Encryption (PBE) algorithm implementations in the SunJCE provider

       
        http://ttux.net/post/java-8-new-features-release-performance-code/

    Wednesday, April 23, 2014

    JSR 250


    • Spring JSR-250 Annotations
    Spring also JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations. Though these annotations are not really required because you already have other alternate
    http://www.tutorialspoint.com/spring/spring_jsr250_annotations.htm

    • JSR 250 is a Java Specification Request with the objective to develop annotations (that is, information about a software program that is not part of the program itself) for common semantic concepts in the Java SE and Java EE platforms
    http://en.wikipedia.org/wiki/JSR_250

    Rules Engine

    • Should I use a Rules Engine?
    commands in sequence with conditionals and loops, it provides a list of production rules. Each rule has a condition and an action - simplistically you can think of it as a bunch of if-then statements.

    The subtlety is that rules can be written in any order and the system can choose to evaluate them in whatever order makes sense for it. A good way of thinking of it is that the system runs through all the rules, picks the ones for which the condition is true, and then evaluates the corresponding actions.

    http://martinfowler.com/bliki/RulesEngine.html


    • Getting Started With the Java Rule Engine API (JSR 94): Toward Rule-Based Applications
    For many mission-critical applications, the process of automating business policies, procedures, and business logic is simply too dynamic to manage effectively as application source code

    The Business Rules Group defines a business rule as a statement that defines or constrains some aspect of the business; a business rule is intended to assert business structure or to control or influence the business's behavior

    A rule engine evaluates and executes rules, which are expressed as if-then statements. The power of business rules lies in their ability both to separate knowledge from its implementation logic and to be changed without changing source code.

    http://www.oracle.com/technetwork/articles/javase/javarule-139829.html



    • Open Source Rule Engines in Java


    Drools
    https://www.jboss.org/drools/
    Mandarax
    JLisa
    JEOPS - The Java Embedded Object Production System
    OpenRules
    Open Lexicon
    SweetRules
    JRuleEngine
    http://java-source.net/open-source/rule-engines

    Monday, April 7, 2014

    spring managed vs jsf managed

    • spring managed beans vs jsf managed beans?

    your beans should be completely managed either by JSF or by Spring.

    Many web applications consist from several 'layers' also called as 'tiers' of the application: web tier, or presentation tier for viewing pages of your application, business tier, or middle tier for executing logic and business rules of your appication and data tier, or persistece tier for tranferring data to/from your database. These tiers might have the following configuratio



    1.     Entity classes that will hold data derived from your database and most plausibly used by an ORM framework like Hibernate;
    2.     DAO classes that will be used to access database and at least perform CRUD operations on the database and most importantly for your web part return Entity classes for your web tier;
    3.     Service classes that will reflect business operations you application provides for;
    4.     Bean classes that will back up your views and will most probably contain data, action methods, transformations etc. used in your web pages.

        The next step is the choice of framework for your web application.
       
    1.     You choose Spring for all layers which means that your DAOs will be @Repository classes, your Services will be @Service classes and your Beans will be @Component classes. You will most probably use an ORM framework like Hibernate to deal with the database, so your Entities will be JPA @Entity classes properly configurated in Hibernate style. Your view technology will most probably be Spring MVC that was elaborated to work with Spring core 
    2.     You choose native JSF+EJB framework for all layers which means that your DAOs and Services will be @EJB classes your beans will be @ManagedBean classes. You will most probably also use Hibernate as ORM solution and JPA provider and will do database access via EntityManager. Your view technology will be JSF as it was naturally intended to be used with the abovementioned technologies.
       
       
        Spring is a lightweight container that will run on simple servlet containers like Tomcat whereas EJBs need an application server like Glassfish to run on. I think that this is the major driving force for combining JSF as a component-based web framework and Spring as a lightweight dependency injection and business tier framework.
       
       
        As we decided to integrate both frameworks together, I will explain how the integration works and why NPEs occur.

    1.     Entity classes will either be JPA/Hibernate annotated classes or simple POJOs configured by xml.
    2.     DAOs will be @Repository implementing base interfaces to avoid tight coupling. They will be managed by the Spring framework.
    3.     Services will be @Service also implementing base interfaces. They will also be managed by the Spring framework. Note that Spring framework will provide for out-of-the-box transaction management for you if you mark service methods with @Transactional.
    4.     Beans therefore must be @Component and @Scope("value") and must be managed by Spring if you want to use it as a dependency injection framework, allowing to access your services and other beans via @Autowired.

       
        So, the NPE stems from misunderstanding that your beans, as a logical part of the view, should be managed by JSF (note that @ManagedProperty wouldn't work as well). The bean gets instantiated by JSF, but your service resides in Spring context that JSF knows noting about, making injection not possible. On the other hand, if the bean remains within Spring context, its lifecycle and dependencies will be injected by Spring
       
       
        So, to make it work, mark the bean as

        @Component
        @Scope("request")
        public class SpringManagedBeanToBeUsedByJSF {

            ...

            @Autowired
            private SpringService springService;

            ...

        }
       
        and make all the prerequisites of using Spring with JSF.
        Consult this excellent example
        http://www.mkyong.com/jsf2/jsf-2-0-spring-hibernate-integration-example/
        This way, all of the beans will be managed by Spring and will be visible in JSF views when you attach EL-resolver in faces-config.xml (allowing JSF to 'see' Spring beans) and necessary listeners in web.xml.
        When you do it like this, all of the Spring beans can be referenced in .xhtml files and if you need to put the JSF action in the bean, just go ahead and place them in the (Spring) managed beans or make them implement vital to JSF interfaces, etc.
        The integration can be achieved only this way. Of course, you can also use JSF managed beans, @FacesConverter and @FacesValidator classes in the application as well, just do not interfere them with each other, but using two dependency injection frameworks withing one application is at least confusing.
       
        http://stackoverflow.com/questions/14766345/spring-dao-is-not-injected-in-jsf-managed-bean



    • To make a Java bean a Spring-managed service bean, you use the @Component or @Service annotation.


        @Component: a generic stereotype for any Spring-managed component.
        @Repository: used in the persistence layer to declare a Spring-managed DAO component.
        @Service: used in the service layer to declare a Spring-managed business service facade.
        @Controller: used in the presentation layer to declare a Spring-managed controller, for example a web controller.

       
        http://steveschols.wordpress.com/2011/07/28/spring-factorybean-managed-wiring-part-2/
       
       
        JSF is a component based web framework with an emphasis on MVC. Spring is a Dependency Injection and Inversion of Control framework that is not exclusive to web applications.
       
        If you don't understand these three terms are:

        Component based web framework

        Dependency Injection

        Inversion of Control

    Then my suggestion is that you just stop what you are doing and immediately begin reading.


    JSF as a standalone framework maintains the scope of its own managed beans without the need for a seperate DI framework. When introducing Spring however then there are naturally going to be conflicts. Spring manages its own Beans apart from JSF, so to reference these ManagedBeans and have business objects or DAO's be properly injected into them for use, the JSF ManagedBeans need to become Spring Controllers.


    You can declare a JSF ManagedBean with the @Controller annotation. Spring 3 is smart enough to recognize that it is a JSF managed bean and the bean name will be whatever the name is declared as for the ManagedBean.

    @Controller
    @Scope("session")
    @ManagedBean(name="testBean")

    The EL Resolver does basically just that, it resolves EL expressions encountered on your XHTML/JSF page. When referencing testBean however it will not be able to resolve this name correctly as it is referring to a JSF managed bean by that name, and will not be able to find the Spring Controller with all the Spring injected dependencies that you need.

    Spring 3 solves this problem by providing you a custom EL Resolver to use in place of the one that comes bundled with your JSF implementation. You can declare it to be used in faces-config.xml

    <application>
       <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
    </application>


    If you are just integrating JSF + Spring without the need for any other Spring controlled Servlets or without the need for Spring Security integration then no you do not need anything additional in your web.xml. You would only need to declare the FacesServlet and its context params, plus any other third party component library servlets that may be necessary for your situation.

    http://stackoverflow.com/questions/12317288/how-to-declare-a-jsf-managed-bean-in-a-spring-3-1-application



    • spring managed?

    @Component
    @Scope("session")
    public class AddressBean {
    }

    vs

    jsf managed?
    @ManagedBean
    @SessionScoped
    public class AddressBean {
    }


    If you were already using Spring for IoC, and if you were to, say, deem it 'cleaner' or 'easier' to use one IoC container for the management of the beans in all of your layers, it is possible to add a resolver to your faces-config.xml file in order to instruct JSF to utilise the Spring container instead:
    <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>


    If you are using JSF and have JSF pages (views) and such, then it could be JSF managed beans.
    Likewise if you have a Spring MVC project it would be Spring beans.

    http://stackoverflow.com/questions/13987826/spring-3-vs-jsf-2-managed-beans



    • Injecting Spring Beans into JSF 2 @ManagedBean Classes

    This particular example is taken from some PoC work done with JSF 2 and Spring 3 running within a Tomcat 6 server (on JDK 5). The reason I wanted to inject Spring references into my JSF managed beans was both for ease of use, and because we haven’t made a decision architecturally (yet) to use JAX-WS or Hessian web services, and the only change would be the Spring configuration of the service definition.

    I then attempted to get Spring to manage the bean, and found that JSF is able to delegate resolution of managed beans to an external resolver if it is configured correctly. In order to achieve this functionality the following needs to be done:

    web.xml
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    faces-config.xml
    <application>
        <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
    </application>

    Each backing bean into which you wish to inject Spring references into needs to be managed by Spring, so need to be annotated with Spring stereotypes.
    page1_backing.java
    package com.test.jsf;

    @ManagedBean
    @Controller
    @Scope(value = "request")
    public class page1_backing
    {
        @Autowired
        private UserInfo ui;

        ...
    }

    The @Autowired annotation is a Spring annotation indicating that the reference will be injected when the Spring bean is created. As the bean is scoped to “request”, the managed bean will be created each time it is referenced by the JSF request lifecycle. In this example, the UserInfo class is a simple POJO that contains user-sensitive data such as forename, surname etc.


    The final piece of the puzzle is to add the component-scan annotation to the Spring configuration file so that stereotypes are automatically picked up when the Spring context is loaded.

    application-context.xml
    1
       
    <context:component-scan base-package="com.test.jsf" />

    http://deevodavis.wordpress.com/injecting-spring-beans-into-jsf-2-managedbean-classes/

    Tuesday, March 25, 2014

    List vs ArrayList


    List is an interface and ArrayList is an implementation of the List interface. 
    The arraylist class has only a few methods in addition to the methods available in the List interface. 
    There is not much difference in this. 

    The only difference is, you are creating a reference of the parent interface in the first one and a reference of the class which implements the List (i.e) the ArrayList class in the second.
     If u use the first, you will be able to call the methods available in the List interface and you cannot make calls to the new methods available in the ArrayList class. Where as, u are free to use all the methods available in the ArrayList, if u use the second one.

    http://www.javabeat.net/difference-between-list-and-arraylist/

    List list = new ArrayList or ArrayList list = new ArrayList

    •  List list = new ArrayList  or    ArrayList list = new ArrayList

    to decouple your code from a specific implementation of the interface
    When you write your code like this:

    List list = new ArrayList();
     
    the rest of your code only knows that data is of type List, which is preferable because it allows you to switch between different implementations of the List interface with ease.


    For instance, say you were writing a fairly large 3rd party library, and say that you decided to implement the core of your library with a LinkedList.
    If your library relies heavily on accessing elements in these lists, then eventually you'll find that you've made a poor design decision;
    you'll realize that you should have used an ArrayList (which gives O(1) access time) instead of a LinkedList (which gives O(n) access time).
    Assuming you have been programming to an interface, making such a change is easy.

    You would simply change the instance of List from,

    List list = new LinkedList();

    to

    List list = new ArrayList(); 

    you have written your code to follow the contract provided by the List interface.

    if you had implemented the core of your library using

    LinkedList list = new LinkedList()

    making such a change wouldn't be as easy, as there is no guarantee that the rest of your code doesn't make use of methods specific to the LinkedList class.
    the choice is simply a matter of design

    http://stackoverflow.com/questions/9852831/polymorphism-why-use-list-list-new-arraylist-instead-of-arraylist-list-n

    Monday, March 24, 2014

    Java ArrayList

    • Java ArrayList

     Java class ArrayList(java.util.ArrayList) is a fast and easy to use class representing one-dimensional array.
     ArrayList is not synchronized i.e. using it in more that one thread may cause problems.

     ArrayList class provides methods for basic array operations:

        add( Object o ) - puts reference to object into ArrayList
        get( int index ) - retrieves object reference from ArrayList index position
        size() - returns ArrayList size
        remove( int index ) - removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list.
        indexOf( Object o) - finds the index in this list of the first occurrence of the specified element
        clear() - removes all of the elements
       
        http://www.anyexample.com/programming/java/java_arraylist_example.xml

    Thursday, February 27, 2014

    validationQuery


    Spring configuration in applicationcontext.cml for mysql

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://${mySQL.host}/${mySQL.db}" />
        <property name="username" value="${mySQL.user}" />
        <property name="password" value="${mySQL.pass}" />
        <property name="testOnBorrow" value="true"></property>
        <property name="validationQuery" value="SELECT 1"></property>
    </bean>
    
    
    validationQuery - The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query MUST be an SQL SELECT statement that returns at least one row.
    
    
    http://stackoverflow.com/questions/5636195/dbcp-and-hibernate-on-spring-doesnt-re-open-dead-connections-why

    Tuesday, January 28, 2014

    securerandom vs random

    Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.

    Java offers a few ways to generate random numbers, the default being java.util.Random. java.security.SecureRandom offers a more-secure extension of java.util.Random which “provides a cryptographically strong random number generator”.

    If you run twice java.util.Random.nextLong() with the same seed, it will produce the same number. For security reasons you want to stick with java.security.SecureRandom because it's a lot less predictable.


    The Random Class
    Java states that the Random class and its subclasses must produce predictable results when seeded with the same data
    This however is not why this is insecure, and it is useful when testing.
    The reason that this class is predictable though is the way in which it is seeded.
    The Random class, in the absence of a seed in its constructor it will seed its random number generator with the current time in milliseconds.
    This means that if somebody knows the time that the Random object was seeded and has several consecutive bytes of output then they can reasonably predict the next numbers.
    Once somebody has discovered the seed for the generator all number produced from it can be seen as compromised.

    The SecureRandom Class
    The SecureRandom class is different, it again uses algorithms that when seeded will produce predictable results, but the algorithm is much more complex.
    It uses a digest algorithm such as SHA-1 on the seed and a counter to generate random data.
    Its true strength however lies in the method in which it is seeded.
    The SecureRandom class is seeded using true random data gathered by the operating system
    This is data gathered by the OS from sources of true randomisation, such as mouse movements, network packet arrival times, IO statistics and interrupts.
    On Linux the data is gathered from /dev/random and on Windows via the CryptGenRandom() call in Windows.

    When using SecureRandom
    The more random numbers some can get a hold of the more likely they can figure out the seed. You should either throw away the SecureRandom object every now and then or reseed it. Keeping in mind the next point though.
    The seeding the generator takes entropy out of the system, if it cannot get any entropy it will block until the system has some. This means if you’re reseeding the generator too often your program will hang along with anything else on the system requiring entropy.
    Don’t seed the SecureRandom class yourself, unless you are 100% absolutely sure you are seeding it with purely random data, or you are testing and need repeatable results

    if what you are generating is a security token of some sort then you will need a secure generator.
    For example a session id, a one time password or an encryption key.

    http://www.danielhall.me/2009/09/cryptographically-secure-random-numbers-in-java/

    Monday, January 27, 2014

    BigInteger

    BigInteger, What Are They?

    (From sun.com) "Immutable arbitrary-precision integers."
    should be used whenever you need to handle very large numbers, anything larger then 'long' variables. Long's have a max a max value of 9223372036854775807. As well, BigInteger provides some useful functions

    for bit manipulation, GCD, random number, and primality testing and generation.
    http://compsci.ca/v3/viewtopic.php?t=13193

    Friday, January 24, 2014

    SecureRandom


    • // Get the instance of SecureRandom class with specified PRNG algorithm

        SecureRandom secureRandom = new SecureRandom();

    // You can use the getInstance() of the Secure Random class to create an object of SecureRandam
        // where you would need to specify the algorithm name.
        // SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");

     // You also specify the algorithm provider in the getInstance() method
        // SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");

        // A call to the setSeed() method will seed the SecureRandom object.
        // If a call is not made to setSeed(),
        // The first call to nextBytes method will force the SecureRandom object to seed itself.

    http://javadigest.wordpress.com/tag/securerandom-example/

    • I think it is best to let the SecureRandom seed itself. 
    This is done by calling nextBytes immediately after it's creation (calling setSeed will prevent this).
    final byte[] dummy = new byte[512];
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.nextBytes(dummy);

    http://stackoverflow.com/questions/12249235/securerandom-safe-seed-in-java


    • Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.

    http://docs.oracle.com/javase/7/docs/api/java/util/Random.html



    • When generating random numbers in Java for cryptographic purposes, many developers often use the java.security.SecureRandom class

    if it is used improperly the output can become predictable.
    The java.security.SecureRandom class does not actually implement a pseudorandom number generator (PRNG) itself.



    A pseudorandom number generator (PRNG), also known as a deterministic random bit generator (DRBG),[1] is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.
    Although sequences that are closer to truly random can be generated using hardware random number generators, pseudorandom numbers are important in practice for their speed in number generation and their reproducibility.
    Cryptographic applications require the output to also be unpredictable, and more elaborate algorithms, which do not inherit the linearity of simpler solutions, are needed.
    java.security.SecureRandom class does not actually implement a pseudorandom number generator (PRNG) itself.
    It uses PRNG implementations in other classes to generate random numbers
    The PRNGs are part of Java cryptographic service providers (CSPs). In Sun’s Java implementation, the SUN CSP is used by default.
    On Windows, the SUN CSP uses the SHA1PRNG implemented in sun.security.provider.SecureRandom by default.

    SecureRandom sr1 = new SecureRandom();
    // The following will create SUN SHA1PRNG if the highest  priority CSP is SUN
    SecureRandom sr2 = SecureRandom.getInstance("SHA1PRNG");
    // The following will always create SUN SHA1PRNG
    SecureRandom sr3 = SecureRandom.getInstance("SHA1PRNG", "SUN");
    according to Sun’s documentation, the returned java.security.SecureRandom instance is not seeded by any of these calls.
    java.security.SecureRandom.nextBytes(byte[]) is called, then the PRNG is seeded using a secure mechanism provided by the underlying operating system (starting with JRE 1.4.1 in Windows and JRE 1.4.2 in Linux and Solaris

    If java.security.SecureRandom.setSeed(long) or java.security.SecureRandom.setSeed(byte[]) is called before a call to java.security.SecureRandom.nextBytes(byte[]), then the internal seeding mechanism is bypassed, and only the provided seed is used to generate random numbers.

    Always specify the exact PRNG and provider that you wish to use. If you just use the default PRNG, you may end up with different PRNGs on different installations of your application that may need to be called differently in order to work properly. Using the following code to get a PRNG instance is appropriate:
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");

    When using the SHA1PRNG, always call java.security.SecureRandom.nextBytes(byte[]) immediately after creating a new instance of the PRNG. This will force the PRNG to seed itself securely. If for testing purposes, you need predictable output, ignoring this rule and seeding the PRNG with hard-coded/predictable values may be appropriate.


    http://www.cigital.com/justice-league-blog/2009/08/14/proper-use-of-javas-securerandom



    • For general statistics, Random is fine. Its a typical modulo congruent function.

    SecureRandom is more random. Specifically, it aims to make it impossible to predict the next "random" number from a sequence, which is trivial to do with most modulo congruent algorithms.

    Consider a Monti Carlo simulation. You call the nextRan() function and are happy as long as the function's pseudo random numbers pass the usual random tests.

    Consider a cryptographic message protocol, where you generate random session keys. Once a few sequential keys are know, you do not want the bad guy (traditionally labelled Mallet or Eve) to be able to predict the next key generated from the "random" function.

    So the use of a traditional modulo congruent algorithm is not at all suitable in a crypto application. 
    http://www.coderanch.com/t/410832/java/java/Java-Random-SecureRandom

    Wednesday, October 9, 2013

    profiling,diagnostic tools

    • Eclipse Memory Analyzer (MAT)


    visualize the references to objects based on Java heap dumps and provides tools to identify potential memory leaks.
    A Java heap dump is a snapshot of the complete Java object graph at a certain point in time. It includes all objects, fields, primitive types and object references.
    http://www.vogella.com/articles/EclipseMemoryAnalyzer/article.html



    • Plumbr 


    Plumbr discovers memory leaks and reports all the details you need to solve it, well before any OutOfMemoryErrors.
    http://plumbr.eu/



    • JProfiler

    JProfiler is an award-winning all-in-one Java profiler. JProfiler's intuitive GUI helps you find performance bottlenecks, pin down memory leaks and resolve threading issues
    http://www.ej-technologies.com/products/jprofiler/overview.html?gclid=CPWxkLOO1asCFcECQAodoE5ZNw


    • Proxy Sniffer

    Proxy Sniffer ™ is an innovative, powerful and reasonably priced tool for measuring the stability and response time of Web applications.
    http://www.proxy-sniffer.com/

    • Rational Purify

    Rational® Purify® is a dynamic software analysis tool designed to help developers write more reliable code. It includes two capabilities: 1) Memory debugging (pinpoints hard to find memory errors such as uninitialized memory access, buffer overflow and improper freeing of memory), 2) Memory leak detection (identifies memory blocks that no longer have a valid pointer)
    http://www-01.ibm.com/software/awdtools/purify/

    • Listing JRockit JVM Processes
    https://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/ctrlbreakhndlr.html#wp1001799

    • the jstack tool. It prints thread dumps to the command line console.
    http://howtodoinjava.com/2012/12/19/how-to-get-thread-dump-in-linux-using-jstack/

    • jstack - Stack Trace
    http://docs.oracle.com/javase/7/docs/technotes/tools/share/jstack.html

    • jps - Java Virtual Machine Process Status Tool
    The jps tool lists the instrumented HotSpot Java Virtual Machines (JVMs) on the target system. The tool is limited to reporting information on JVMs for which it has the access permissions.
    http://docs.oracle.com/javase/7/docs/technotes/tools/share/jps.html

    Monday, August 26, 2013

    SSO vs CAS


    • For example, a user logs on to her workstation, then decides to access a company database

    Typically, the database would require another username and password for authentication. But in an SSO environment, the application simply determines whether it can authenticate the user based on information the network's authentication server provides

    With centralized authentication, this authentication process is different. Using the example above, logging on to the database isn't transparent; the user would have to enter her authentication information again. However, the required credentials would be identical to the credentials she used to log on to her workstation. Centralized authentication effectively solves only one problem: users having to remember multiple sets of authentication credentials.

    http://windowsitpro.com/networking/sso-vs-centralized-authentication


    • The Central Authentication Service (CAS) is a single sign-on protocol for the web

    Its purpose is to permit a user to access multiple applications while providing their credentials (such as userid and password) only once
    It also allows web applications to authenticate users without gaining access to a user's security credentials, such as a password.
    http://en.wikipedia.org/wiki/Central_Authentication_Service


    • Central Authentication Service project, more commonly referred to as CAS.  

    CAS is an authentication system originally created by Yale University to provide a trusted way for an application to authenticate a user. CAS became a Jasig project in December 2004.
    CAS provides enterprise single sign-on service:
    http://www.jasig.org/cas

    • FreeIPA is an integrated security information management solution combining Linux (Fedora), 389 Directory Server, MIT Kerberos, NTP, DNS, Dogtag (Certificate System). It consists of a web interface and command-line administration tools.
    FreeIPA is an integrated Identity and Authentication solution for Linux/UNIX networked environments. A FreeIPA server provides centralized authentication, authorization and account information by storing data about user, groups, hosts and other objects necessary to manage the security aspects of a network of computers.
    https://www.freeipa.org/page/About

    • cookie-based SSO

    share the user logged in across multiple applications using only a cookie on the browser

    cookies can be shared if domains have a master domain in common. foo.example.com and bar.example.com can share a .example.com cookie
    When the user authenticates on site-a.com, you set a cookie on site-a.com domain. Then on site-b.com, you link a dynamic javascript from site-a.com, generated by server side script (php, etc) who has access to the created cookie, and then copy the same cookie on site-b.com on the client-side using js. Now both sites have the same cookie, without the need of asking the user to re-login
    I have seen custom SSO solutions that transmit the payload using XML over HTTPS.
    https://stackoverflow.com/questions/1784219/cookie-based-sso

    Sunday, July 21, 2013

    Reporting

    • JFreeChart is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications. JFreeChart's extensive feature set includes:
    http://www.jfree.org/jfreechart/


    • BIRT is an open source Eclipse-based reporting system that integrates with your Java/Java EE application to produce compelling reports.
    http://www.eclipse.org/birt/phoenix/

    • The JasperReports Library is the world's most popular open source reporting engine. It is entirely written in Java and it is able to use data coming from any kind of data source and produce pixel-perfect documents that can be viewed, printed or exported in a variety of document formats including HTML, PDF, Excel, OpenOffice and Word.
    http://community.jaspersoft.com/project/jasperreports-library


    • Open Source Charting & Reporting Tools in Java
    http://java-source.net/open-source/charting-and-reporting

    • Google Charts
    https://developers.google.com/chart

    • Jaspersoft Studio is the new Eclipse-based report designer for JasperReports and JasperReports Server.
    It is a full rewrite of iReport Designer, available as Eclipse plugin, and as a standalone application
    http://community.jaspersoft.com/project/jaspersoft-studio