Saturday, November 21, 2009

Comparing PHP Java and Ruby

Today I tried to do a small research to try and find out what language is best
when it comes to web development and tools that supports it. I tried to compare the three most used languages for web frameworks namely PHP, Java and Ruby.
All the details collected here are from my colleagues and not from a firm source. So if there is
any mistake please feel free to highlight.

The comparison was split between following items.

1/ Speed
2/ Debugging (and profiling)
3/ IDEs and Tools
3/ Testing (Unit, functional, performance)
4/ Logging and Log file maintenance
5/ Security
6/ Application integration (Integrate legacy systems and ERP systems).

Speed component depends on what you really do and the actual framework you
are using. But in general when the number of requests are low to medium PHP > Java > Ruby. When the number of requests are
high Java > Ruby > PHP is the case.

Tools that supports Debugging.
PHP - PHPEd, Expert Debugger
Java - Any IDE, JMeter, JProfiler
Ruby - ruby-debug,ruby-prof(Profiler)


List of popular IDEs for each language.
PHP - PHPEd, PHP Designer, Zend Studio Professional, PHP Expert Editor
Java - Eclips, JIdea, JBuilder
(Note: JIdea is best)
Ruby - Aptana RadRails http://www.radrails.org/, TextMate, Steel IDE (http://www.sapphiresteel.com/). NetBeans, JIdea Ruby plugin, CodeGear's 3rdRail
(Note: NetBeans free and the best so far)

Testing.
PHP - Testilence, izh_test,Phpunit, Spike PHPCoverage,SimpleTest.
Java - Junit, Cactus,Jemmy, jfcUnit, Abbot
Ruby - MiniTest, Test::Unit

The security features of Java is unmatched when compared with PHP or Ruby or any other language. Actually Java was born
with security. Starting from its Strong data typing, Automatic memory management, Bytecode verification, Secure class loading
Java exposed a new dimension to the world of security.

When it comes to logging and application integration also Java leads the other languages for its versatility, available tools and frameworks.

Now the issue is if Java is such strong what is the catch. Why people use PHP for most of the sites. One reason is the cost. You need a dedicated server to host a Java site most of the time. Next you need a skilled staff from development to network administration to handle a heavy wait Java application server.Because of the above reasons PHP would be a better option to run small to moderate sites.

Also check the following comment by
James Gosling the father of the Java programming language
Ruby can't scale as good as Java

Monday, November 16, 2009

Porting our existing J2EE ecommerce application to Liferay.

The main reason for porting the existing portal to Liferay was, to use the
CMS capabilities it provides. On the evaluation on what CMS to use
we found a hand full of Java Portal/CMS systems.
Although the framework of each of them were attractive they lacked good portlets or plugins which can be used out of the box. Liferay on
the other hand has many plugins available already. It has a Forum, Blog, RSS/Atom Module, A fine HTML templating module and a couple of simple frame works to write CRUD applications which were critical for our requirements.

The site we implemented had three full fledged ecommerce applications, landing sites for several affiliate products, promotion pages,
forums, blogs, newsletters, testimonials, press releases and articles. There was a magazine and advertising
campaign application that was meant to be used by the readers of the company magazine. This application
had a poll, a survey, a competition and couple of other options aimed for the campaign.

From the side of implementation we used an agile development approach and our development
team had 11 members. The time span for this project was only 2 months and the site had around 80 pages both
dynamic and static. Although this was a tough deadline we had to accept it as the management already scheduled advertising
campaigns that follows the delivery of the site.

Since the complexity of the user interface designs and for the flexibility we agreed not to use portlets for implementing
the ecommerce modules. The architecture was to use AJAX/JSON to integrate functionality and keep the pages
generating from the Liferay CMS.

Today we got a reward for completing the project on time with a lot of appreciation from our management. Being the
project manager Im so pleased and like to thank the whole team for their dedication and hard work. Cheers Guys.
Also now we are fully convinced that Liferay Portal is a better Java based CMS (or a WCM - Web content Management System) among the
Java CMS family.

If you like to have a look on the site visit this link
>>>Link Removed !<<<

Thursday, November 5, 2009

Use rewriterule with DocumentRoot instead of ProxyPass

When ProxyPass is used on root level with DocumentRoot proxing will dominate and appache will not serve anything from the document directory.

For example if following configuration is used

DocumentRoot /var/www/html/
ProxyPass / ajp://10.231.40.6:8009/
ProxyPassReverse / ajp://10.231.40.6:8009/

The content in /var/www/html/ will not be served by appache.

RewriteRule is the way to solve this.


