Saturday 25 May 2013

Order of Operations

    1. () [] --> . ::         grouping, scope, array, member access
    2. ! ~ - + * &  sizeof type cast ++x --x       (most) unary operations, sizeof and type casts
    3. * / %                 multiplication division modulo
    4. + -                    addition subtraction
    5. << >>               bitwise shift left and right
    6. < <= > >=        comparisons: less than, ....
    7. == !=               equal, not equal
    8. &                     bitwise AND
    9. ^                      bitwise exclusive OR
    10. |                       bitwise inclusive (normal) OR
    11. &&                  Logical AND
    12. ||                      Logical OR
    13. ?:                     condition expression (ternary operator)
    14. = += -= *= /= %= &= |= ^= <<= >>= assignment operators
    15. .                      common operator

Thursday 7 February 2013

Using MAVEN to create war file

  1. Download and install Maven
  2. Go the command line run: mvn archetype:generate
  3. Follow the prompted steps - choosing the simple java web project (18) and a suitable name.
  4. When it is finished run: mvn eclipse:eclipse
  5. Start Eclipse. Choose File -> Import -> Existing project. Select the directory where you ran the mvn goals.
  6. That's it you should now have a very good start to a war project in eclipse
  7. You can create the war itself by running mvn package or deploy it by setting up a server in eclipse and simply adding adding the project to the server.
Sample Configuration:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1-alpha-2</version>
    <configuration>
        <outputDirectory>${project.build.directory}/tmp/</outputDirectory>
        <workDirectory>${project.build.directory}/tmp/war/work</workDirectory>
        <webappDirectory>${project.build.webappDirectory}</webappDirectory>
        <cacheFile>${project.build.directory}/tmp/war/work/webapp-cache.xml</cacheFile>
        <nonFilteredFileExtensions>
            <nonFilteredFileExtension>pdf</nonFilteredFileExtension>
            <nonFilteredFileExtension>png</nonFilteredFileExtension>
            <nonFilteredFileExtension>gif</nonFilteredFileExtension>
            <nonFilteredFileExtension>jsp</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
        <webResources>
            <resource>
                <directory>src/main/webapp/</directory>
                <targetPath>WEB-INF</targetPath>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </webResources>
        <warName>Application</warName>
    </configuration>
</plugin>
 
if you want to go with maven is to stick to maven conventions and particularly the Maven Directory Layout.

A simple war project would have the following directory layout:

 

struts-config.xml的主要元素

<?xml version=”1.0” encoding=”ISO-8859-1”?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd";>
 
<struts-config>

<data-sources>
      <data-source>
      </data-source>
</data-sources>

<form-beans>
      <form-bean / >
</form-beans>

<global-forwards>
      <forward / >
</global-forwards>

<action-mappings>
      <action / >
</action-mappings>

<controller / >

<message-resources / >

<plug-in />

</struts-config>

struts-config.xml配置文件必须按照这个顺序进行配置,否则在你的容器启动的时候就会出错。

Wednesday 6 February 2013

Using ANT to create WAR file

<target name="default" depends="setup,compile,buildwar,deploy"></target>
You can then execute one click in Eclipse to run that Ant target. Here are examples of each of the steps:

Preconditions

We'll assume that you have your code organized like:
  • ${basedir}/src: Java files, properties, XML config files
  • ${basedir}/web: Your JSP files
  • ${basedir}/web/lib: Any JARs required at runtime
  • ${basedir}/web/META-INF: Your manifest
  • ${basedir}/web/WEB-INF: Your web.xml files

Set up

Define a setup task that creates the distribution directory and copies any artifacts that need to be WARred directly:
<target name="setup">
    <mkdir dir="dist" />
    <echo>Copying web into dist</echo>
    <copydir dest="dist/web" src="web" />
    <copydir dest="dist/web/WEB-INF/lib" src="${basedir}/../web/WEB-INF/lib" />
</target>

Compile

