Chủ Nhật, 23 tháng 12, 2012

TomEE and NetBeans

Netbeans and TomEE works great together. You can infact add TomEE as an Apache Tomcat server in Netbeans by following the simple steps given below.
Lets assume that you have already downloaded TomEE and you have NetBeans already setup.So to begin lets just create a Java Web project in NetBeans (Assuming you have basic working knowledge with NetBeans and you know how to create and run a web project in NetBeans). In the server screen we can add TomEE like the given screenshot below.
alt text
Now hit next. In the next step you need to select the folder where the TomEE server is present.
alt text
As soon as you hit finish your work is done. NetBeans would add the manager user in the tomcat server and also you will get back to the project creation window. Continue to the step for choosing your favorite web framework and complete the project creation process. Once the project is created just run it once to see if everything is fine.
Working with OpenJPA in Netbeans
Let us move to the point where we will do the more interesting part. We will configure OpenJPA in Netbeans so that the netbeans Entity generator can nicely work work OpenJPA and TomEE. So to do that you need to first create a connection to a database. Lets assume that we create one for MySQL server as shown in the screenshot below.
alt text
So once this connection is there we are ready to create Entity classes from the selected database. To do that follow the menu as shown in the screenshot below. alt text
Once you select "Entity Classes from Database" You will be presented with the follow dialog
alt text
In this dialog first of all we would select the connection that we created before from the top dropdown. Once you select the connection Netbeans would bring all the tables in "Available Tables" list. You can hit "Add All" to select all tables for entity class generation. Now lets hit "Next" and go to the next screen. And then again hit next and in the next screen hit finish. You can accept all the defaults that are given by the system and finish the Entity creation wizard. With this you are done creating the entities. But as soon as you are done creating the entities You will get a failed message from TomEE server (In case your TomEE server is running). This is because by default Netbeans generate Entity classes using Eclipselink which is not present in TomEE. So to make everybody happy. Next we will configure OpenJPA. To do that you need to open the persistence.xml file from the project (Project explorer -> double click on persistence.xml). This would open the persistence.xml editor window. As shown below
alt text
Now in this window we will select "New Persistence Library" option from the Persistence Library dropdown. This will open the following dialog box.
alt text
Here you need to choose the following two jar files from the TomEE installation folder - javaee-api-6.0-4-tomcat.jar and openjpa-asm-shaded-2.2.0.jar. Do make sure that you are choosing the jar files from the same location where your TomEE server is. Once you choose the proper libraries hit Ok to close the dialog and go back to the persistence.xml editor screen of netbeans.
alt text
Now here from the persistence library choose OpenJPA and save the file as shown in the above screenshot. Now just restart the server once and you are all set to run TomEE with JPA.
Do remember you may need to set your tomcat server in development mode so that your app gets deployed live. to do that you can follow the instructions given in the JSP hot deployment section following link

Source: http://tomee.apache.org/tomee-and-netbeans.html

Thứ Tư, 31 tháng 10, 2012

How to Import from Excel to Oracle with SQL Developer

For our example I’ll be using HR.EMPLOYEES to build the XLS file. I have created a blank copy of the table in another schema and want to import the data from my excel file over.

Step 0: The Empty Oracle Table and your Excel File

You have an Oracle table and you have one or more Excel files.

 Data here but not there!?!

Step 1: Mouse-right click – Import Data

 Yes, it's that easy.

Step 2: Select your input (XLS) file

Yes, we also support XLSX, CSV, etc

Step 3: Verify the data being read

Mind the headers!
Does your Excel file have column headers? Do we want to treat those as a row to the table? Probably not. The default options take care of this. You can also choose to preview more than 100 rows.
Here’s what it looks like if you uncheck the ‘Header’ box

 Sometimes you may want the column headers as a row in the table?
Sometimes your Excel file has multiple headers, or you may need to only import a certain subset of the spreadsheet. Use the ‘Skip Rows’ option to get the right data.

Step 4: Create a script or import automatically 

 Script or do it for me?
For this exercise the ‘Insert’ method will be used.

Step 5:

 Choose the Excel columns to be imported
You may have an Excel file with 100 columns but your table only has 30. This is where you tell SQL Developer what columns are to be used for the import. You can also change up the column order, which may make the next step a bit easier.

Step 6: 

 If you’re not paying attention and just letting the wizard guide you home, then now is the time to wake up. There’s a good chance the column order of the Excel file won’t match the definition of your table. This is where you will tell SQL Developer what columns in the spreadsheet match up to what columns in the Oracle table.

Step 7: Verify your settings

Hit the ‘verify’ button. Fix any mistakes.

SQL Developer is telling you it doesn’t know how to reconcile the data for this DATE column. We need to know what the DATE FORMAT is.

So we need to go back to the Column definition wizard and inspect the HIRE_DATE column settings.



You need to look at how the dates are stored in the spreadsheet and write them in terms that Oracle can understand. This will be used on the INSERTs via a TO_DATE() function that will turn your Excel string into an actual DATE value.
After correcting this, go back to the Verification screen and see if that fixes the problem.

Step 8: 


Everything looks right!
Click on the ‘Finish’ button.

Step 9: Verify the import look at your new table data


  The data is there and the dates look right!
Note the ‘Log’ panel. SQL Developer is processing the records in batches of 50. No errors and the data is there!
 Source: http://www.thatjeffsmith.com/archive/2012/04/how-to-import-from-excel-to-oracle-with-sql-developer/