DocumentRoot /var/www/html/

RewriteEngine on
rewriterule ^/blog - [L]
rewriterule ^/(.*) ajp://10.231.40.6:8009/$1 [P,L]

When the configuration is changed as shown in the above example the content in the folder /var/www/html/blog will be accessible with a URL like http://domain/blog

Wednesday, October 14, 2009

Liferay service deploying exception

I was working with the announcement portlet and wanted to make it a portlet plugin rather than editing it in the liferay ext environment. Initially I only wanted to change the appearance of it. For this while coping the jsp files and other required file to a newly created directories I have added the following jar files too. After
few tries I got it to work.

commons-beanutils.jar
commons-configuration.jar
commons-digester.jar
commons-lang.jar
commons-math.jar
displaytag.jar
easyconf.jar
newsletter-portlet-service.jar
struts.jar
xstream.jar

When I tried to add my own set of tables using the service builder and
deployed the portlet the server started to spit the following error.




Caused by: org.springframework.beans.factory.BeanCreationException: Error creati
ng bean with name 'liferayTransactionManager' defined in ServletContext resource
[/WEB-INF/classes/META-INF/hibernate-spring.xml]: Initialization of bean failed
; nested exception is org.springframework.beans.TypeMismatchException: Failed to
convert property value of type [com.liferay.portal.spring.hibernate.PortletHibe
rnateConfiguration] to required type [org.hibernate.SessionFactory] for property
'sessionFactory'; nested exception is java.lang.IllegalArgumentException: Canno
t convert value of type [com.liferay.portal.spring.hibernate.PortletHibernateCon
figuration] to required type [org.hibernate.SessionFactory] for property 'sessio
nFactory': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getOb
ject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
y.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBe
an(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:164)


10:09:49,297 INFO [STDOUT] 10:09:49,297 ERROR [PortletApplicationContext] org.s
pringframework.beans.factory.parsing.BeanDefinitionParsingException: Configurati
on problem: Class that bean class [com.liferay.portal.spring.annotation.BeanRefe
renceAnnotationBeanPostProcessor] depends on not found
Offending resource: ServletContext resource [/WEB-INF/classes/META-INF/base-spri
ng.xml]
Bean 'beanReferenceAnnotationBeanPostProcessor'; nested exception is java.lang.N
oClassDefFoundError: org/springframework/beans/factory/BeanFactoryAware
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Config
uration problem: Class that bean class [com.liferay.portal.spring.annotation.Bea
nReferenceAnnotationBeanPostProcessor] depends on not found
Offending resource: ServletContext resource [/WEB-INF/classes/META-INF/base-spri
ng.xml]
Bean 'beanReferenceAnnotationBeanPostProcessor'; nested exception is java.lang.N
oClassDefFoundError: org/springframework/beans/factory/BeanFactoryAware
at org.springframework.beans.factory.parsing.FailFastProblemReporter.err
or(FailFastProblemReporter.java:68)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderC
ontext.java:85)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.er
ror(BeanDefinitionParserDelegate.java:288)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.pa
rseBeanDefinitionElement(BeanDefinitionParserDelegate.java:487)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.pa
rseBeanDefinitionElement(BeanDefinitionParserDelegate.java:389)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.pa
rseBeanDefinitionElement(BeanDefinitionParserDelegate.java:358)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe
ader.processBeanDefinition(DefaultBeanDefinitionDocumentReader.java:239)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe
ader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:153)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe
ader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:132)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe
ader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)

And loads of other error !!!!!!!!!!!!!!!!!!!!!!!


After struggling for some time I got to know what was going on. I have added the spring.jar and portal-impl.jar initially for my testing and I didnt remove them from the project and that was the issue. After removing these two files the protlet started to deploy without any problem

================================================================================

Saturday, August 29, 2009

Cookies and Javascript

Handling cookies in Javascript
=================================



function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

function eraseCookie(name) {
createCookie(name,"",-1);
}

function delCookie(name) {
document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT" +
"; path=/";
}

Thursday, August 27, 2009

Regular expressions in javascript and Java

Regular expressions lets you to search a text in a text string or do a search and
replace a text in a text string.



Java Script:

Create the expression
================================================================================

var exp = /expression/;
Or
var exp = new RegExp("expression");

Testing availability of a text.
================================================================================

if(/text/.test("The text string.")) alert("Found text");

OR

if ("The text string".match(/text/)) alert("Match found for text");

Doing a search and replace.
================================================================================

var output = "The text string".replace(/text/g, "replacement");

OR

var re = new RegExp("text", "g");
var output = "The text string".replace(re,"replacement");