Build your Java files into classes and copy over any non-Java artifacts that reside under src but need to be available at runtime (e.g. properties, XML files, etc.):
<target name="compile">
    <delete dir="${dist.dir}/web/WEB-INF/classes" />
    <mkdir dir="${dist.dir}/web/WEB-INF/classes" />
    <javac destdir="${dist.dir}/web/WEB-INF/classes" srcdir="src">
        <classpath>
            <fileset dir="${basedir}/../web/WEB-INF/lib">
                  <include name="*" />
            </fileset>
        </classpath>
    </javac>
    <copy todir="${dist.dir}/web/WEB-INF/classes">
        <fileset dir="src">
            <include name="**/*.properties" />
            <include name="**/*.xml" />
        </fileset>
    </copy>
</target>

Build WAR

Create the WAR itself:
<target name="buildwar">
    <war basedir="${basedir}/dist/web" destfile="My.war"
     webxml="${basedir}/dist/web/WEB-INF/web.xml">
        <exclude name="WEB-INF/**" />
        <webinf dir="${basedir}/dist/web/WEB-INF/">
            <include name="**/*.jar" />
        </webinf>
    </war>
</target>

Deploy

Finally, you can set up a task to deploy the WAR directly into your Tomcat deploy location:
<target name="deploy">
    <copy file="My.war" todir="${tomcat.deploydir}" />
</target>

Click and go!

Once all this is set up, simply launching the default target from Eclipse will compile, WAR, and deploy your solution.
The advantage of this approach is that it will work outside Eclipse as well as within Eclipse and can be used to easily share your deployment strategy (e.g. via source control) with other developers who are also working on your project.

Friday 18 January 2013

HTML - Hyper Text Markup Language

HTML editors:

  • Adobe Dreamweaver
  • Microsoft Expression Web
  • CoffeeCup HTML Editor

HTML Tags syntax:

   <tagname>content</tagname>

The common <!DOCTYPE> Declarations

HTML5
   <!DOCTYPE html>

HTML 4.01
   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

XHTML 1.0
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org//TR/xhtml1/DTD/xhtml1-transitional.dtd">

HTML Comments

<!-- This is a comment-->

HTML Headings

<h1>content</h1>
<h2>content</h2>
<h3>content</h3>
:
<h6>content</h6>

HTML horizontal line

<hr>

HTML Paragraphs

<p>content</p>

HTML Line Breaks

<br>

HTML Links

<a href="link_address">content</a>

HTML Images

<img src="image_source" alt="some_text" width="value1" height="value2">
 <map>
<area>

HTML Text Formatting Tags

Tag Description
<b> Defines bold text
<em> Defines emphasized text 
<i> Defines a part of text in an alternate voice or mood
<small> Defines smaller text
<strong> Defines important text
<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text

HTML "Computer Output" Tags

Tag Description
<code> Defines computer code text
<kbd> Defines keyboard text 
<samp> Defines sample computer code
<var> Defines a variable
<pre> Defines preformatted text

HTML Citations, Quotations, and Definition Tags

Tag Description
<abbr> Defines an abbreviation or acronym
<address> Defines contact information for the author/owner of a document
<bdo> Defines the text direction
<blockquote> Defines a section that is quoted from another source
<q> Defines an inline (short) quotation
<cite> Defines the title of a work
<dfn> Defines a definition term

HTML <title> Element

<title>to defines a title in the browser toolba.</title>

HTML <base> Element

<base href="default address or a default target for all links on a page"><base target-"_blank">

HTML <link> Element

The <link> tag defines the relationship between a document and an external resource.
<link rel="stylesheet" type="text/css" href="mystyle.css">

HTML <style> Element

The <style> tag is used to define style information for an HTML document.

<style type="text/css">
body {background-color:yellow}
p {color:blue}
</style>

HTML <meta> Element

The <meta> tag provides metadata about the HTML document. It is used to spcify page description, keywords, author of the document, last modified and other metadata.