Thứ Tư, 24 tháng 10, 2012

VARRAY in Oracle and Java

Inserting a VARRAY Value into an Oracle Table Using a Prepared Statement:
try {
    // Create an oracle.sql.ARRAY object to hold the values
    oracle.sql.ArrayDescriptor arrayDesc =
        oracle.sql.ArrayDescriptor.createDescriptor("number_varray", connection);
    int arrayValues[] = {123, 234};
    oracle.sql.ARRAY array = new oracle.sql.ARRAY(arrayDesc, connection, arrayValues);

    // Create a prepared statement for insertion into varray_table
    PreparedStatement ps =
        connection.prepareStatement("INSERT INTO varray_table VALUES(?)");

    // Set the values to insert
    ((oracle.jdbc.driver.OraclePreparedStatement)ps).setARRAY(1, array);

    // Insert the new row
    ps.execute();
} catch (SQLException e) {
}
 
Creating a VARRAY Type in an Oracle Database
try {
    Statement stmt = connection.createStatement();

    // Create a 10-element VARRAY of NUMBERs
    stmt.execute("CREATE TYPE number_varray AS VARRAY(10) OF NUMBER(12, 2)");

    // Create a table with a column to hold the new VARRAY type
    stmt.execute("CREATE TABLE VARRAY_TABLE(col_number_array number_varray)");
} catch (SQLException e) {
}
 
Getting a VARRAY Value from an Oracle Table
try {
    // Create a statement
    Statement stmt = connection.createStatement();

    // Select rows from varray_table
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM varray_table");

    // Get the VARRAY values from each row
    while (resultSet.next()) {
        // Get the VARRAY value in the first column
        oracle.sql.ARRAY array = ((oracle.jdbc.driver.OracleResultSet)resultSet).getARRAY(1);

        // Get the VARRAY elements; values.length is the number of values in the VARRAY
        java.math.BigDecimal[] values = (java.math.BigDecimal[])array.getArray();
    }
} catch (SQLException e) {
}
 
Inserting a VARRAY Value into an Oracle Table
try {
    // Create a statement
    Statement stmt = connection.createStatement();

    // Insert a row with an array of two values
    stmt.execute ("INSERT INTO varray_table VALUES(number_varray(123, 234))");
} catch (SQLException e) {
} 


Source: http://www.exampledepot.com/

Three Ways To Transpose Rows Into Columns in Oracle SQL

Have you ever been in a situation where you as a developer knows that your data is stored in your table rows, but your customer don’t care…wanting to present the data as columns?In this tutorial I will discuss three different variants on how to transpose table rows into columns. By using SUM + DECODE, the new Oracle 11g PIVOT operator, and by using WITH + sub SELECTs.

Introduction

According to Wikipedia®, one definition of the word “transpose”  is:
A matrix obtained from a given matrix by interchanging each row and the corresponding column.
There are many technical variants on what transposing really is, but in our case it is simply to present row values as columns. This is very helpful if you i.e. want to present data in a crosstab, or matrix. An example can i.e. be that you have your order table where each row has an order date, and you want to present the sales per month (extracted from the order date) in columns. A very common situation in Data Warehouse reporting.
This functionality has existed a long time in Excel (transpose when you use “Paste Special..“), reporting tools like Web Intelligence (Business Objects), etc.
In Oracle it has been possible to mimic this functionality for a long time…but until version 11g, it had not been a thought through functionality.
We are going to look at three of the most common ways to do row to column transposing.

Examples

For our three examples we are going to use the following query as a base:

SQL> SELECT    o.order_mode
  2          ,o.order_status
  3          ,SUM(o.order_total) order_total
  4  FROM    orders o
  5  GROUP BY o.order_mode, o.order_status
  6  ORDER BY o.order_mode
  7          ,o.order_status
  8  /

ORDER_MODE ORDER_STATUS ORDER_TOTAL
---------- ------------ -----------
direct                0    163131.3
direct                1    227569.5
direct                2    166169.5
direct                3    206659.4
direct                4     56352.5
direct                5    172586.2
direct                6      115968
direct                7     33617.1
direct                8    545300.5
direct                9    205674.2
direct               10       10601
online                0     25976.7
online                2    103834.4
online                3     56381.7
online                4    700068.1
online                5    183261.2
online                6     90411.8
online                8    322192.5
online                9     57062.4
online               10    225236.7

20 rows selected


 What we want to do is to present the data like this:
ORDER_MODE     STAT_0     STAT_1     STAT_2     STAT_3     STAT_4     STAT_5     STAT_6     STAT_7     STAT_8     STAT_9    STAT_10
---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
DIRECT       163131.3   227569.5   166169.5   206659.4    56352.5   172586.2     115968    33617.1   545300.5   205674.2      10601
ONLINE        25976.7              103834.4    56381.7   700068.1   183261.2    90411.8              322192.5    57062.4   225236.7


Ok, let’s get down to some business…

Example # 1a: Transpose rows into columns using SUM and DECODE to summarize data

Before version 11g of Oracle this method of transposing data was probably the most proficient. It is actually the exact query that generated the data result shown above.