Using the /g OR "g" modifier makes sure that all occurrences of "text" are replaced


Splitting a text string by a delimiter
================================================================================

var myArray = "comma, separated, text, string".split(/,/);


Retrieving the part of the string that was matched
================================================================================

var mymatch = /text/.exec("The text string")

if (mymatch == null) {
alert("No match");
} else {
var s = "Match at position " + mymatch .index + ":\n";
for (i = 0; i < s =" s" mystringarr = "comma, separated, text, string" replaced = "change, delimiter, of, text, string" regex = "match this string" regex = "match.*" class ="=" mypattern =" Pattern.compile(" mymatcher =" myPattern.matcher("> The "^" says check the beginning of the text. [A-Z] specify range of
numbers.

Check for any text starting with a digit 1 to 5.
==============================================================================

^[1-5]

See reference [http://www.regular-expressions.info/reference.html] for details.

Tuesday, August 25, 2009

Password protect D-Link wireless router DSL-2640U

Security options to choose from.

Wired Equivalent Privacy (WEP) - Less secure (The key can be recovered from network sniffing)
Wi-Fi Protected Access (WPA and WPA2) - The recommended solution to WEP security problems.
WPA-PSK (Pre-shared key mode) is the personal mode which is designed for home and small office network setups.
WPA supports two encription methods to choose from.
TKIP - Temporal Key Integrity Protocol.
AES - Advanced Encryption Standard which is considered to be fully secured.


Seting up a security key (password)
===================================

Type http://192.168.1.1/ in your browser to open the router admin console.
Go to the wireless security tab and choose the follwing settings for each
option.
Network Authentication: WPA-PSK
WPA Pre-Shared Key (Password): Combination of numbers and letters.
WPA Group Rekey Interval: 0
WPA Encryption: AES
WEP Encryption: Disabled.

Following is a screenshot of the required settings.






Adding the wireless network password to Windows Vista


Setingup the password in Windows Vista can be done throught the "Manage Wireless Networks". Access "Manage Wireless Networks" from Control Panel>Network and Sharing Center>. Right click and select properties of the DLink network. Select the security tab and enter the following.
Security type: WPA-Personal
Encryption type: AES
Network security key: (Enter the previousely setup password)




Now your wireless network is fully protected.

Monday, July 20, 2009

Start a brand new PostgreSQL server

Create a directory to hold the postgres database cluster files. (Eg. c:\pgdata or /usr/local/pgsql/pgdata in linux)

Cluster is a collection of databases that are managed by a single server instance.
Be sure the pgdata directory owned by postgres user and the directory is empty

Type the following command to initialise the cluster.
initdb -D c:\pgdata -U postgres

Start the cluster by invoking the following command.
pg_ctl -D c:\pgdata -l c:\pgdata\logfile start

To stop the database cluster use the following command.
pg_ctl -D c:\pgdata stop

Other Info

Create a user called "user1"
createuser -U postgres -P user1 (Prompted for a password)

Create a database called "database1"
createdb -U user1 -E UTF-8 database1

Create Language
createlang -U postgres -d database1 plpgsql

Exporting data from a database.
pg_dump -U user1 database1 > dumpfile.dmp

Importing data to the database
psql -U user1 database1 < dumpfile.dmp

Check the status and data file location:
ps aux | grep post

Default data file location: /var/lib/postgresql/

Change default password ALTER USER postgres WITH PASSWORD ‘password’;
change the Linux user password of postgres to the same.

(Note: "postgres" is the user created when installing Postgre. If you create a user account named postgres in the OS and installed Postgre into this account "postgres" can be ommited. This is valid for both Windows OS and Linux. )

Wednesday, July 8, 2009

Starting oracle admin web console

Go to the ORACLE_HOME/bin directory
Eg. /u01/app/oracle/product/11.1.0/db_1/bin

** To check the status enter ./emctl status dbconsole
** To start the enterprise db console enter ./emctl start dbconsole
** To stop the admin console enter ./emctl stop dbconsole

Wednesday, June 24, 2009

Mixing transactions manual and container managed with JTA

How-to Mix manual transactions and container managed transactions


Container managed transactions use JTA for transaction management. If we need to mix the manual transactions and container managed transactions we have to use the JTA for the manual transactions as well.


You can use the following two classes for handling manual transactions with JTA.





Listing : Class CustomTransactionCallbackWithoutResult





public abstract class CustomTransactionCallbackWithoutResult {

   public abstract void doInTransactionWithoutResult();

}




Listing : Class CustomTransactionTemplate



import javax.transaction.UserTransaction;

import javax.transaction.SystemException;



public class CustomTransactionTemplate {

 


   
UserTransaction ut;
 


    public CustomTransactionTemplate(UserTransaction ut) {

        this.ut = ut;

   
}
    public void execute(CustomTransactionCallbackWithoutResult transactionCallbackWithoutResult) {
      

            try {
        

              try {

                ut.begin();

                transactionCallbackWithoutResult.doInTransactionWithoutResult();

                ut.commit();
            } catch (Throwable ex) {

                try {

                  ut.rollback();

                } catch (SystemException syex) {

                  throw new Exception( "Rollback failed: " + syex.getMessage());

                }

                 throw new Exception( "Transaction failed: " + ex.getMessage());

           }

        } catch (Throwable e) {

            throw new RuntimeException(e);

        }
    }





Using the above two classes

 


InitialContext ic = new InitialContext();

UserTransaction ut = (UserTransaction) c.lookup("java:comp/UserTransaction");

final DataSource ds = (DataSource) c.lookup("java:/sampleDS");

 

CustomTransactionTemplate txTemplate = new CustomTransactionTemplate(ut);

txTemplate.execute(new CustomTransactionCallbackWithoutResult() {

   public void doInTransactionWithoutResult() {

     //We are in the transaction
                        // Use ds and update a table

     // call a session bean which in turn call Entity bean

    // and cause Container  managed transactions                     

     //

     }

 });



 

When mixing container managed transactions and manual transactions if  you try to use the setAutoCommit() or Hibernate TransactionTemplate the following errors will be fired. To avoid the error the best bet is to use the JTA transactions in every place.

 


java.sql.SQLException: Connection handle has been closed and is unusable at org.jboss.resource.adapter.jdbc.WrappedConnection.checkStatus(WrappedConnection.java:537) at org.jboss.resource.adapter.jdbc.WrappedConnection.checkTransaction(WrappedConnection.java:524) at org.jboss.resource.adapter.jdbc.WrappedConnection.prepareStatement(WrappedConnection.java:184) at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:505) at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:423) at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:139) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1547) at org.hibernate.loader.Loader.doQuery(Loader.java:673) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236) at org.hibernate.loader.Loader.doList(Loader.java:2220)     


 

