{ JavaTechNote's }
  • Linkedin
  • Github
  • Facebook
  • Twitter
  • Instagram

About me

Let me introduce myself


A bit about me

I am Dhananjaya Naidu and I’m just like you; a java lover. I feel proud to say that I am a Java Developer and currently located in Bangalore, India.

I enjoy coding in full Java/J2ee stack (Spring, JSF, Hibernate, Struts, Servlets, JSP) and Web Technologies (HTML, CSS, JavaScript, JQuery).


I love to play Cricket, Kabaddi, Valley Ball and any Outdoor Sports. I love the nature and like to travel new places.

Profile

Dhananjaya Naidu

Personal info

Dhananjaya Naidu Reddi

Be good, Do good !!!

Birthday: 19 Jun 1988
Website: www.rdnaidu.com
E-mail: hello@rdnaidu.com

Skills & Interests

Productive
90%
Java & J2ee
Creative
70%
HTML & CSS
Progressive
50%
Blogger

Notes

My latest writings


Wednesday, 22 July 2020

GoF Design Patterns in Java's core libraries


GoF Design Patterns
You can find an overview of a lot of design patterns in Wikipedia. It also mentions which patterns are mentioned by GoF. I'll sum them up here and try to assign as many pattern implementations as possible, found in both the Java SE and Java EE APIs.

Creational patterns

Abstract factory 

(recognizeable by creational methods returning the factory itself which in turn can be used to create another abstract/interface type)

Builder 

(recognizeable by creational methods returning the instance itself)

Factory method 

(recognizeable by creational methods returning an implementation of an abstract/interface type)

Prototype 

(recognizeable by creational methods returning a different instance of itself with the same properties)

Singleton 

(recognizeable by creational methods returning the same instance (usually of itself) everytime)


Structural patterns

Adapter 

(recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own/another abstract/interface type which decorates/overrides the given instance)

Bridge 

(recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own abstract/interface type which delegates/uses the given instance)
  • None comes to mind yet. A fictive example would be new LinkedHashMap(LinkedHashSet<K>, List<V>) which returns an unmodifiable linked map which doesn't clone the items, but uses them. The java.util.Collections#newSetFromMap() and singletonXXX() methods however

Composite 

(recognizeable by behavioral methods taking an instance of same abstract/interface type into a tree structure)

Decorator 

(recognizeable by creational methods taking an instance of same abstract/interface type which adds additional behaviour)

Facade 

(recognizeable by behavioral methods which internally uses instances of different independent abstract/interface types)

Flyweight 

(recognizeable by creational methods returning a cached instance, a bit the "multiton" idea)

Proxy 

(recognizeable by creational methods which returns an implementation of given abstract/interface type which in turn delegates/uses a different implementation of given abstract/interface type)


Behavioral patterns

Chain of responsibility 

(recognizeable by behavioral methods which (indirectly) invokes the same method in another implementation of same abstract/interface type in a queue)

Command 

(recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been encapsulated by the command implementation during its creation)

Interpreter 

(recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type; note that parsing/formatting is not part of the pattern, determining the pattern and how to apply it is)

Iterator 

(recognizeable by behavioral methods sequentially returning instances of a different type from a queue)

Mediator 

(recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the command pattern) which delegates/uses the given instance)

Memento 

(recognizeable by behavioral methods which internally changes the state of the whole instance)

Observer (or Publish/Subscribe) 

(recognizeable by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state)

State 

(recognizeable by behavioral methods which changes its behaviour depending on the instance's state which can be controlled externally)

Strategy 

(recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been passed-in as method argument into the strategy implementation)

Template method 

(recognizeable by behavioral methods which already have a "default" behaviour defined by an abstract type)

Visitor 

(recognizeable by two different abstract/interface types which has methods defined which takes each the otherabstract/interface type; the one actually calls the method of the other and the other executes the desired strategy on it)


Friday, 26 June 2020

Git Tips - How to know the remote repository URL of your local Branch

If you want only the remote URL, or referential integrity has been broken: 
git config --get remote.origin.url 

If you require full output or referential integrity is intact: 
git remote show origin 
When using git clone (from GitHub, or any source repository for that matter) the default name for the source of the clone is "origin". Using git remote show will display the information about this remote name. The first few lines should show:
C:\Users\jaredpar\VsVim> git remote show origin
* remote origin
Fetch URL: git@github.com:jaredpar/VsVim.git
Push URL: git@github.com:jaredpar/VsVim.git 
HEAD branch: master
Remote branches:

If you want to use the value in the script, you would use the first command listed in this answer.

Java Security: Illegal key size or default parameters.?

The Problem

Java 1.6.0.12 installed on my Linux server and the code below runs just perfectly.
String key = "av45k1pfb024xa3bl359vsb4esortvks74sksr5oy4s5serondry84jsrryuhsr5ys49y5seri5shrdliheuirdygliurguiy5ru";
try {
    Cipher c = Cipher.getInstance("ARCFOUR");

    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "ARCFOUR");
    c.init(Cipher.DECRYPT_MODE, secretKeySpec);

    return new String(c.doFinal(Hex.decodeHex(data.toCharArray())), "UTF-8");

} catch (InvalidKeyException e) {
    throw new CryptoException(e);
}

