Maven hello world

Categories: Java; Tagged with: ; @ July 21st, 2013 11:45

Use maven to create, test, build project.

Steps:

  1. Create new project:
    mvn archetype:generate -DgroupId=com.liguoliang.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
  2. init Eclipse project:
    mvn eclipse:eclipse
  3. import the project into eclipse. (or you can directly create maven project in Eclipse using the Eclipse maven plugin)
  4. build the package:
    mvn package

 

life cycle:

  • validate: validate the project is correct and all necessary information is available
  • compile: compile the source code of the project
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

Trouble shooting

Error: Caused by: java.lang.UnsupportedClassVersionError:Unsupported major.minor version 51.0

Check the JVM which is using by Maven:

mvn –version can get a summary:

C:\Users\Guoliang>mvn -version
Apache Maven 3.0.4 (r1232337; 2012-01-17 16:44:56+0800)
Maven home: C:\Tools\sts\apache-maven-3.0.4\bin\..
Java version: 1.7.0_17, vendor: Oracle Corporation
Java home: C:\Tools\jdk7\jre
Default locale: en_SG, platform encoding: GBK
OS name: "windows 7", version: "6.1", arch: "x86", family: "windows"

You can edit the Java Home path or specify the JVM for maven.

How To Design A Good API and Why it Matters 笔记

Categories: Java; Tagged with: ; @ June 2nd, 2013 23:22

YouTube: http://www.youtube.com/watch?v=aAb7hSCtvGw

by Joshua Bloch (Principal Software Engineer of Google)

 

API设计是重要的

对公司来说, API 很可能成为公司重要财产, 客户要购买, 学习, 停止使用API的代价过高, 并且, 成功的API可以帮助公司抓牢客户.  当然, 设计太烂的API也会拖垮公司.

对于程序员来说,  如果你写程序, 那你就是一个API设计师,  有用的模块会被重用, 但一旦被其他人使用, 那就不能随便更改.  如果在平时的编程当成设计API会提高代码质量

干货来了:

Characteristics of a Good API

• Easy to learn
• Easy to use, even without documentation 多美好啊
• Hard to misuse
• Easy to read and maintain code that uses it
• Sufficiently powerful to satisfy requirements
• Easy to extend
• Appropriate to audience

 

Outline

I. The Process of API Design

1. Gather Requirements – With a Healthy Degree of Scepticism

我们经常会收到解决方案而不是需求 — 所以我们常说, Product management/BA们不要提Solution.

我们的工作是提炼需求, 最好是以Use Case的形式.

(以前我有个Technical Manager, 他总是要求我们吃透需求, 挑战PM. 事实上, 如果暂时妥协, 接受未经挑战的需求, 可能会为日后的重构埋下伏笔)

Can be easier and more rewarding to build something more general

2. Start with Short Spec–1 Page is Ideal

跟领导演讲稿一样

“If you want me to speak for an hour – give me a moment’s notice; if you want me to speak for half an hour, give me a day’s notice; if you want me to speak for five minutes—give me a week.”__Winston Churchill

3. Write to Your API Early and Often

Code lives on as examples, unit tests

II. General Principles

API Should Be As Small As Possible But No Smaller

API should satisfy its requirements

When in doubt leave it out
_ Functionality, classes, methods, parameters, etc.
_ You can always add, but you can never remove

Minimize Accessibility of Everything

Names Matter–API is a Little Language

 

Document Religiously
• Document every class, interface, method,
constructor, parameter, and exception
_ Class: what an instance represents

_ Method: contract between method and its client
_ Preconditions, postconditions, side-effects
_ Parameter: indicate units, form, ownership
• Document state space very carefully

 

III. Class Design

 

Minimize Mutability

Classes should be immutable unless there’s a
good reason to do otherwise
_ Advantages: simple, thread-safe, reusable
_ Disadvantage: separate object for each value
• If mutable, keep state-space small, well-defined
_ Make clear when it’s legal to call which method

Subclass Only Where It Makes Sense

Design and Document for Inheritance or Else Prohibit it

Inheritance violates encapsulation (Snyder, ‘86)

IV. Method Design

Don’t Make the Client Do Anything the Module Could Do

Don’t Violate the Principle of Least Astonishment

User of API should not be surprised by behavior

Fail Fast–Report Errors as Soon as Possible After They Occur

快速失败

Provide Programmatic Access to All Data Available in String Form

Overload With Care

Avoid ambiguous overloadings,  If you must provide ambiguous overloadings, ensure same behavior for same arguments.

Just because you can doesn’t mean you should: often better to use a different name

Use Appropriate Parameter and Return Types