Tuesday, June 9, 2009

Oracle XE change http port and enable remote access to web console

To change the http port use the following command in sqlplus

call dbms_xdb.cfg_update( updateXML(dbms_xdb.cfg_get(), '/xdbconfig/sysconfig/protocolconfig/httpconfig/http-port/text()', 8090))

or

EXEC DBMS_XDB.SETHTTPPORT(8090);

To enable remote access use the following command in sqlplus

EXEC DBMS_XDB.SETLISTENERLOCALACCESS(FALSE);

Monday, May 18, 2009

Well done Sri Lanka

Congratulations Mr. President Mahinda Rajapaksha and Sri Lankan forces for freeing the nation from terror by defeating LTTE, which is the most ruthless terrorist outfit in the world. The good news was informed officially on yesterday 18th May 2009 evening.

Wednesday, May 6, 2009

Convert url from non-www version to www version or vise versa


Redirect with Apache
Redirect www to non-www:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,L]


An alternative which includes domain name is as follow:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

The following is the version to redirect non-www to www:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

WWW Redirect with nginx

Redirect to non-www, add the following code:

server {
listen 80;
server_name www.example.com;
rewrite ^/(.*) http://example.com/$1 permanent;
}

The word permanent is key. It turns the redirect into 301 redirection. After this block, you may configure the domain without www.

Redirecting non-www to www:

server {
listen 80;
server_name example.com;
rewrite ^/(.*) http://www.example.com/$1 permanent;
}

WWW Redirect with lighttpd

Redirecting www to non-www can be done with the following code:

$HTTP["host"] =~ "^example]\.com$" {
url.redirect = ( "^/(.*)" => "http://www.example.com/$1" )
}

Redirecting non-www to www:

$HTTP["host"] =~ "^example]\.com$" {
url.redirect = ( "^/(.*)" => "http://www.example.com/$1" )
}

Thursday, March 26, 2009

Java compile error with Ant or Maven

I hope you may have got the following error on some time of your programing career. When you compile some java files using your IDE, Ant, Maven javac etc this error may pop.

class file has wrong version 49.0, should be 48.0

The reason for this is one or more classes or java libraries in your classpath are not compatible with the current version of the java compiler. To fix this need download the latest JDK and set the JAVA_HOME to the new jdk.