SQL> SELECT    UPPER(o.order_mode) order_mode
  2          ,SUM(DECODE(o.order_status, 0, o.order_total)) stat_0
  3          ,SUM(DECODE(o.order_status, 1, o.order_total)) stat_1
  4          ,SUM(DECODE(o.order_status, 2, o.order_total)) stat_2
  5          ,SUM(DECODE(o.order_status, 3, o.order_total)) stat_3
  6          ,SUM(DECODE(o.order_status, 4, o.order_total)) stat_4
  7          ,SUM(DECODE(o.order_status, 5, o.order_total)) stat_5
  8          ,SUM(DECODE(o.order_status, 6, o.order_total)) stat_6
  9          ,SUM(DECODE(o.order_status, 7, o.order_total)) stat_7
 10          ,SUM(DECODE(o.order_status, 8, o.order_total)) stat_8
 11          ,SUM(DECODE(o.order_status, 9, o.order_total)) stat_9
 12          ,SUM(DECODE(o.order_status, 10, o.order_total)) stat_10
 13  FROM    orders o
 14  GROUP BY o.order_mode
 15  ORDER BY 1
 16  /

ORDER_MODE     STAT_0     STAT_1     STAT_2     STAT_3     STAT_4     STAT_5     STAT_6     STAT_7     STAT_8     STAT_9    STAT_10
---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
DIRECT       163131.3   227569.5   166169.5   206659.4    56352.5   172586.2     115968    33617.1   545300.5   205674.2      10601
ONLINE        25976.7              103834.4    56381.7   700068.1   183261.2    90411.8              322192.5    57062.4   225236.7


As you probably see, for each of the eleven possible order_status values, there is a “stat_x” line. If we had twelve values…well…then it would have been twelve “stat_x” fields. This is actually one of the situations where I find it easier to use a DECODE function, rather than CASE. If you want to know about the difference between CASE, and DECODE – please take a look at the post named “Oracle DECODE and CASE: What is the difference“.

Example # 1b: Transpose rows into columns using MAX and DECODE – for non-summarized data

I want to show another variant of this (above) query as well.
Let us pretend we are going to help our MLM (Multi Level Marketing) company with calculating commission for our distributors, and we want to calculate everything using three different rate scenarios to be able to measure the commission impact against each other. And, we just want to show all the rates in a nice way, grouped by each scenario.
Ok, this is the data we start out with:

SQL> col scenario format a10
SQL> SELECT    r.scenario
  2          ,r.currency
  3          ,r.rate
  4  FROM    rates r
  5  /

  SCENARIO CURRENCY       RATE
---------- -------- ----------
         1 USD            1.00
         1 CAD            1.45
         1 MYR            3.34
         1 NOK            6.08
         2 USD            1.00
         2 CAD            1.47
         2 MYR            3.47
         2 NOK            6.12
         3 USD            1.00
         3 CAD            1.51
         3 MYR            2.98
         3 NOK            5.96

12 rows selected


 To show a nice crosstab version of our data, the query below would do the trick:

SQL> SELECT    x.scenario
  2          ,MAX(DECODE(x.currency, 'CAD', x.rate)) CAD_rate
  3          ,MAX(DECODE(x.currency, 'MYR', x.rate)) MYR_rate
  4          ,MAX(DECODE(x.currency, 'NOK', x.rate)) NOK_rate
  5          ,MAX(DECODE(x.currency, 'USD', x.rate)) USD_rate
  6  FROM    (
  7              SELECT    r.scenario
  8                      ,r.currency
  9                      ,r.rate
 10              FROM    rates r
 11          ) x
 12  GROUP BY x.scenario
 13  /

  SCENARIO   CAD_RATE   MYR_RATE   NOK_RATE   USD_RATE
---------- ---------- ---------- ---------- ----------
         1       1.45       3.34       6.08          1
         2       1.47       3.47       6.12          1
         3       1.51       2.98       5.96          1


BTW – The rates shown are totally random…

Example # 2:  Transpose rows into columns using the Oracle PIVOT operator

The PIVOT and the UNPIVOT operators were introduced in Oracle version 11g. The following query will give the same result as the query above, just by using the PIVOT operator.

SQL> SELECT    UPPER(order_mode)
  2          ,stat_0
  3          ,stat_1
  4          ,stat_2
  5          ,stat_3
  6          ,stat_4
  7          ,stat_5
  8          ,stat_6
  9          ,stat_7
 10          ,stat_8
 11          ,stat_9
 12          ,stat_10
 13  FROM    (
 14              SELECT    o.order_mode
 15                      ,o.order_status
 16                      ,SUM(o.order_total) order_total
 17              FROM    orders o
 18              GROUP BY o.order_mode, o.order_status
 19          )
 20  PIVOT    (
 21              SUM(order_total) FOR order_status IN (0 stat_0, 1 stat_1, 2 stat_2, 3 stat_3, 4 stat_4, 5 stat_5, 6 stat_6, 7 stat_7, 8 stat_8, 9 stat_9, 10 stat_10)
 22  )
 23  /

UPPER(ORDER_MODE)     STAT_0     STAT_1     STAT_2     STAT_3     STAT_4     STAT_5     STAT_6     STAT_7     STAT_8     STAT_9    STAT_10
----------------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
DIRECT              163131.3   227569.5   166169.5   206659.4    56352.5   172586.2     115968    33617.1   545300.5   205674.2      10601
ONLINE               25976.7              103834.4    56381.7   700068.1   183261.2    90411.8              322192.5    57062.4   225236.7


Example # 3: Transpose rows into columns using WITH and sub SELECTS