<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript">
<meta name="description" content="Free web tutorials on HTML and CSS">
<meta name="author" content="Hege Refsnes">

HTML <script> Element

The <script> tag defines a client-side script.

Inline CSS Styles

<p style="color:blue;margin-left:20px;">This is a paragraph.</p>

Internal CSS Style Sheet

<head>
<style type="text/css">
body {background-color:yellow;}
p {color:blue;}
</style>
</head> 

External CSS Style Sheet

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

HTML Tables

<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

Tag Description
<table> Defines a table
<th> Defines a header cell in a table
<tr> Defines a row in a table
<td> Defines a cell in a table
<caption> Defines a table caption
<colgroup> Specifies a group of one or more columns in a table for formatting
<col> Specifies column properties for each column within a <colgroup> element
<thead> Groups the header content in a table
<tbody> Groups the body content in a table
<tfoot> Groups the footer content in a table

HTML List Tags

Tag Description
<ol> Defines an ordered list
<ul> Defines an unordered list
<li> Defines a list item
<dl> Defines a definition list
<dt> Defines an item in a definition list
<dd> Defines a description of an item in a definition list

<ol>
<li>list 1</li>
<li>list 2</li>
</ol> 
 output:
  1. list 1
  2. list 2
<dl>
<dt>item 1</dt>
<dd>- description 1 for item 1</dd>
<dt>item 2</dt>
<dd>- description 1 for item 2</dd>
</dl>

output:
item 1
- description 1 for item 1
item 2
- description 1 for item 2

HTML Block Elements

Most HTML elements are defined as block level elements or as inline elements.
Block level elements normally start (and end) with a new line when displayed in a browser.
Examples: <h1>, <p>, <ul>, <table>

HTML Inline Elements

Inline elements are normally displayed without starting a new line.
Examples: <b>, <td>, <a>, <img>



HTML Grouping Tags

Tag Description
<div> Defines a section in a document (block-level)
<span> Defines a section in a document (inline)    




HTML Forms

HTML forms are used to pass data to a server.
An HTML form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements.
The <form> tag is used to create an HTML form:
<form>
.
input elements
.
</form>


HTML Forms - The Input Element

The most important form element is the <input> element.
The <input> element is used to select user information.
An <input> element can vary in many ways, depending on the type attribute. An <input> element can be of type text field, checkbox, password, radio button, submit button, and more.
The most common input types are described below.

Text Fields

<input type="text"> defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
How the HTML code above looks in a browser:
First name:
Last name:
Note: The form itself is not visible. Also note that the default width of a text field is 20 characters. 

Password Field

<input type="password"> defines a password field:
<form>
Password: <input type="password" name="pwd">
</form>
How the HTML code above looks in a browser:
Password:
Note: The characters in a password field are masked (shown as asterisks or circles).

Radio Buttons

<input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE of a limited number of choices:
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>
How the HTML code above looks in a browser:
Male
Female

Checkboxes

<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE options of a limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
How the HTML code above looks in a browser:
I have a bike
I have a car

Submit Button

<input type="submit"> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. The file defined in the action attribute usually does something with the received input:
<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user">
<input type="submit" value="Submit">
</form> 
 

TML Form Tags

New : New tags in HTML5.
Tag Description
<form> Defines an HTML form for user input
<input> Defines an input control
<textarea> Defines a multiline input control (text area)
<label> Defines a label for an <input> element
<fieldset> Groups related elements in a form
<legend> Defines a caption for a <fieldset> element
<select> Defines a drop-down list
<optgroup> Defines a group of related options in a drop-down list
<option> Defines an option in a drop-down list
<button> Defines a clickable button
<datalist>New Specifies a list of pre-defined options for input controls
<keygen>New Defines a key-pair generator field (for forms)
<output>New Defines the result of a calculation
 

HTML Iframes

 An iframe is used to display a web page within a web page.