Or else if you have the source of the library files it self you can rebuild the libraries using the current version of the JDK.

===============

Wednesday, March 25, 2009

Unable to retrieve search results column is not indexed

When working in site studio and oracle ucm content server i got the following error when trying to select the assets drop down to insert a css or a image etc.

Unable to retrieve search results. Unable to retrieve search results. Unable to create result set for query 'SELECT IdcColl1.dID, dDocName, dDocTitle, dDocType, dRevisionID, dSecurityGroup, dDocAuthor, dDocAccount, dRevLabel, dFormat, dOriginalName, dExtension, dWebExtension, dInDate, dOutDate, dCreateDate, dPublishType, dRendition1, dRendition2, VaultFileSize, WebFileSize, URL, dFullTextFormat, dFullTextCharset, DocMeta.*FROM IdcColl1, DocMetaWHERE IdcColl1.dID=DocMeta.dID AND (((CONTAINS(dDocFullText,'test') > 0 ))) ORDER BY dInDate Desc'. ORA-20000: Oracle Text error:DRG-10599: column is not indexed

To fix this error need to Configure Site Studio Metadata and Zone Fields. To do this

1. Open the content server Administration page.

2. Click Zone Fields Configuration.

3. Move Web Sites and Exclude From Lists into Zone Text Fields column.

Then press update.

This should basically fix the issue above. Refer to the Site studio installation guide for more information.


Note:

According to the installation guide full text indexing is required by the ucm to run correctly even though you do not need full text indexing facility.

To do this execute the Database-Script [ucm-install-target]/database/oracle/admin/stellentrole.sql

Use the following command to enable the role to the user.
grant stellent_role to ;

Script for creating a user for content server is in [ucm-install-target]/database/oracle/admin/contentserveruser.sql. This script assigns required rights and roles to the content server user.

Enabling full text search

In addition to the above settings the following should be done to enable full text search.

If the database used is 10gR2 should run the following script
[ucm-install-target]/database/oracle/admin/batchsnippet.sql

Edit [ucm-install-target]/config/config.cfg and add the following:
SearchIndexerEngineName=DATABASE.FULLTEXT

Restart the content server.

Run the repository manager tool comes with the content server and rebuild the indexes.

This will basically enable full text search in content server. Please refer to the installation guild in the following location for further information.

http://download-west.oracle.com/docs/cd/E10316_01/cs/cs_doc_10/documentation/integrator/install_cserver_win_10en.pdf.

=====================

Sunday, March 8, 2009

Error while getting remote MBeanServer

When creating a connection from the JDeveloper to the Oracle Application server you might get an error similar to the following.

Error while getting remote MBeanServer for url: ormi://176395.176395-web1.server.domain:12401/default

To fix this add the fully qualified application server name (which is 176395.176395-web1.server.domain in above case) to the hosts file in the client machine that runs JDeveloper which used to access the server.

The hosts file is located in the following locations on the client machine.

Linux - /etc/sysconfig/networking/profiles/default/hosts
Windows - C:\WINDOWS\system32\drivers\etc\hosts

The hosts file should look similar to the following after adding the entry.

127.0.0.1 localhost
83.138.171.4 176395.176395-web1.server.domain

Just adding the entry and saving the hosts file is enough and no need to restart anything for this to work.
======================================================

Friday, March 6, 2009

Oracle pfile and spfile

Oracle pfile is the parameter file which is used for initilazing the oracle database. This is usualy init.ora in the ${ORACLE_HOME}/dbs/ which is /u01/app/oracle/product/11.1.0/db_1/dbs in my case.

spfile is the binary counterpart of pfile which was introduced starting from Oracle 9i. spfile is used to store dynamic changes done via ALTER SYSTEM or ALTER SESSION statements.

On startup database first looks the spfile and if not found checks for pfile.

Creating spfile
spfile can be created as privilaged user by following command
SQL> create spfile from pfile;
The file is created in ${ORACLE_HOME}/dbs/ and named spfile{ORACLE_SID}.ora. The command will over write if a old file exist in the path and if its in use following error will throw.
ORA-32002: cannot create SPFILE already being used by the instance

Starting up with different spfile.
On startup the system checks the parameter file in following order.
spfile${ORACLE_SID}.ora file in ${ORACLE_HOME}/dbs/
spfile.ora in ${ORACLE_HOME}/dbs/
init${ORACLESID}.ora in ${ORACLE_HOME}/dbs/

To specify the parameter file on startup use the following command
SQL> startup pfile='/db2/ORACLE/SID/spfile/init.ora';

SCOPE and ALTER SYSTEM statements