• Favor interface types over classes for input
_ Provides flexibility, performance
• Use most specific possible input parameter type
_ Moves error from runtime to compile time
• Don’t use string if a better type exists
_ Strings are cumbersome, error-prone, and slow
• Don’t use floating point for monetary values
_ Binary floating point causes inexact results!
• Use double (64 bits) rather than float (32 bits)
_ Precision loss is real, performance loss negligible

 

Use Consistent Parameter Ordering Across Methods

Avoid Long Parameter Lists

V. Exception Design

 

VI. Refactoring API Designs

 

Links:

Rule of three

Java Code Quality Control Eclipse Plugins 代码质量控制Eclipse插件

Categories: Development NotesJava; Tagged with: ; @ May 2nd, 2013 22:04

Several Eclipse plugins which can help to improve code quality.  all plugs can find from Eclipse Market.

1.  FindBugs

Find potential bugs for you.  “a program which uses static analysis to look for bugs in Java code

image

2. eCobertura

“eCobertura is a free Eclipse plugin for Cobertura – a Java code coverage reporting tool.”

With “eCobertura”, we can get an overview of code coverage within Eclipse.

image

BTW, This plugin hasn’t been updated for more than 2 years.

How to clear the code coverage highlighting?
Currently, no this feature (https://github.com/jmhofer/eCobertura/issues/8), but can reset by edit the java class.

3. CheckStyle

Help developer to check the coding style, for example, coding conversation, make sure the code is clean and neat.

Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard. It automates the process of checking Java code to spare humans of this boring (but important) task. This makes it ideal for projects that want to enforce a coding standard.

image

 

[to be continued]

Using Oracle Auto-Increment/Sequence in Hibernate/MyBatis

Categories: Java; Tagged with: ; @ May 1st, 2013 23:41

(Hibernate) Error 1 : java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist

Solution:

Specify the sequence:

package com.liguoliang.jee.vo;

/**
 * Represents Client.
 * @author Guoliang
 *
 */
@Entity
@Table (name="Client")
public class Client {
	
	@Id
	@Column(name="id")
	@SequenceGenerator(name="my_seq", sequenceName="CLIENT_ID_SEQUENCE")
	@GeneratedValue(strategy = GenerationType.SEQUENCE ,generator="my_seq")
	private int id;
	
	@Column(name="name")
	String name;
	
	public Client() {
		// TODO Auto-generated constructor stub
	}
//....

}

(MyBatis) Error 2: java.sql.SQLException: Invalid column type: getInt not implemented for class oracle.jdbc.driver.T4CRowidAccessor

Code before change:

	/**
	 * insert new client.
	 * @param client
	 */
	
	@Insert("INSERT INTO CLIENT(name) VALUES (#{name})")
	@Options(useGeneratedKeys=true, keyProperty="id")
	void insert(Client client);

Solutions:

1. Directly Remove @Options(useGeneratedKeys=true, keyProperty=”id”)

2. Replace @Options with @SelectKey:

	/**
	 * insert new client.
	 * @param client
	 */
	
	@Insert("INSERT INTO CLIENT(name) VALUES (#{name})")
	@SelectKey(
			keyProperty = "id",
			before = true,
			resultType = Integer.class,
			statement={" select CLIENT_ID_SEQUENCE.nextval AS id from dual"}
			)
	void insert(Client client);

Oracle 11 XE & JDBC

Categories: Java; Tagged with: ; @ May 1st, 2013 0:51

How to get Oracle 11 XE for Windows 64?

Download the Oracle 11 XE 32 bit and install it.

No problem for me ( Win7 64)

Forgot the sys password, how to reset?

Conn / as sysdba

passw system

input new password.

[http://rolfje.wordpress.com/2007/01/16/lost-oracle-sys-and-system-password/]

How to get the version of Oracle?

select * from v$version

How to Add Oracle JDBC Driver in Loacl Maven Repo?

mvn install:install-file -Dfile=C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar
then add modify your pom:

<dependency>
	<groupId>com.oracle</groupId>
	<artifactId>ojdbc6</artifactId>
	<version>11.2.0</version>
</dependency>
[http://www.mkyong.com/maven/how-to-add-oracle-jdbc-driver-in-your-maven-local-repository/]

Quick test using JDBC

	public static void main(String[] args) throws Throwable {
		
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection connection = null;
		connection = DriverManager.getConnection(
			"jdbc:oracle:thin:@localhost:1521:xe","root","root");
		System.out.println(connection.getMetaData().getDatabaseMajorVersion());
		connection.close();
	}

Newer Posts <-> Older Posts



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.