Syntax for adding an iframe:
<iframe src="URL"></iframe> 
 

Tables

<table border="1">
  <tr>
    <th>table header</th>
    <th>table header</th>
  </tr>
  <tr>
    <td>table data</td>
    <td>table data</td>
  </tr>
</table>

Iframe

<iframe src="demo_iframe.htm"></iframe>

Forms

<form action="demo_form.asp" method="post/get"> <input type="text" name="email" size="40" maxlength="50">
<input type="password">
<input type="checkbox" checked="checked">
<input type="radio" checked="checked">
<input type="submit" value="Send">
<input type="reset">
<input type="hidden">
<select>
<option>Apples</option>
<option selected="selected">Bananas</option>
<option>Cherries</option>
</select>
<textarea name="comment" rows="60" cols="20"></textarea>

</form>

Entities

&lt; is the same as <
&gt; is the same as >
&#169; is the same as © 


Tuesday 15 January 2013

Linux : Check Network Connection Command

  1. ss command: It dump socket (network connection) statistics such as all TCP / UDP connections, established connection per protocol (e.g., display all established ssh connections), display all the tcp sockets in various state such as ESTABLISHED or FIN-WAIT-1 and so on.
  2. netstat command: It can display network connections, routing tables, interfaces and much more.
  3. tcptrack and iftop commands: Displays information about TCP connections it sees on a network interface and display bandwidth usage on an interface by host respectively.

Display Currently Established, Closed, Orphaned and Waiting TCP sockets, enter:

# ss -s
Or you can use the netstat command as follows:
# netstat -s

Display All Open Network Ports

Use the ss command as follows:
# ss -l

OR Use the netstat command as follows:
# netstat -tulpn

Display All TCP Sockets

Type the ss command as follows:
# ss -t -a
Or use the netstat command as follows:
# netstat -nat

Display All UDP Sockets

Type the ss command as follows:
# ss -u -a
Or use the netstat command as follows:
# netstat -nau

lsof Command

# lsof -i :portNumber
# lsof -i tcp:portNumber
# lsof -i udp:portNumber
# lsof -i :80 | grep LISTEN

View Established Connections Only

Use the netstat command as follows:
# netstat -natu | grep 'ESTABLISHED'

Say Hello To tcptrack

The tcptrack command displays the status of TCP connections that it sees on a given network interface. tcptrack monitors their state and displays information such as state, source/destination addresses and bandwidth usage in a sorted, updated list very much like the top command.
# tcptrack -i eth0

iftop command

The iftop command listens to network traffic on a given network interface such as eth0, and displays a table of current bandwidth usage by pairs of hosts:
# iftop -i eth1
It can display or analyses packet flowing in and out of the 192.168.1.0/24 network:
# iftop -F 192.168.1.0/24

Monday 14 January 2013

JSP - Java Server Pages

JSP(Java Server Pages)是由Sun Microsystems公司倡导、许多公司参与一起建立的一种动态网页技术标准。
JSP技术有点类似ASP技术,它是在传统的网页HTML文件(*.htm,*.html)中插入Java程序段(Scriptlet)和JSP标记(tag),
从而形成JSP文件(*.jsp)。 用JSP开发的Web应用是跨平台的,既能在Linux下运行,也能在其他操作系统上运行。
 
JSP技术使用Java编程语言编写类XML的tags和scriptlets,来封装产生动态网页的处理逻辑。网页还能通过tags和
scriptlets访问存在于服务端的资源的应用逻辑。JSP将网页逻辑与网页设计和显示分离,支持可重用的基于组件的设计,
使基于Web的应用程序的
开发变得迅速和容易。 

Web服务器在遇到访问JSP网页的请求时,首先执行其中的程序段,然后将执行结果连同JSP文件中的HTML代码一起
返回给客户。插入的Java程序段可以操作数据库、重新定向网页等,以实现建立动态网页所需要的功能。 