Ok, in this example we are going to put our main query inside a WITH statement, and then query the WITH materialized resultset multiple times. Using WITH, the main resultset wil not be recomputed multiple times.

 SQL> WITH main_query AS (
  2                          SELECT    o.order_mode
  3                                  ,o.order_status
  4                                  ,SUM(o.order_total) order_total
  5                          FROM    orders o
  6                          GROUP BY o.order_mode, o.order_status
  7  )
  8  SELECT    UPPER(x.order_mode) order_mode
  9          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 0 ) stat_0
 10          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 1 ) stat_1
 11          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 2 ) stat_2
 12          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 3 ) stat_3
 13          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 4 ) stat_4
 14          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 5 ) stat_5
 15          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 6 ) stat_6
 16          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 7 ) stat_7
 17          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 8 ) stat_8
 18          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 9 ) stat_9
 19          ,(SELECT y.order_total FROM main_query y WHERE y.order_mode = x.order_mode AND y.order_status = 10 ) stat_10
 20  FROM    (
 21              SELECT    DISTINCT m.order_mode
 22              FROM    main_query m
 23          ) x
 24  /

ORDER_MODE     STAT_0     STAT_1     STAT_2     STAT_3     STAT_4     STAT_5     STAT_6     STAT_7     STAT_8     STAT_9    STAT_10
---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
DIRECT       163131.3   227569.5   166169.5   206659.4    56352.5   172586.2     115968    33617.1   545300.5   205674.2      10601
ONLINE        25976.7              103834.4    56381.7   700068.1   183261.2    90411.8              322192.5    57062.4   225236.7


Well, there you have it. Three different ways to get the same data.

Other ways to solve the problem

Although only three different methods are presented here, there are actually other ways to transpose the data from rows to columns. One of them is to use a WITH statement, and then multiple UNIONs with a SUM of all columns at the end. I will let it be up to you to try this one out. If you really would like to know how to do this, leave a comment below, and I will give you a sample. It is a more cumbersome (reason for not initially showing a sample) way to do the transposing this way.
Yet another possibility, after my understanding, is to use XML in your query. I will give a sample on our PL/SQL site for this one.

Conclusion

As  you can see, there are a few ways to to transpose rows into columns in Oracle. If you have a different..or even better way to do this…we will all love to hear about it. The comment field is made just for you. ;-)
BTW – If you wonder about the data used in the examples, they are from the “OE” sample schema that comes with Oracle. It is normally locked and expired by default.

Hope this help you out in your work,

 Source: http://oracletuts.net/tutorials/three-ways-to-transpose-rows-into-columns-in-oracle-sql/

Thứ Ba, 16 tháng 10, 2012

GZIp Compression for JEE Web Application

GZip is based on the DEFLATE algorithm, which is a combination of LZ77 and Huffman coding. gzip is often also used to refer to the gzip file format, which is:

1. a 10-byte header, containing a magic number, a version number and a time stamp. 2. optional extra headers, such as the original file name.
3. a body, containing a DEFLATE-compressed payload. 4. an 8-byte footer, containing a CRC-32 checksum and the length of the original uncompressed data.
Although its file format also allows for multiple such streams to be concatenated (zipped files are simply decompressed concatenated as if they were originally one file), gzip is normally used to compress just single files . Compressed archives are typically created by assembling collections of files into a single tar archive, and then compressing that archive with gzip. The final .tar.gz or .tgz file is usually called a tarball.
Most of the FE view generation time is tied up in downgrading all the components in the page: like html, images, stylesheets, scripts, ActiveX components and static resources.
Using gzip compression technique we can drastically reduce the size (almost 1/10th of original response content size ,as per spec) of the resources which takes less time, bandwidth to traverse through the wire interns increase the view generation performance.
It Also it provides transport layer encoding.




Steps to Implement
1. Write a GZipFilter through which all request/response should pass to/from Web app Servlet.
2. In filter Check if the requester (For web app its browser) can support gzip encoding or not. by checking "Accept-Encoding" header value of request. This check is necessary because if the requester client does not support gzip encoding then normal operation should be performed without encoding.
4, If client supposts gzip encoding set a response header "Content-Encoding" with value "gzip". It's needed for browser to understand about the meta-data of coming response content.
3. If it's supports gzip encoding set the object of GZipOutputStream in HTTPServletResponseweb app servlet.
4. Web app will write the response byte Stream in GZipOutputStream instead of simple OutputStream and browser will take care of the rest.

JSF Application Tuning (WebApp performance)

SF requires two paths: one to create the tree and one to render it.One of the areas of JSF that We think suffers compared to other models hat it requires two paths instead of one. In JSP,code is compiled directly into Java byte code. That code is then directly executed when the servlet is accessed. As a result, a single path is executed to render the content to the output stream. In JSF, first a component tree is created and renders associated with it. Once that tree is constructed and JSF enters the render phase, the tree is walked completely and content is written to the output stream. Thus, JSF requires two paths: one to create the tree and one to render it.
On plus side it's a cleaner MVC architecture for performing validation, actions, and rendering.

Below are some analysis, suggestions for JSF application settings optimized JSF performance.

In JSF, when the FacesServlet is accessed, it asks its associated view handler implementation to restore or build a view or component tree.. As components are stateful, a new instance must be created per request. Thus, for a very large page with several components, it requires invoking several tag handler classes that end up retrieving the application to get the component which then creates the component by using reflection on the associated class type. This has two impacts to performance.
First, you have to create several components for a given page and each of those invocations require memory allocation, initialization, referencing, setting attributes, etc…very expensive tasks. This also impacts garbage collection by creating excess garbage per request.
Second, it has to use reflection to create the classes and reflection is generally slower than directly invoking the new operator.