When installed Java 1.6.0.26 on my server user and when I try to run my application, I get the following exception. My guess would be that it has something to do with the Java installation configuration because it works in the first one, but doesn't work in the later version.I keep getting this Error. 

Caused by: java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.init(DashoA13*..) ~[na:1.6]
    at javax.crypto.Cipher.init(DashoA13*..) ~[na:1.6]
    at my.package.Something.decode(RC4Decoder.java:25) ~[my.package.jar:na]
    ... 5 common frames omitted

Solution

Most likely you don't have the unlimited strength file installed now. 
Extract the jar files from the zip and save them in ${java.home}/jre/lib/security/

This is a code only solution. No need to download or mess with configuration files. It's a reflection based solution, tested on java 8 Call this method once, early in your program.
 //Imports

import javax.crypto.Cipher;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
//method

public static void fixKeyLength() {
    String errorString = "Failed manually overriding key-length permissions.";
    int newMaxKeyLength;
    try {
        if ((newMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES")) < 256) {
            Class c = Class.forName("javax.crypto.CryptoAllPermissionCollection");
            Constructor con = c.getDeclaredConstructor();
            con.setAccessible(true);
            Object allPermissionCollection = con.newInstance();
            Field f = c.getDeclaredField("all_allowed");
            f.setAccessible(true);
            f.setBoolean(allPermissionCollection, true);

            c = Class.forName("javax.crypto.CryptoPermissions");
            con = c.getDeclaredConstructor();
            con.setAccessible(true);
            Object allPermissions = con.newInstance();
            f = c.getDeclaredField("perms");
            f.setAccessible(true);
            ((Map) f.get(allPermissions)).put("*", allPermissionCollection);

            c = Class.forName("javax.crypto.JceSecurityManager");
            f = c.getDeclaredField("defaultPolicy");
            f.setAccessible(true);
            Field mf = Field.class.getDeclaredField("modifiers");
            mf.setAccessible(true);
            mf.setInt(f, f.getModifiers() & ~Modifier.FINAL);
            f.set(null, allPermissions);

            newMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES");
        }
    } catch (Exception e) {
        throw new RuntimeException(errorString, e);
    }
    if (newMaxKeyLength < 256)
        throw new RuntimeException(errorString); // hack failed
}
  
Follow this stackoverflow.com Q&A discussion for more information    
© Delthas

How to edit .bash_profile and modify or add $PATH on OSX ?

First, make sure the .bash_profile file is existing?  Remember that the .bash_profile file isn't there by default. You have to create it on your own.



Go into your user folder in finder. The .bash_profile file should be findable there. -> HD/Users/[USERNAME]

Remember: Files with a point at the beginning '.' are hidden by default.

To show hidden files in Mac OS Finder:  Press: Command + Shift + . 
If it's not existing, you have to create .bash_profile on your own.

Open terminal app and switch into user folder with simple command:

cd

If it's not existing, use this command to create the file:
touch .bash_profile 
Now we can edit .bash_profile using many ways mentioned below.

vi ~/.bash_profile 
or 
subl ~/.bash_profile 
or 
mate ~/.bash_profile, depending on your favourite editor.

You have to open that file with a text editor and then save it.
touch ~/.bash_profile; open ~/.bash_profile 
It will open the file with TextEdit, paste your things and then save it. If you open it again you'll find your edits.

You can use other editors:
nano ~/.bash_profilemate ~/.bash_profilevim ~/.bash_profile 
But if you don't know how to use them, it's easier to use the open approach.

Alternatively, you can rely on pbpaste. Copy
export ANDROID_HOME=/<installation location>/android-sdk-macosxexport PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools 
in the system clipboard and then in a shell run
pbpaste > ~/.bash_profile
Or alternatively you can also use cat
 cat > ~/.bash_profile
(now cat waits for input: paste the two export definitions and then hit ctrl-D).



References:

Best way to declare String in Java !!!

     String str = new String("SOME"); //always create a new object on the heap
     String str="SOME"; //uses the String pool

        //Try this small example:

        String s1 = new String("Hello");
        String s2 = "Hello";
        String s3 = "Hello";

        System.err.println(s1 == s2);
        System.err.println(s2 == s3);

To avoid creating unnecessary objects on the heap use the second form. 


 Q) Should I set the initial java String values from null to "" ? Often I have a class as such: 

    public class Foo { 
        private String s1;
        private String s2;
        // etc etc etc
    }