JSP与Java Servlet一样,是在服务器端执行的,通常返回该客户端的就是一个HTML文本,因此客户端只要有浏览器就
能浏览。 

JSP的1.0规范的最后版本是1999年9月推出的,12月又推出了1.1规范。目前较新的是JSP1.2规范,JSP2.0规范的征求
意见稿也已出台。

JSP页面由HTML代码和嵌入其中的Java代码所组成。服务器在页面被客户端请求以后对这些Java代码进行处理,然后
将生成的HTML页面返回给客户端的浏览器。Java Servlet 是JSP的技术基础,而且大型的Web应用程序的开发需要Java 
Servlet和JSP配合才能完成。JSP具备了Java技术的简单易用,完全的面向对象,具有平台无关性且安全可靠,主要面向
因特网的所有特点。 

1. JSP技术的强势 

(1)一次编写,到处运行。在这一点上Java比PHP更出色,除了系统之外,代码不用做任何更改。

(2)系统的多平台支持。基本上可以在所有平台上的任意环境中开发,在任意环境中进行系统部署,在任意环境中扩展。
相比ASP/PHP的局限性是现而易见的。 

(3)强大的可伸缩性。从只有一个小的Jar文件就可以运行Servlet/JSP,到由多台服务器进行集群和负载均衡,到多台
Application进行事务处理,消息处理,一台服务器到无数台服务器,Java显示了一个巨大的生命力。 

(4)多样化和功能强大的开发工具支持。这一点与ASP很像,Java已经有了许多非常优秀的开发工具,而且许多可以免
费得到,并且其中许多已经可以顺利的运行于多种平台之下。 

2. JSP技术的弱势 

(1) 与ASP一样,Java的一些优势正是它致命的问题所在。正是由于为了跨平台的功能,为了极度的伸缩能力,所以
极大的增加了产品的复杂性。 

(2) Java的运行速度是用class常驻内存来完成的,所以它在一些情况下所使用的内存比起用户数量来说确实是“最低
性能价格比”了。从另一方面,它还需要硬盘空间来储存一系列的.java文件和.class文件,以及对应的版本文件。 
 
__________________________________________________________________________________
 
1. Download & install JDK, JBoss, Apache-maven
 
2. Set environment variable for JAVA_HOME, JBOSS_HOME, M2_HOME & PATH
 
3. create the jsp file.
 
4. create the web.xml in the WEB-INF directory.
 
5. run command to generate war file: 
        jar cvf XXX.war XXX.jsp WEB-INF
 
6. put the war file in the %JBOSS_HOME%\standalone\deployments directory.
 
7. execute the JBoss web server using standalone.bat
 
8. URL to be used: http://localhost:8080/XXX/XXX.jsp

__________________________________________________________________________________  
 
Important: 
1. The character sequences <%= and %> enclose Java expressions, which are evaluated at run time.
2.   JSP allows user to write blocks of Java code inside the JSP by placing your Java code between <% and %> 
character (just like expressions, but without the = sign at the start of the sequence.)
3. Instead of using an expression, we are generating the HTML directly
by printing to the "out" variable.  The "out" variable is of type javax.servlet.jsp.JspWriter. 
      out.println("xxxxxxxx");
 
 

<jsp:useBean> in JSP

        
Syntax:  
<jsp:useBean id= "nameOfInstance" scope= "page | request | session | application" class= "package.class" type= "package.class > </jsp:useBean>.

The child tags of <jsp:useBean> are:
<jsp:setProperty name = "nameOfBeanInstance" property="*"  | propertyName ("parameterName")  | value=string | <%= expression%> >
<jsp:getProperty name="nameOfBeanInstance" property="propertyName"/>
Scope of <jsp:useBean>

1. page: It means that we can use the Bean within the JSP page.
2. request: It means that we can use the Bean from any JSP page processing the same request.
3. session: It means that we use the Bean from any Jsp page in the same session as the JSP page that created the Bean.
4. application: It means that we use the Bean from any page in the same application as the Jsp page that created the Bean.

