Volcanohong's Learning Notes

Enjoy everything in everyday


  • Home

  • Archives

  • Categories

  • Tags

  • About

  • Search
close

MySQL notes I

Posted on 2016-07-29   |   In Database
  • Install MySQL

  • Here are the instructions for installing MySQL on a MacOS by using homebrew.
  • First, ensure that homebrew is up to date and ready to brew
brew update
brew doctor
brew upgrade

brew update
  • Installed mysql
brew install mysql
Read more »

Hippo notes I

Posted on 2016-07-18   |   In Hippo
  • Introduction

Hippo is a java based Content Management System (CMS) that allows you to create, control, and deliver engaging content to your visitors in every channel. Hippo CMS is an open-source, dual licensed platform.

Ref: onehippo

There are three components to Hippo CMS (wiki):

  1. Delivery tier
    The Hippo Site Toolkit is the presentation framework, using either JSP or FreeMarker to generate pages. Alternatively a EST API can be defined to serve structured content.
  2. Interface
    The user interface through which the content management and administrative functionalities can be used.
  3. Content repository
    All content, metadata and configuration is stored in a modified version of Apache Jackrabbit.
Read more »

Effective java notes

Posted on 2016-07-16   |   In Java
  • Item 38: check parameters for validity

    Most methods and constructors have some restrictions on what values may be passed into their parameters. For example, index values must be non-negative and object values must be non-null.
    You should enforce them with checks at beginning of the method body.

    Read more »

Linux notes I

Posted on 2016-07-14   |   In Blog
  • Commands

  • grep

grep is a useful command to search text in a file.

Format:
grep [–bcEFilnqsvx] [–e pattern] ... [–f patternfile] ... [pattern] [file ...]

grep with multiple strings:

/logs/xxx | grep -e 'error' -e 'falure'

grep with highlight color:

egrep --color=auto -i '(error|fatal|warn|drop)' /logs/xxx

Change grep display color: following will set background to red and foreground to white:

export GREP_OPTIONS='--color=auto'
export GREP_COLOR='1;37;41'

Useful links:
Writing shell scripts
Search a file for a specified pattern


Java SSL debugging

Posted on 2016-07-13   |   In Java
  • SSL: ValidatorException

Exception Message: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Read more »

Hexo notes I

Posted on 2016-07-10   |   In Blog
  • Hexo commands

Install Hexo, make sure you have node.js installed

npm install hexo-cli -g
Read more »

JUnit test notes I

Posted on 2016-07-08   |   In Unit Test
  • Test method with parameter: @Mocked object

Learn how to recording expectations…, which needs further justification.

Read more »

Java coding notes III

Posted on 2016-07-04   |   In Java
  • Sending HTTP post request

In case of sending HTTP post request to a URL with parameters such as submitting a HTML form and expecting to receive some response.

Read more »

Java coding notes II

Posted on 2016-06-28   |   In Java
  • Print all properties of an Object with name/value

public void printObjectFields(Object object) {
Field[] fields = object.getClass().getDeclaredFields();
StringBuilder msg = new StringBuilder();
String newLine = System.getProperty("line.separator");

msg.append( object.getClass().getName() );
msg.append(newLine);
Method method = null;
String methodName = "";
String methodValue = "";
for ( Field field : fields ) {
msg.append(" ");
try {
methodName = field.getName();
msg.append( methodName );
msg.append(": ");
//requires access to private field:
//field.setAccessible(true);

//run the `get` method to obtain the value
methodName = "get" + Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1);
method = object.getClass().getMethod(methodName);
methodValue = String.valueOf(method.invoke(object));
msg.append(methodValue);
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
} catch ( IllegalAccessException e ) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
}
msg.append(newLine);
}
//print msg
}
  • Compare two objects

Compare every filed of two objects by using CompareToBuilder…

private int compareBrand(Brand oldBrand, Brand newBrand) {
return new CompareToBuilder().append(oldBrand.getBrandId(), newBrand.getBrandId())
.append(oldBrand.getBrandName(), newBrand.getBrandName())
.toComparison();
}
  • URL encoding of query string parameter

Either using java.net.URLEncoder:

String str = "a=b+c";
str = URLEncoder.encode(str, "UTF-8");
Read more »

Java coding notes I

Posted on 2016-06-26   |   In Java
  • Create a singleton by enum

A Singleton means a class can have one instance only (instantiated exactly once).

  1. The declaration will make it clear that the class is a singleton.
  2. It gives us the flexibility to change whether the class should be singleton without changing its API.

    public class Moose {
    public static final Moose INSTANCE = new Moose();
    private Moose() {...}
    public static Moose getInstance() { return INSTANCE;}
    }
  3. Making an enum type with one element

    // Enum singleton
    public enum Moose {
    INSTANCE;

    public void Move(){ ... }
    }

This approach is functionally equivalent to the public field approach.

  • Builder pattern for creating an object

In the case that a constructor has many parameters and it’s hard to remember the names.

Problem in JavaBeans pattern:

  1. A JavaBean may be in an inconsistent state partway through its construction.
  2. It precludes the possibility of making a class immutable.

Builder is a static member of the class.


public class StaffActionLog{
private final StaffMember staffMember;
private final DateTime date;
private String actionField;

private StaffActionLog(Builder builder){
this.staffMember = builder.staffMember;
this.actionField = builder.actionField;
this.date = builder.date;
}

//StaffActionLog builder
public static class Builder{
//mandatary fields
private final StaffMember staffMember;
//reserved field
private final DateTime date = new LocalDate().toDateTimeAtCurrentTime();
//optional fields
private String actionField;
//constructor for mandatory field
public Builder(StaffMember staffMember) {
this.staffMember = staffMember;
}
//setter method for option field
public Builder actionField(String actionField){
this.actionField = actionField;
return this;
}
//build() method, return the object
public StaffActionLog build(){
return new StaffActionLog(this);
}
}
}

Call the builder function

StaffActionLog staffActionLog = new StaffActionLog.Builder(staffMember).actionField(actionField).build();

  • Static factory method

Use static factory method instead of common constructor…

//static factory method for creating staff action log
public static StaffActionLog staticCreateStaffActionLog(StaffMember staffMember, String actionField, String oldValue, String newValue){
return new StaffActionLog.Builder(staffMember).actionField(actionField).oldValue(oldValue).newValue(newValue).build();
}

Why we use static factory method compared to the constructor?

  1. A readable name for the method to create an instance

    + Refer the static methods in class `java.util.concurrent.Executors` in JDK, such as `newFixedThreadPool`, `newSingleThreadExecutor`, `newCachedThreadPool`, and `newScheduledThreadPool` etc.
    
  2. Not required to create a new instance each time

    + It's possibly that the static method returns a instance existing in the cache rather than a new instance, which can improve the performance. E.g., static method for `Integer` in JDK, 
    
    public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
    }
    + The above code will return the `Integer` instances in the cache with high probability integers.
  3. Can return an object of any type

    + Return the instance of an inherited object, e.g., the application of `java.util.EnumSet` in JDK, 
    + In the following code, the `noneOf()` function will return an instance based on the parameters.
    
    public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, java.io.Serializable {
    EnumSet(Class<E>elementType, Enum[] universe) {
    }
    public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) {
    if (universe.length <= 64)
    return new RegularEnumSet<>(elementType, universe);
    else
    return new JumboEnumSet<>(elementType, universe);
    }
    }
  4. Siplified the creation of a new object

    + Use this
    
    public static <K, V> HashMap<K, V> newInstance() {
    return new HashMap<K, V>();
    }
    Map<String, List<String>> m = HashMap.newInstance();
    Rather than
    Map<String, List<String>> m = new HashMap<String, List<String>>();

Disadvantages:

  1. With only static factory method, classes without public or protected constructors cannot be subclassed.
  2. The static factory methods are not readily distinguishable from other static methods.

1…34
Volcanohong

Volcanohong

Good things are coming, just KEEP GOING...

40 posts
12 categories
47 tags
RSS
GitHub
Creative Commons
Links
  • Google
  • Wiki
© 2016 - 2018 Volcanohong
Powered by Hexo
Theme - NexT.Mist