Instead of keeping all component as Stateful we could mark a panel group as stateless.
@Stateless
public class UIPanel extends UIComponentBase {
// normal code
}For an input component, you might mark all input components as stateful.
@Stateful
public class UIInput extends UIOutput {
// normal code
}

Remove Serialization Overhead:
Performance measurements have shown that plain server side state saving (without serialization and without compressing state) comes with the best values. State saving at client side is having security concerns as well as overhead of serialization of entire JSF tree every time.

Web app deployment descriptor entry:
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>


Reduce Session overhead:

javax.faces.ViewState is a hidden field in JSF which gets auto generated when the page is deployed as a web application.JSF keeps lots of information about the current page and previous pages in the JSF state object. This allows all of the Faces components to keep track of their state, and also allows the back button to work. Server side state saving is where the component tree and all component state are stored within the user's session. This entry within the session is tracked by writing a key in the response that is used to look up the entry on subsequent post-backs. By default the value of holding state in a single session is 15.

So, If the view is 5K big, in a single session its holding almost 5MB data.For 1000 concurrent user its almost 4.8GB data we are storing into session (Application memory) is unnecessary. It'll give out of memory for sure as 32 bit Application Server (most common open source servers) can only support max 2GB of heap size (for 64 bit it supports max 4GB heap size).

The numberOfViewsInSession parameter is the big one – this only allows three back buttons inside a faces form.Value shoud be given as per application requirement.

Web app deployment descriptor entries: (Optimize values of following parameters can vary according to application requirement)
<context-param>
<param-name>com.sun.faces.numberOfViewsInSession</param-name>
<param-value>3</param-value>
</context-param>

<context-param>
<param-name>com.sun.faces.numberOfLogicalViews</param-name>
<param-value>10</param-value>
</context-param>


Source:  hirenscafe.blogspot.com/2010/03/jsf-application-tuning-webapp.html

Chủ Nhật, 30 tháng 9, 2012

SSL in Tomcat

First Create Certificate file (key store) by using java 'keytool" command utility.
Change the underlined words to suit you.

Second, copy the 'cert.cer' file into tomcat/conf.

Third, modify the 'server.xml' file in conf folder like this below:

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" keystore="conf/cert.cer" keypass="phucnt123"/>