Print HTML with Header & Footer on Each Page

Method 1: Add a page break at the bottom of each page

Layout onePageOfLayout = new VLayout(){{
            :
            : 
           final ListGrid contentGrid;
           contentGrid= new ListGrid () {{
              setDataSource(reportDataSource);
              setHeight("65%");
              setPrintWrapCells(false);
              setPrintAutoFit(false);

              setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATE);
              ListGridHelper.setDataSourceFields(this,
                   lineItemColumns
                   );
         }};


            setPadding(0);

            //Layout's addMember(...) function's argument can be
            // Label, DynamicForm, ListGrid
            addMember(headerForm);
            addMember(ContentForm);
            addMember(footerForm);
           
            if(isNotLastPage){
                HTMLPane pageBreakElement = new HTMLPane(){{
                    setLayoutAlign(VerticalAlignment.BOTTOM);
                }};
                pageBreakElement.setContents("<div style='page-break-after:always'></div>");
                addMember(pageBreakElement);
            }

           
        }};


Method 2: Print documents in PDF format (1)

import java.io.FileOutputStream;
import java.util.Date;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
 
:
: 

private static String FILE = "c:\example1.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMA
Document document = new Document();
      PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open(); 
// add a paragraph to the document
Paragraph para = new Paragraph();
para .add(new Paragraph( 
        "This paragraph describes something which is very important ",
        new Font(Font.FontFamily.TIMES_ROMAN, 16,
                 Font.BOLD))); 
:
: 
document.add(para);
// Start a new page
document.newPage();
 
document.close();
 

Method 2: Print documents in PDF format (2)

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Set;
import java.util.TreeSet;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
:
 
public void createPdf(String filename)
        throws IOException, DocumentException, SQLException {

        // step 1
        Document document = new Document(PageSize.A4, 36, 36, 54, 36);
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, 
                                                             new FileOutputStream("example2.pdf"));
        TableHeader event = new TableHeader();
        writer.setPageEvent(event);
        // step 3 - fill in the document
        document.open();

        event.setHeader("Hello!");
        document.add(new Paragraph("Testing."));
        document.newPage();
        event.setHeader("There!");
        document.add(new Paragraph("Testing."));

        document.close();
    } 
Line Spacing
Paragraph objects knows how to add line spacing if the added text exceeds the right edge of the document. Line spacing is measured in user units. There are 72 units per inch. The default spacing is 1.5 times the font height. You can change the line spacing by passing spacing as a parameter to the Paragraph constructor, like this:
    Paragraph paragraph = new Paragraph(50);

Spacing Before and After Paragraph
You can also set the spacing before and after a paragraph. Here is how you do that in code:
   paragraph.setSpacingAfter(50); 
   paragraph.setSpacingBefore(50);

Alignment
You can set the alignment of the paragraph using the setAlignment() method. This sets what side of the page the text is aligned to. Here is an example:
    paragraph.setAlignment(Element.ALIGN_LEFT);   
    paragraph.setAlignment(Element.ALIGN_CENTER); 
    paragraph.setAlignment(Element.ALIGN_RIGHT);

Indentation
You can set the left and right indentation of the paragraph. This moves the paragraph content further away from the edges of the page. Here is the code to do that:
    paragraph.setIndentationLeft(50); 
    paragraph.setIndentationRight(50);

Method 3: HTML Print Header & Footer

<div class="divFooter">UNCLASSIFIED</div>
CSS:
<style type="text/css">
    @media screen {
        div.divFooter {
            display: none;
        }
    }
    @media print {
        div.divFooter {
            position: fixed;
            bottom: 0;
        }
    }
</style>
 
----------------------------------------------------------
 
<span class="printspan">UNCLASSIFIED</span>

And in your CSS, do something like this:
<style type="text/css" media="screen"> .printspan { display: none; } </style> <style type="text/css" media="print"> .printspan { display: inline; font-family: Arial, sans-serif; font-size: 16 pt; color: red; } </style>
 