This makes the initial values of s1 and s2 equal to null. Would it be better to have all my String class fields as follows? 


    public class Foo {
    private String s1 = "";
    private String s2 = "";
    // etc etc etc
    }
Then, if I'm consistent with class definition I'd avoid a lot of null pointer problems. What are the problems with this approach? I disagree with the other posters. Using the empty string is acceptable. I prefer to use it whenever possible. In the great majority of cases, a null String and an empty String represent the exact same thing - unknown data. 



Whether you represent that with a null or an empty String is a matter of choice. The one place where you may need new String(String) is to force a substring to copy to a new underlying character array, as in 

    small = new String(huge.substring(10,20)) 
However, this behavior is unfortunately undocumented and implementation dependent. I have been burned by this when reading large files (some up to 20 MiB) into a String and carving it into lines after the fact. I ended up with all the strings for the lines referencing the char[] consisting of entire file. 

Unfortunately, that unintentionally kept a reference to the entire array for the few lines I held on to for a longer time than processing the file - I was forced to use new String() to work around it. The only implementation agnostic way to do this is: 

 small = new String(huge.substring(10,20).toCharArray()); 
This unfortunately must copy the array twice, once for toCharArray() and once in the String constructor. There needs to be a documented way to get a new String by copying the chars of an existing one; or the documentation of String(String) needs to be improved to make it more explicit (there is an implication there, but it's rather vague and open to interpretation). Pitfall of Assuming what the Doc Doesn't State In response to the comments, which keep coming in, observe what the Apache Harmony implementation of new String() was: 

    public String(String string) {
        value = string.value;
        offset = string.offset;
        count = string.count;
    }
That's right, no copy of the underlying array there. And yet, it still conforms to the (Java 7) String documentation, in that it: Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable. The salient piece being "copy of the argument string"; it does not say "copy of the argument string and the underlying character array supporting the string". 

Difference Between String , StringBuilder And StringBuffer Classes in Java

String

  • String is immutable ( once created can not be changed )object . 
  • The object created as a String is stored in the Constant String Pool. 
  • Every immutable object in Java is thread safe ,that implies String is also thread safe . 
  • String can not be used by two threads simultaneously. 
  • String once assigned can not be changed.

StringBuffer

  • StringBuffer is mutable means one can change the value of the object . 
  • The object created through StringBuffer is stored in the heap. 
  • StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow two threads to simultaneously access the same method.  Each method can be accessed by one thread at a time . But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property. Thus StringBuilder is faster than the StringBuffer when calling the same methods of each class. String Buffer can be converted to the string by using toString() method.
StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

  • StringBuilder is same as the StringBuffer, that is it stores the object in heap and it can also be modified . 
  • The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
  • StringBuilder is fast as it is not thread safe .
StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder


Works

What can I do


Branding

Social media Branding is far and away the best technique a company has to boost engagement with its customer base. Even a minimum of involvement, such as making one post a day.

Web Design

Web design is the process of creating websites. It encompasses several different aspects, including webpage layout, content production, and graphic design.

Development

Web Development refers to building, creating, and an maintaining websites. It includes aspects such as web design, web publishing, web programming and database management.

Graphic Design

Graphic design is the process of visual communication and problem-solving through the use of typography, photography, and illustration. The field is considered a subset of visual communication and communication design.

Photography

Photography is the art, application and practice of creating durable images by recording light or other electromagnetic radiation, either electronically by means of an image sensor, or chemically by means of a light-sensitive material such as photographic film.

User Experience

User experience (UX) design is the process design teams use to create products that provide meaningful and relevant experiences to users. This involves the design of the entire process of acquiring and integrating the product, including aspects of branding, design.

Contact

Get in touch with me


Adress/Street

Bangalore, India