Changes done by ALTER SYSTEM and ALTER SESSION statements are normally persistent in spfile. However this behaviour can be changed.

Specifying SCOPE=MEMORY and the changes are valid until the next restart and the spfile will not affected. To do this use the following commands.

SQL> SHOW PARAMETER timed_statistics
SQL> ALTER SYSTEM SET timed_statistics=TRUE scope=memory;
SQL> SHOW PARAMETER timed_statistics

Specifying SCOPE=SPFILE and the changes will not affect the current running instance but will be visible after a database restart. For this use the following command.

SQL> ALTER SYSTEM SET timed_statistics=TRUE scope=spfile;

Specifying SCOPE=BOTH will affect both the running instance and the spfile hence will be persistent. Following is the command to do this.

SQL> ALTER SYSTEM SET timed_statistics=TRUE scope=both;

To check this parameter in both contexts memory and spfile use the following commands

SQL> SELECT name,value FROM v$parameter WHERE name='timed_statistics';
SQL> SELECT name,value FROM v$spparameter WHERE name='timed_statistics';

Check what paramter file (spfile or pfile) used in the database.

SQL> SELECT name,value FROM v$parameter WHERE name = 'spfile';

Export the spfile to pfile

SQL> create pfile from spfile;

OR can specify the file names as

SQL> create pfile='/db2/ORACLE/SID/spfile/init.ora' from spfile='/db2/ORACLE/SID/spfile/spfileorcl.ora'

===================

Thursday, March 5, 2009

Oracle instance currently running

To retrieve the Oracle instance name, execute the following SQL statement:
select sys_context('USERENV','DB_NAME') as Instancefrom dual;

Following commands can be used to check the TNS Listener status