---------------------------------------------------------- 
 
Use page breaks to define the styles in CSS:
@media all
  {
  #page-one, .footer, .page-break { display:none; }
  }

@media print
  {
  #page-one, .footer, .page-break   
    { 
    display: block;
    color:red; 
    font-family:Arial; 
    font-size: 16px; 
    text-transform: uppercase; 
    }
  .page-break
    {
    page-break-before:always;
    } 
}
Then add the markup in the document at the appropriate places:
<h2 id="page-one">unclassified</h2>
<!-- content block -->
<h2 class="footer">unclassified</h2>
<h2 class="page-break">unclassified</h2>
<!-- content block -->
<h2 class="footer">unclassified</h2>
<h2 class="page-break">unclassified</h2>
<!-- content block -->
<h2 class="footer">unclassified</h2>
<h2 class="page-break">unclassified</h2>
<!-- content block -->
<h2 class="footer">unclassified</h2>
<h2 class="page-break">unclassified</h2>
 

Tuesday 1 January 2013

More Secure SSH Settings



$ vi /etc/ssh/sshd_config

PermitRootLogin no                      # Disable Root Logins

AllowUsers Who1 Who2               # Limit User Logins

Protocol 2                                     # protocol 2 is more secure

Port 1234                                     # Run ssh on a non-standard port

$ service sshd restart

7. Use Public/Private Keys for Authentication


Using encrypted keys for authentication offers two main benefits. Firstly, it is convenient as you no longer need to enter a password (unless you encrypt your keys with password protection) if you use public/private keys. Secondly, once public/private key pair authentication has been set up on the server, you can disable password authentication completely meaning that without an authorized key you can't gain access - so no more password cracking attempts.
It's a relatively simple process to create a public/private key pair and install them for use on your ssh server.
First, create a public/private key pair on the client that you will use to connect to the server (you will need to do this from each client machine from which you connect):
$ ssh-keygen -t rsa

This will create two files in your (hidden) ~/.ssh directory called id_rsa and id_rsa.pub. id_rsa is your private key and id_rsa.pub is your public key.
If you don't want to still be asked for a password each time you connect, just press enter when asked for a password when creating the key pair. It is up to you to decide whether or not you should password encrypt your key when you create it. If you don't password encrypt your key, then anyone gaining access to your local machine will automatically have ssh access to the remote server. Also, root on the local machine has access to your keys although one assumes that if you can't trust root (or root is compromised) then you're in real trouble. Encrypting the key adds additional security at the expense of eliminating the need for entering a password for the ssh server only to be replaced with entering a password for the use of the key.
Now set permissions on your private key:
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/id_rsa 

Copy the public key (id_rsa.pub) to the server and install it to the authorized_keys list:
$ cat id_rsa.pub >> ~/.ssh/authorized_keys

Note: once you've imported the public key, you can delete it from the server.
and finally set file permissions on the server:
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys

The above permissions are required if StrictModes is set to yes in /etc/ssh/sshd_config (the default).
Now when you login to the server you won't be prompted for a password (unless you entered a password when you created your key pair). By default, ssh will first try to authenticate using keys. If no keys are found or authentication fails, then ssh will fall back to conventional password authentication.
Once you've checked you can successfully login to the server using your public/private key pair, you can disable password authentication completely by adding the following setting to your /etc/ssh/sshd_config file:
# Disable password authentication forcing use of keys

hibernate



 Business Object
A layer between your application code and the DAOs
○ Only allow business objects to hit the DAOs
○ Business objects and app code use persistent objects
Provide a consistent place to use AOP
○ try/catch/finally for transactions
Risk duplicating DAO code
○ Sometimes business object methods just delegate