Fourth, edit your web.xml file in tomcat/conf and add the following inside of your container element:     
<!-- Require HTTPS for everything except /img (favicon) and /css. -->
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>HTTPSOnly</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>HTTPSOrHTTP</web-resource-name>
            <url-pattern>*.ico</url-pattern>
            <url-pattern>/img/*</url-pattern>
            <url-pattern>/css/*</url-pattern>
        </web-resource-collection>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

 
Now, start Tomcat and run your web application, you will see your web application will run with HTTPS.

That's it!

Thứ Sáu, 28 tháng 9, 2012

Websockets or Comet or Both? What’s supported in the Java EE land

In preparation for the Atmosphere Framework 1.0.0 release, I’ve started listing what Java EE (or WebServer) supports in terms of Native Comet and WebSockets. This blog describes who supports what. I’ve also added a section describing what transport (WebSocket, Http Streaming, Long Polling or JSONP) Browsers are supporting, again tested using Atmosphere. Of course, Atmosphere supports both matrix, but that’s not the goal of this blog. I’ve also not included SPDY or Server Side Events Support because they are yet to be implemented by the majority of Servers.

Server Supports

The following table describes what Atmosphere supports but it can also be seen as what available in Java EE in general. The third and fourth columns are describing if the server has native support for Comet and WebSocket, by either supporting the ugly Servlet 3.0 API or if they have native implementation. The same apply for WebSockets native support (there is no WebSocket standard yet). Last four columns list the “most” popular transport, e.g WebSockets, Http Streaming (also called Forever Frame), Long-Polling and JSSONP. Note that servers like Tomcat 5 doesn’t support native Comet or WebSocket, but Comet can always be emulated by blocking a thread (this is what Atmosphere is doing when deployed there).
(LP: long-Polling HS: Http Streaming)
Server Version Native Comet Native WebSocket WebSockets LP HS JSONP
Netty 3.3.x X X X X X X
Jetty 5.x


X X X
Jetty 6.x X

X X X
Jetty 7.x X X X X X X
Jetty 8.x X X X X X X
GlassFish 2.x X

X X X
GlassFish 3.x to 3.1.1 X

X X X
GlassFish 3.1.2 X X X X X X
Tomcat 5.x


X X X
Tomcat 6.x X

X X X
Tomcat 7.0.26 and lower X

X X X
Tomcat 7.0.27 and up X X X X X X
JBoss 5.x


X X X
JBoss 6.x X

X X X
JBoss 7.x X

X X X
WebLogic 10.x X

X X X
WebLogic 11.x and up X

X X X
Resin 2.x


X X X
Resin 3.x X  X
X X X
WebSphere 7.x


X X X
WebSphere 8.x X

X X

Supported Browsers

The current list of Browsers have been tested with Atmosphere using the atmosphere.js Javascript library and the transport they supports.
Browser Version WebSockets Long-Polling Http Streaming JSONP
Firefox 3.x to 8.x
X X X
Firefox 9.x to 11.x X X X X
Chrome 12.x and lower
X X X
Chrome 13.x and higher X X X X
Internet Explorer 6x to 9.x
X X X
Internet Explorer 10.x X X X X
Opera 10.x and lower
X
X
Opera 11.x X X
X
Safari 4.x
X X X
Safari 5.x X X X X
Android 2.x and up
X X X
Safari (iOS) 1.x to 4.x
X X X
Safari (iOS) 5.x X X X X
Note that I haven’t listed private/commercial/proprietary WebSockets implementations like Kaazing and JWebSocket or Pusher or framework like Cometd (who only works properly on Jetty).

Source: http://jfarcand.wordpress.com/2012/04/19/websockets-or-comet-or-both-whats-supported-in-the-java-ee-land/

Thứ Năm, 6 tháng 9, 2012

Java Serializable Interface

When should i implment Serializble interface?

1. From What's this "serialization" thing all about?:

        It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).

        Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."

    So, implement the Serializable interface when you need to store a copy of the object, send them it to another process on the same system or over the network.

    2. Because you want to store or send an object.

    3. It makes storing and sending objects easy. It has nothing to do with security.

Chủ Nhật, 15 tháng 7, 2012

Determine used and free space in a tablespace

SELECT t.tablespace,
       t.totalspace AS " Totalspace(MB)",
       ROUND ( (t.totalspace - fs.freespace), 2) AS "Used Space(MB)",
       fs.freespace AS "Freespace(MB)",
       ROUND ( ( (t.totalspace - fs.freespace) / t.totalspace) * 100, 2)
           AS "% Used",
       ROUND ( (fs.freespace / t.totalspace) * 100, 2) AS "% Free"
  FROM (SELECT ROUND (SUM (d.bytes) / (1024 * 1024)) AS totalspace,
               d.tablespace_name tablespace
          FROM dba_data_files d
        GROUP BY d.tablespace_name) t,
       (SELECT ROUND (SUM (f.bytes) / (1024 * 1024)) AS freespace,
               f.tablespace_name tablespace
          FROM dba_free_space f
        GROUP BY f.tablespace_name) fs
 WHERE t.tablespace = fs.tablespace
ORDER BY t.tablespace;

Thứ Sáu, 13 tháng 7, 2012

Config FTP server

SUN Solaris FTP
SUN Solaris comes with ftp daemon based on WU-FTPd Washington University project.
While not being very enthusiastic about its vulnerabilities discovered over the years and being rather
abandoned by its developers ,still it comes by default and as long as Sun ok with that it is ok with me too.
Below I will shortly introduce configuring it for local user access as well as anonymous one.

By default FTP daemon (in.ftpd) is disabled. Here is the initial state you have it :
root@Solaris# svcs ftp
STATE STIME FMRI
disabled 7:21:44 svc:/network/ftp:default
As ftpd is inet managed daemon more information can be queried from inetadm:
root@Solaris# inetadm -l svc:/network/ftp:default
SCOPE NAME=VALUE
name=”ftp”
endpoint_type=”stream”
proto=”tcp6″
isrpc=FALSE
wait=FALSE
exec=”/usr/sbin/in.ftpd -a”
user=”root”
default bind_addr=”"
default bind_fail_max=-1
default bind_fail_interval=-1
default max_con_rate=-1
default max_copies=-1
default con_rate_offline=-1
default failrate_cnt=40
default failrate_interval=60
default inherit_env=TRUE
default tcp_trace=FALSE
default tcp_wrappers=FALSE
default connection_backlog=10
Insecure you say , well , you are right – let’s sharpen it a bit.
Enable more detailed logging.
root@Solaris# inetadm -m svc:/network/ftp:default tcp_trace=TRUE
root@Solaris# inetadm -l svc:/network/ftp
SCOPE NAME=VALUE
name=”ftp”
endpoint_type=”stream”
proto=”tcp6″
isrpc=FALSE
wait=FALSE
exec=”/usr/sbin/in.ftpd -a”
user=”root”
default bind_addr=”"
default bind_fail_max=-1
default bind_fail_interval=-1
default max_con_rate=-1
default max_copies=-1
default con_rate_offline=-1
default failrate_cnt=40
default failrate_interval=60
default inherit_env=TRUE
tcp_trace=TRUE
default tcp_wrappers=FALSE
default connection_backlog=10
When execution option –a is given (and it is by default) then ftpd will consult /etc/ftpd/ftpaccess
file for additional restrictions and tweaks. Here are the few that are worth enabling.
Uncomment following lines to have more verbose logging available:
log transfers real,guest,anonymous inbound,outbound
xferlog format %T %Xt %R %Xn %XP %Xy %Xf %Xd %Xm %U ftp %Xa %u %Xc %Xs %Xr
Make sure these changes are applied
root@Solaris# svcadm refresh svc:/network/ftp:default
Configure anonymous access.
All the configs so far will allow only local valid users to connect by ftp and be automatically
placed in their respective home directories. To allow anonymous ftp access with dedicated chrooted for that folder there is a special set of tools to use. Actually it is just one script that does all the hard work behind the scenes – creates ftp user, creates directory tree , sets up needed permissions, sets up chrooted environment for the anonymous ftp user.
 
root@Solaris# ftpconfig /export/home/ftp_pub
Updating user ftp
Creating directory /export/home/ftp_pub
Updating directory /export/home/ftp_pub
That is all, now you can login anonymously and download anything from /export/home/ftp_pub/pub directory. To also allow upload there , change the upload option in “/etc/ftpd/ftpaccess” and set accordingly permissions on the Solaris level for the directory pub (777)

root@Solaris#chmod 777 /etc/ftpd/ftpaccess

upload class=anonusers * /pub yes
#upload class=anonusers * * no nodirs
And finally enable it
root@Solaris# svcadm enable ftp
 

Thứ Sáu, 6 tháng 7, 2012

Using the vi Text Editor in Solaris 9

In the world of Solaris, most files are plain text without fancy typographic material, whether text, shell scripts, Web pages, or even C programs. No bold, no multiple font colors, no included graphics. As a result, most Solaris users use vi, a powerful (albeit tricky to learn) text-only editor that enables you enter and modify text quickly. With vi, you must do everything — from cursor motion to search and replace — from the keyboard.

Understanding modes

Perhaps the most puzzling aspect of vi is that it is a modal editor. These are the two modes of operation:
  • Insert mode: If you're in insert mode and type an x, the letter is added to the document at the current cursor point.
  • Command mode: If you're in command mode, the x command causes the letter under the cursor to be deleted, not added.
Fortunately, there's a trick to starting up vi that enables a mode display function on the bottom line of the screen. This display quickly tells you whether you're in insert or command mode. Rather than specify the show mode feature manually each time you start vi, open a terminal window and type the following:
echo "set showmode" >> ~/.exrc
Do that once, and you've created a custom preferences file for vi (yes, it should be called .virc, but that's a long story). You don't have to ever think about it again.

Starting vi

You can start the vi editor from the command line several ways:
  • Type vi on the command line:
$ vi
  • Specify the name of an existing file to edit or a new file to create:
$ vi my.new.file
  • You can also specify a list of filenames if you want. You can finish editing the first file, and then move to the second, and so on to modify a batch of files in sequence.
Start vi by specifying the name you want to create:
$ vi ashley.travels.txt
The File, Edit, View, and other menus are for the terminal application, not vi. The vi program has no fancy interface elements, just whatever you type at the keyboard.
There's no menu at the bottom, just a cursor at the top-left corner and a bunch of tilde symbols (~) running down the left side. The lines prefaced with tilde symbols are placeholders, not part of the file. They're beyond the end of the file being edited.

Entering text

By default, the editor starts out in command mode: Type an x, and you'll hear a beep as the editor tells you that there's nothing to delete. You can move into insert mode several ways, depending on where you want to insert text. In fact, vi has dozens and dozens of commands.
Following are a few some basic commands:
  • To insert just before the current cursor location (where the flashing block is sitting), press i.
  • To insert just after the current cursor location, use a to append text.
  • To insert just above the current line by creating a new blank line, use O (capital o).
  • To insert into a new blank line just below the current line, use o (lowercase o).
Jump into this by pressing i and typing the following:
Gulliver's Travels is the most well-known work of Irish writer Jonathan Swift, famous for his work as a novelist, essayist and satirist. You Betcha!
To make this interesting, add a few random nonsense characters at the end of what you type in.
Notice that the bottom-right corner of your screen says INSERT MODE. That's the show mode feature giving a visual clue of what mode you're in.
To leave insert mode and get back to command mode, press the magic key, Esc. Intelligently, the Esc key has no function in command mode. You can press it any time you want to be in command mode and aren't sure what mode you're in. It just beeps.

Moving in the file

Because vi has no scroll bars and no mouse support, it has a set of keys that you can use in command mode to move around.
On Solaris, you can also use the arrow keys on your keyboard unless you're connected remotely, in which case they may or may not work.
The four key movement keys are h, j, k, and l:
  • h moves one character to the left.
  • j moves one line down.
  • k moves one line up.
  • l moves one character to the right.
Try using these four keys to move around. If these letters start to appear in your document, you're still in insert mode and need to press the Esc key.
  • You can move one word at a time with w or b, depending on whether you want to move forward one word or backward one word.
  • You can jump to the beginning of the line with 0 (zero) and to the end of the line with $.
  • To move page by page, when the file is sufficiently large to have pages of text, use
• ^F to move forward a page
• ^B to move back a page
• ^D to move down half a page
• ^U to move up half a page
  • You can jump to the first line of the file with 0G (zero followed by G) and to the end of the file with G by itself.
Use motion keys to move to the first letter of the extraneous stuff you added to the file. Now press the x key a few times. Each time you press it, you should see the letter under the cursor deleted and the text slide left to fill the now open hole.
Finish up the delete process so that there are no stray characters. Then use the a append function to add a few carriage returns immediately after the period ending the sentence. The cursor should now be on the last line, with at least one blank line separating it from the text in the file.

Including other files

To include the contents of another file, you need to jump to the vi command line.
  • You do this by typing : , at which point the cursor immediately jumps to the bottom-left corner of the screen.
    Type in the following command:
r gullivers.travels.txt
  • After pressing Enter, the contents of the file are injected into the buffer, exactly as you saw in the GNOME Text Editor and CDE Text Editor.

Saving files

The final step on this journey is to save the new file. You started vi with the new filename. To save the file with that name, type one of these commands:
  • :w writes the file and stays in vi.
  • :wq writes the file and quits vi.
ZZ writes out the file if it has changed and then quits, without the command line (:) sequences.
If you entered more than one file, use :w to write out this file and then :n to move to the next file on your list.
To quit and discard the changes that you have made, add a ! to the end of the command, like this:
:q!

Source:  http://www.dummies.com/how-to/content/using-the-vi-text-editor-in-solaris-9.html

Sync Date/Time on Solaris with NTP Server

"Manually" set the clock correctly just once

Sample: ntpdate -b clock.example.org timekeeper.sample.com
 
Set the clock correctly on every boot up
Create the ntp.conf file.
To activate the ntpd daemon, the ntp.conf file must first be created.

# cd /etc/inet
# cp ntp.client ntp.conf

 Edit the ntp.conf file.

 
Sample: 
driftfile /etc/ntp.drift 
# public NTP servers we sync to:  (use these 2 lines ONLY on ntp1 and 
ntp2!)
server clock.example.org
server timekeeper.sample.com

Thứ Năm, 5 tháng 7, 2012

Check Oracle run Cluster Mode or not

SET SERVEROUT ON

DECLARE
BEGIN
    IF DBMS_UTILITY.is_cluster_database
    THEN
        DBMS_OUTPUT.put_line (
            'Your database is running in Parallel server mode');
    ELSE
        DBMS_OUTPUT.put_line (
            'Your database is NOT running in Parallel server mode');
    END IF;
END;

Thứ Tư, 16 tháng 5, 2012

Datatable with row editing and deleting in Primefaces 3

JSF Page

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      xmlns:p="http://primefaces.org/ui">

    <h:head>
        <title>Summary Report Page</title>
    </h:head>
    <h:body>
        <h:form id="form">
            <p:growl id="messages" showDetail="true"/> 
            <p:dataTable id="basic" var="car" value="#{tableBean.carsSmall}" editable="true">
                <p:ajax event="rowEdit" listener="#{tableBean.updateItem(car)}"  />
                <p:column headerText="Model" style="width:125px">
                    <p:cellEditor>
                        <f:facet name="output">
                            <h:outputText value="#{car.model}" />
                        </f:facet>
                        <f:facet name="input">
                            <p:inputText value="#{car.model}" style="width:100%"/>
                        </f:facet>
                    </p:cellEditor>
                </p:column>

                <p:column headerText="Year" style="width:125px">
                    <p:cellEditor>
                        <f:facet name="output">
                            <h:outputText value="#{car.year}" />
                        </f:facet>
                        <f:facet name="input">
                            <p:inputText value="#{car.year}" style="width:100%" label="Year"/>
                        </f:facet>
                    </p:cellEditor>
                </p:column>

                <p:column>
                    <f:facet name="header">
                        Manufacturer
                    </f:facet>
                    <h:outputText value="#{car.manufacturer}" />
                </p:column>

                <p:column>
                    <f:facet name="header">
                        Color
                    </f:facet>
                    <h:outputText value="#{car.color}" />
                </p:column>
                <p:column>
                    <f:facet name="header">
                        Delete
                    </f:facet>
                    <p:commandButton icon="ui-icon-close" title="remove from cart"
                                     actionListener="#{tableBean.removeItem(car)}" update="@form"/>
                </p:column>
                <p:column>
                    <f:facet name="header">
                        Edit
                    </f:facet>
                    <p:rowEditor/>
                </p:column>
            </p:dataTable>
        </h:form>
    </h:body>
</html>
Managed Bean:

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "tableBean")
@ViewScoped
public class TableBean implements Serializable {
   
    private final static String[] colors;
    private final static String[] manufacturers;
    private List<Car> carsSmall;
   
    static {
        colors = new String[10];
        colors[0] = "Black";
        colors[1] = "White";
        colors[2] = "Green";
        colors[3] = "Red";
        colors[4] = "Blue";
        colors[5] = "Orange";
        colors[6] = "Silver";
        colors[7] = "Yellow";
        colors[8] = "Brown";
        colors[9] = "Maroon";
       
        manufacturers = new String[10];
        manufacturers[0] = "Mercedes";
        manufacturers[1] = "BMW";
        manufacturers[2] = "Volvo";
        manufacturers[3] = "Audi";
        manufacturers[4] = "Renault";
        manufacturers[5] = "Opel";
        manufacturers[6] = "Volkswagen";
        manufacturers[7] = "Chrysler";
        manufacturers[8] = "Ferrari";
        manufacturers[9] = "Ford";
    }
   
    public TableBean() {
        carsSmall = new ArrayList<Car>();
        populateRandomCars(carsSmall, 9);
    }
   
    private void populateRandomCars(List<Car> list, int size) {
        for (int i = 0; i < size; i++) {
            list.add(new Car(getRandomModel(), getRandomYear(), getRandomManufacturer(), getRandomColor()));
        }
    }
   
    public void removeItem(Car car) {
        carsSmall.remove(car);
    }
   
    public void updateItem(Car car) {
        System.out.println("New value: " + car.getModel());
    }
   
    public List<Car> getCarsSmall() {
        return carsSmall;
    }
   
    private int getRandomYear() {
        return (int) (Math.random() * 50 + 1960);
    }
   
    private String getRandomColor() {
        return colors[(int) (Math.random() * 10)];
    }
   
    private String getRandomManufacturer() {
        return manufacturers[(int) (Math.random() * 10)];
    }
   
    private String getRandomModel() {
        return UUID.randomUUID().toString().substring(0, 8);
    }
}

web.xml

<context-param>
        <param-name>com.sun.faces.expressionFactory</param-name>
        <param-value>com.sun.el.ExpressionFactoryImpl</param-value>
    </context-param>

Note: using E.L 2.2 (el-api-2.2.jar ; el-impl-2.2.jar) in Tomcat 6 lib folder