tnsping oracl (Where oracl is the instance name under concern

lsnrctl services

lsnrctl status

Wednesday, March 4, 2009

Apache library Permission denied in Linux when configuring oracle UCM and SELinux

I encountered the following issue while trying to configure Apache web server in Linux (Fedora) to run the oracle UCM content management system.

<IfModule !IdcApacheAuth>
LoadModule IdcApacheAuth "/oracle/ucm/server/shared/os/linux/lib/IdcApache22Auth.so"
</IfModule>

IdcUserDB "idc" "/oracle/ucm/server/data/users/userdb.txt" Alias "/idc" "/oracle/ucm/server/weblayout/"

<Location "/idc">
IdcSecurity "idc"
Allow from allDirectoryIndex portal.htm
</Location>


Following Permission denied exception thrown when i restarted the server after adding the above configuration.

httpd: Syntax error on line 1001 of /etc/httpd/conf/httpd.conf: Cannot load /oracle/ucm/server/shared/os/linux/lib/IdcApache22Auth.so into server: /oracle/ucm/server/shared/os/linux/lib/IdcApache22Auth.so: cannot open shared object file: Permission denied


This is really not an issue. Actually an advanced security feature in linux called SELinux is blocking the library file from loading. SELinux (Security Enhanced Linux) is a proxy controlling the request to all aspects of the system including filesystem, processes, users, network connections, etc.

Method 1 - Disable SELinux

One way of fixing this issue is turning the mode of SELinux to off or warning only.
In command shell type
shell system-config-selinux
to bring the graphical administraion window of SELinux and set the following parameters

System default enforcing mode - Disabled or Permisive
current enforcing mode - Permisive

Also you can manualy configure it by editing configuration file
/etc/selinux/config
set the variable SELINUX=disabled and reboot the system.

Alternatively can use the following commands to temparoryly disable SELinux until next reboot.
setenforce 1
echo 0 > /selinux/enforce

Specify in /etc/grub.conf on the "kernel" command line: enforcing=0 which will also
work on reboot and permenent.


Method 2 - Configure the SELinux security paramters

Login as root and copy the file IdcApache22Auth.so to /usr/lib which has permissions for running the file. Should use the copy command instead of move command to set the directory permissions in file.

cp /oracle/ucm/server/shared/os/linux/lib/IdcApache22Auth.so /usr/lib

Then change the httpd.conf file parameter from
/oracle/ucm/server/shared/os/linux/lib/IdcApache22Auth.so
to
/usr/lib/IdcApache22Auth.so

Check current security setting using following commands
ls -Z /oracle will show the current settings
ps -eZ to see security contexts of processes

Make the /oracle directory accessible by invoking the following command

chcon -R -h -t httpd_sys_content_t /oracle

-R: Recursive. Files and directories in current directory and all subdirectories.
-h: Affect symbolic links.
-t: Specify type of security context.

Make the httpd connect to ucm by setting the following httpd option. Execute the following command

setsebool -P httpd_can_network_connect=1

retart httpd by issueing follwing command as root

service httpd restart

Now the above issue should be fixed.

=============================

Monday, March 2, 2009

Terrorist Attack on Sri Lankan Cricket Team

Me and my friend Nivanka thought of turning the site black to condemn the brutal terrorist attack on our Cricket team as they approached the Gaddaphi Cricket Stadium in Pakistan to continue the third day of the Test match.

BBC-Link
http://news.bbc.co.uk/2/hi/south_asia/7920260.stm

CCN-Link
http://edition.cnn.com/2009/WORLD/asiapcf/03/02/pakistan.srilanka.attack/index.html?eref=edition

As Sri Lankans we have suffered a lot because of the terrorist activities carried by the LTTE (the local terrorist group) for almost 30 years. Because of the never ending effort of our brave solders now the LTTE is conformed to a very little area of 50 square kilometers and they are continuing to pounding the asses of them.

Terrorism is a virus demolishing the beauty of the world. So the whole world should put hands together on the effort of eliminating it altogether.

Once our President Mahinda Rajapaksha said we cannot categorise Terrorism to Good Terrorists and Bad Terrorists. The above incidence is another one which proves this idea.

Hope all the leaders in the whole world unite in overcoming this issue very soon.


=================================================================


I have rolled back the blackout effect of my blog today (05th March 2009). Hope peace will prevail on earth and incidences like this will not happen in future in anywhere of the world.

=================================================================

Sunday, March 1, 2009

Increase sessions and processes of Oracle DB

If you use the oracle XE starter database and try to setup a bulky application like the oracle ucm content management system you will get the following error.

Unable to initialize the application. Error: Unable to initialize the system provider 'SystemDatabase'. Unable to create database connection for the database 'SystemDatabase' with connection string 'jdbc:oracle:thin:@localhost:1521:XE'. Please make sure that the connection string, user and password are correct. Listener refused the connection with the following error:ORA-12519, TNS:no appropriate service handler found

The default parameters of the starter database are not set to handle havy loads. To increase the parameters use the following commands.

Log into sqlplus by

sqlplus sys/password as sysdba (Replace password with administrator password).

Database Sessions

Increase the number of sessions to allow more users to access the database.
SQL> show parameters sessions
SQL> alter system set sessions=250 scope=spfile;

Database Processes

Increase the number of database processes which will allow more connections to the database.

SQL> show parameters processes
SQL> alter system set processes=200 scope=spfile;

Finally restart the database for the parameters to take effect.

This should fix the above error.

Wednesday, February 25, 2009

Oracle ucm content management installation

Use the link http://www.oracle.com/technology/products/content-management/ucm/index.html to get the installation and the documentations.


First install the Apache web server. http://httpd.apache.org/

Create a user in the database with username and password ucm/ucm.

CREATE USER ucm IDENTIFIED BY ucm;
GRANT CONNECT, RESOURCE TO ucm;

Go to the directory which contains the setup executable.
Linux - /home/ucm/V13684-01/UCM/ContentServer/linux
Windows - G:\ContentServer_Windows_10gR3_20080807\UCM\ContentServer\win32

Run ./setup.sh in linux or Installer.exe in windows.

Summery of values selected.

Review install settings. . .
Content Server Core Folder: /oracle/ucm/server
Java virtual machine: Sun Java 1.5.0_11 JDK
Content Server Native Vault Folder: /oracle/ucm/server/vault/
Content Server Weblayout Folder: /oracle/ucm/server/weblayout/
Proxy authentication through another server: no
Install admin server: yes
Web Browser Path: /usr/bin/firefox
Content Server System locale: English-US
Content Server Port: 4444
Admin Server Port: 4440
Incoming connection address filter: 127.0.0.1
Web Server Relative Root: /idc/
Company Mail Server: mailserver.somedomain
Administrator E-Mail Address: user@server.somedomain
Web Server HTTP Address: localhost.localdomain
Server Instance Name: idc
Server Instance Label: idc
Server Description: Content Server idc
Web Server: Apache
Content Server Database: Oracle
Manually configure JDBC settings for this database: false
Oracle Server Hostname: localhost
Oracle Listener Port Number: 1521
Oracle User: ucm
Oracle Password: hOYGE/WjtaG1G/Fgm3xJXa2194WX5GMrSeGcNyfW4OM=
Oracle Instance Name: orcl
Configure the JVM to find the JDBC driver in a specific jar file: false
Attempt to create database tables: yes

Select Proceed to continue

Add the configuration parameters from the installed directory server\data\users\apache22\apache.conf to the apache configuration file httpd.conf.

Change the Allow from any to
Allow from all

Also add the following parameter if it is not already there.
DirectoryIndex portal.htm

The parameters should look something like below.

<ifmodule>
LoadModule IdcApacheAuth "G:/product/10.1.3.1/ucm/server/shared/os/win32/lib/IdcApache22Auth.dll"
</ifmodule>
IdcUserDB "idc" "G:/product/10.1.3.1/ucm/server/data/users/userdb.txt"
Alias "/idc" "G:/product/10.1.3.1/ucm/server/weblayout/"
<location>
IdcSecurity "idc"
Allow from all
DirectoryIndex portal.htm
</location>


Start the content server by executing server\bin\IdcServer.exe
Start the admin server by executing server\admin\bin\IdcAdmin.exe

Restart the Apache server .

Point the browser to http://localhost/idc/

The following message will come if the web server is not configured properly.

Network message format error. Unable to parse browser environment or content item. Unable to parse properties. Name-value pairs are missing an '='.

Check the parameters and try again.

Once successful log in as sysadmin/idc

Sunday, February 22, 2009

Difference in two Dates, Daylight saving issue and fixing

Calculating the number of days between two dates is not straight forward if
you are in a Time Zone which has daylight saving. Most of the programmers miss this
point and waits until it get caught up by the testing team or by the public user.

The worst case is sometimes this issue will continue to stay even without noticing as this happens only when the dates which are chosen are inside a period of daylight saving and may cost a lot at the end of the year.

The simplest way of calculating the number of days between two dates is
get the UTC time difference of the two dates and divide it by number of milliseconds per day. But this is incorrect as this can give false results if daylight saving is active on that particular dates.

Try the following example in Java.

Date d = new Date(2009, 2, 28, 12, 0, 0);
System.out.println(d + " local <=> GMT " + d.toGMTString());

Here we have created a Date object for 28 March 2009 and set the time to 12:00. Assume your time zone is GMT. But if you run this code you will notice the GMT time shows as 11:00. That means if you use getTime() function to get the time it is 1 hour less than what you expect.



There are few methods to fix this in Java.

1/ Add 2 hours to the difference that is 3600000 * 2 milliseconds.

Date d1 = new Date(year, month-1, day, 12, 0, 0);
Date d2 = new Date(year, month-1, day, 12, 0, 0);
int dif = (int)((d1.getTime() - d2.getTime() + 3600000 * 2 ) / 86400000);

Since 3600000 * 2 / 86400000 is a fraction it will be eliminated when casting to int. So this method will work when you are in daylight saving or not. This method can be used in any language Java, C, VB, PHP etc. or even JavaScript.

2/ Remove the offset value from the time component

Date d1 = new Date(year, month-1, day, 12, 0, 0);Date d2 = new Date(year, month-1, day, 12, 0, 0);

int dif = (int)((d.getTime() - d.getTimezoneOffset() * 60000 - (td.getTime() - td.getTimezoneOffset() * 60000) ) / 86400000);

Here the d.getTimezoneOffset() * 60000 is used because the offset is given in minutes. This is not required if you use the Calendar Object instead.

3/ You can pass a Custom TimeZone object to the Calendar object which doesn’t have anything in method bodies.

=============

Wednesday, February 11, 2009

TNS Listener Crashes with error

I got the follwoing error in TNS Listner after installing Oracle application server 10g.

lsnrctl Message 1073 not found; No message file for product=NETWORK, facility=TNS

and

Windows No such file or directory message.

To see this error use Start>Run and type cmd and press enter
then type lsnrctl status and press enter.

The issue is with the ORACLE_HOME envirnment variable which got change after installing the application server.

To fix this change the ORACLE_HOME to C:\oraclexe\app\oracle\product\10.2.0\server in my case. This should be done in My Computer>Properties>Advanced Tab>Envirnoment Variables.

Please check the registry key
ORACLE_HOME
in
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Control\Session Manager\Environment

which should be the same as above.

Friday, January 30, 2009

My Song Album

I have created a blog for some nice songs i came across in the internet.

http://mysongalbum.blogspot.com/

check this out.

Thursday, January 29, 2009

Cool visual effects demonstration

This is a really cool visual effects demonstration


Wednesday, January 21, 2009

Sri Lankan mp3 songs

A nice mp3 collection of Sri Lankan sinhalese songs.

http://srirg.blogspot.com
http://thepiratebay.org/user/SriRG/

Subscribe