DAOs
Insulate your code from Hibernate specifics
CRUD operations
○ I use Java 5 generics heavily
○ You can also use Spring for DAO support
Locating persistent objects
○ Use Hibernate queries for efficiency
○ From there, walk the graph using normal Java
collections semantics
Detached objects can be challenging

What is Hibernate?

Hibernate is a high-performance Object/Relational persistence and query service (Object/Relational Mapping (ORM) solution for JAVA).

○ Open source – GNU Lesser General Public License (LGPL)
○ http://www.hibernate.org/ (JBoss Group)


Lets you avoid SQL
Works with (almost) all relational DBs
○ DB2/NT, FrontBase, HSQLDB, Informix Dynamic Server, Ingres, Interbase,
Mckoi, MySQL, Oracle, Pointbase, PostgreSQL, Progress,
SAP DB, Microsoft SQL Server, Sybase SQL Server, etc...
○ Or you can extend one of the Dialect classes

Has a huge feature list
○ Go to their web site – we don't have time

Maps JavaBeans (POJOs) to tables
○ XML defines the mappings
○ Very few bean requirements

SQL is generated at app startup time
○ As opposed to bytecode manipulation
○ New database? No problem! Change a few props


 
Following is a very high level view of the Hibernate Application Architecture.

Following is a detailed view of the Hibernate Application Architecture with few important core classes.
 


 1) Configuration Object
 Create the Hibernate Configuration objects for Hibernate application.
  • Database connection: This is handled through one or more configuration files supported by Hibernate. hibernate.properties and hibernate.cfg.xml
  • Class Mapping Setup : This component creates the connection between the Java classes and database tables.
2) SessionFactory Object
 Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application.
The SessionFactory is is heavyweight object so usually it is created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.


3) Session Object
Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.


4) Transaction Object
A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose


5) Query Object
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

6) Criteria Object:
Criteria object are used to create and execute object oriented criteria queries to retrieve objects.

 Hibernate Environment Setup
1. Download & install the latest version of Hibernate from http://www.hibernate.org/downloads
2. copy all the Hibernate library files from /lib into your CLASSPATH, and change your classpath variable to include all the JARs.
3. Finally copy hibernate3.jar file into your CLASSPATH. This file lies in the root directoru of the installation and is the primary JAR that Hibernate needs to do its work.

Hibernate Prerequisites:
Following is the list of the packages/libraries required by Hibernate and you should install them before starting with Hibernate. To install these packages you would have to copy library files from /lib into your CLASSPATH, and change your CLASSPATH variable accordingly.

1 dom4j - XML parsing www.dom4j.org/
2 Xalan - XSLT Processor http://xml.apache.org/xalan-j/
3 Xerces - The Xerces Java Parser http://xml.apache.org/xerces-j/
4 cglib - Appropriate changes to Java classes at runtime http://cglib.sourceforge.net/
5 log4j - Logging Faremwork http://logging.apache.org/log4j
6 Commons - Logging, Email etc. http://jakarta.apache.org/commons
7 SLF4J - Logging Facade for Java http://www.slf4j.org

Compilation and Execution:
Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.
1. Create hibernate.cfg.xml configuration file as explained in configuration chapter.
2. Create Employee.hbm.xml mapping file as shown above.
3. Create Employee.java source file as shown above and compile it.
4. Create ManageEmployee.java source file as shown above and compile it.
5. Execute ManageEmployee binary to run the program.


Persistent Objects
POJOs - Plain Old Java Objects
○ No base class or interface requirement
Must have public no-arg constructor
 Should have getter/setters
○ Or Hibernate can access fields directly
○ Hibernate uses JavaBeans property names
For mappings as well as in queries
Serializable is recommended
XDoclet tags are useful but not required

Gotchas
Must always have an open session
○ Seemingly innocent code like fetching a lazy
collection bombs
○ Swing – open a session on event thread
○ Servlets – use a filter or Spring
Hibernate tasks do not abort Ant
○ No failonerror attribute
○ Watch the build output carefully
Test associations and collections heavily