Friday, November 16, 2012

Analyse log files in the pseudo-standard NCSA format

Quick awk script to analyse log files in the pseudo-standard NCSA format to show the number of times each page is hit and what HTTP Status Code is returned for each of the pages
awk '{
splitter=index($7,"=")-1;
if (splitter==-1)
  splitter=length($7);
url=substr($7,1,splitter) "\t" $9;
urls[url]++;
}
END {
for (url in urls)
  print url,"\t",urls[url];
}'

Monday, January 9, 2012

Creating a self-signed certificate using Oracle orapki

In our development environment, when configuring HTTPS for the Oracle XML DB Protocol Server I had to generate a self-signed certificate. All the examples I had seen relied on the owm utility which is only useful in Windows or a X11 environment. To generate a self-signed certificate from the command line execute the following commands:

# Create a new wallet in $ORACLE_BASE/oradata/DEV/wallets/
orapki wallet create -wallet $ORACLE_BASE/oradata/DEV/wallets/ -pwd oracle01 -auto_login

# Add the self-signed certificate to the new wallet
orapki wallet add -wallet $ORACLE_BASE/oradata/DEV/wallets/ -dn "CN=,OU=,O=My Organsisation,L=London,ST=Greater London,C=GB" \
-keysize 1024 -self_signed -validity -pwd oracle01

Friday, October 14, 2011

Adding Software Oracle Linux 5

I downloaded the one of the Oracle Developer Days VM and was trying to install subversion via the Add/Remove Software dialog (which is basically a GUI for yum). It turns out the VM you download points to Oracles internal yum servers. To fix this follow these steps (as root, the default password is oracle):
# cd /etc/yum.repos.d
# mv ULN-Base.repo to ULN-Base.repo.old
# wget http://public-yum.oracle.com/public-yum-el5.repo

Open the public-yum-el5.repo file in a text-editor and change the enabled flag for the first repository to enabled=1

Thursday, August 4, 2011

Foreign Keys with missing Indexes

The following script will show any Foreign Keys that do not have a corresponding Index:

select fk.owner, fk.table_name, fk.constraint_name, fkc.column_name
from all_constraints fk
, all_cons_columns fkc
where fk.owner = :owner
and fk.constraint_type = 'R'
and not exists ( select null
from all_indexes ind
where ind.index_name = fk.constraint_name
and ind.owner = fk.owner )
and fkc.owner = fk.owner
and fkc.table_name = fk.table_name
and fkc.constraint_name = fk.constraint_name
and not exists ( select null
from all_constraints pk
, all_cons_columns pkc
where pk.constraint_type = 'P'
and pk.owner = fk.owner
and pk.table_name = fk.table_name
and pkc.owner = pk.owner
and pkc.table_name = pk.table_name
and pkc.constraint_name = pk.constraint_name
and fkc.column_name = pkc.column_name )
order by owner, table_name, constraint_name;

Thursday, June 16, 2011

CTAS (Create Table As Select)and NOT NULL Constraints

Stumbled across YAOF (Yet Another Oracle Feature) today; When performing a CTAS (Create Table As Select) NOT NULL Constraints are usually created, for example:
CREATE TABLE ctas_test
( id NUMBER NOT NULL
, name VARCHAR2(30) NULL );

CREATE TABLE ctas_test_copy AS
SELECT * FROM ctas_test;

SELECT table_name, column_name, nullable
FROM all_tab_columns
WHERE table_name LIKE 'CTAS_TEST%'
ORDER BY table_name, column_name;

As you can see the Not Null Constraints have been successfully replicated to the CTAS_TEST_COPY table. However if I now execute:

CREATE TABLE ctas_test_minus AS
SELECT * FROM ctas_test
MINUS
SELECT * FROM ctas_test;

SELECT table_name, column_name, nullable
FROM all_tab_columns
WHERE table_name LIKE 'CTAS_TEST%'
ORDER BY table_name, column_name;

The Not Null Constraints are missing from the CTAS_TEST_MINUS table.

Thursday, September 30, 2010

Bulk Data Loading with Hibernate

The most efficient way of loading large amounts of data into Hibernate is using a StatelessSession (provided of course you don't want to keep the objects being loaded in the Persistent Context). The StatelessSession essentially works like a plain JDBC connection with the added bonus of being able to use your mapped persistent classes. You should be able to copy/paste the following into your code:

public void bulkCreate(Collection<?> entities) {
// Open a Stateless Session (this doesn't have a persistence context cache and
// doesn't interact with any other second-level or query cache). Everything
// executed with a Stateless session results in an immediate SQL operation.
StatelessSession session = HibernateUtil.getSessionFactory().openStatelessSession();
session.beginTransaction();
Iterator<?> it = entities.iterator();
while (it.hasNext()) {
session.insert(it.next());
}
session.getTransaction().commit();
session.close();
}

Wednesday, September 29, 2010

Confguring Java mail with JBoss AS 5 and gmail

I've been reading the excellent book: JBoss AS 5 Development and the Example in Chapter 4 creates a Mailer EJB, however the book gives no indication on how to configure Java Mail in JBoss, so I thought I'd share.

  1. Navigate to:

  2. $JBOSS_HOME/server/default/deploy

  3. Open the file: mail-service.xml in your favorite text editor
  4. Edit it as follows:


  5. <server>

    <mbean code="org.jboss.mail.MailService" name="jboss:service=Mail">
    <attribute name="JNDIName">java:/Mail</attribute>
    <attribute name="User">${username}@gmail.com</attribute>
    <attribute name="Password">${password}</attribute>
    <attribute name="Configuration">
    <!-- A test configuration -->
    <configuration>
    <!-- Change to your mail server prototocol -->
    <property name="mail.store.protocol" value="pop3" />
    <property name="mail.transport.protocol" value="smtp" />

    <!-- Change to the user who will receive mail -->
    <property name="mail.user" value="${username}@gmail.com" />

    <!-- Change to the mail server -->
    <property name="mail.pop3.host" value="pop.gmail.com" />

    <!-- Change to the SMTP gateway server -->
    <property name="mail.smtp.host" value="smtp.gmail.com" />
    <property name="mail.smtp.auth" value="true" />
    <property name="mail.smtp.user" value="${username}@gmail.com" />
    <property name="mail.smtp.password" value="${password}" />
    <property name="mail.smtp.ssl.enable" value="true" />
    <property name="mail.smtp.starttls.enable" value="true" />
    <property name="mail.smtp.socketFactory.class"
    value="javax.net.ssl.SSLSocketFactory" />

    <!-- The mail server port -->
    <property name="mail.smtp.port" value="465" />

    <!-- Change the default address mail will be from -->
    <property name="mail.from" value="${username}@gmail.com" />

    <!-- Enable debugging output from the javamail classes -->
    <property name="mail.debug" value="false" />
    </configuration>
    </attribute>
    <depends>jboss:service=Naming</depends>
    </mbean>
    </server>

NOTE: If you are using Google Apps, simply change the gmail.com extension to your-domain.com.

Friday, June 4, 2010

Testing for a number in the ksh

Quick script for testing for a number in the ksh
#!/bin/ksh

if [[ $1 = ?([+-])+([0-9]) ]]; then
echo "true";
else
echo "false";
fi

Wednesday, May 19, 2010

Sending a mail with an attachment

I always end up googling this; so thought I'd add it to my blog - leaving me only one place to look!

To mail a single attachment (with no message):

uuencode filename.txt.gz filename.txt.gz | mailx -s subject email_address

To mail a single attachment with a message:

(cat message.txt; uuencode filename.txt.gz filename.txt.gz) | mailx -s subject email_address

To mail multiple attachments:

(cat message.txt; uuencode filename01.txt.gz filename02.txt.gz && uuencode filename02.txt.gz filename02.txt.gz) | mailx -s subject email_address

Friday, September 25, 2009

Hacking the Trac Database

Unfortunately my Trac Server at work has been down for a number of days and I've had to manually log tickets in an Excel spreadsheet. The network team have finally fixed the issue and I've just finished importing the tickets using the excellent csv2trac.py Python program.

Unfortunately I need to adjust some of the dates which can be done easily using sqlite. Essentially log on the the trac database using the following command:
sqlite3 /path/to/trac/project/db

All dates and times in sqlite are stored as the number of seconds since 01-Jan-1970, therefore to subtract 5-days from the creation date you would run:
UPDATE ticket
SET time = time - (5*24*60*60)
WHERE id = n

Wednesday, August 26, 2009

Configuring Hibernate 3 with c3p0

Thought I'd share a little tip that doesn't (currently) appear in the documentation for configuring c3p0 connection pooling with Hibernate 3.

Apart from setting the properties below (which are documented):
<!-- configuration pool via c3p0-->
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">100</property> <!-- seconds -->
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.timeout">100</property> <!-- seconds -->

You must also set the following (un-documented) property:
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>

If you do not set the provider_class property hibernate will continue to us the built-in connection pool!

Tuesday, June 16, 2009

Custom String Values for an Enum in Java

The default String value that Java returns for an enum is the actual name of the enum constant in use. For example given the following enum:

public enum DayOfWeek {

MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

}
This simple program:
public class DayOfWeekTest {

public static void main(String[] args) {
DayOfWeek dow = DayOfWeek.MONDAY;
System.out.println(dow.toString());
}
}
Will return:
$ java DayOfWeekTest
MONDAY
But in the program above what I really want is an abbreviated version of the week day in Title Case; For example Mon. Now I could override the toString method of the enum class as follows:
public enum DayOfWeek {

MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

public String toString() {
String dayOfWeek = name().toString();
dayOfWeek = dayOfWeek.charAt(0) + dayOfWeek.substring(1,3).toLowerCase();
return dayOfWeek;
}
}
Which does meet my needs, but it’s not the most obvious or readable piece of code. What Java allows you to do is provide a constructor for the enumeration as follows:
public enum DayOfWeek {

MONDAY("Mon"), TUESDAY("Tue"), WEDNESDAY("Wed"), THURSDAY("Thu"), FRIDAY("Fri"), SATURDAY("Sat"), SUNDAY("Sun");

private String dayOfWeek;

private DayOfWeek(String dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}

public String toString() {
return this.dayOfWeek;
}
}
Which I think we can all agree is a far simpler piece of code.

Now to make this enum really useful we should provide a method to convert a String back to an enum. If we simply used the supplied valueOf method in the DayOfWeekTest as follows:
public class DayOfWeekTest {

public static void main(String[] args) {
DayOfWeek mon = DayOfWeek.MONDAY;
System.out.println(mon.toString());
DayOfWeek tue = DayOfWeek.valueOf("Tue");
System.out.println(tue.toString());
}
}
A java.lang.IllegalArgumentException: No enum const class DayOfWeek.Tue is thrown as the valueOf method expects the full name of the enum constant; For example TUESDAY. A new method is needed, therefore out final enum becomes:
public enum DayOfWeek {

MONDAY("Mon"), TUESDAY("Tue"), WEDNESDAY("Wed"), THURSDAY("Thu"), FRIDAY("Fri"), SATURDAY("Sat"), SUNDAY("Sun");

private String dayOfWeek;

private DayOfWeek(String dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}

public String toString() {
return this.dayOfWeek;
}

public static DayOfWeek getValue(String dayOfWeek) {
for (DayOfWeek dow : DayOfWeek.values()) {
// Use equalsIgnoreCase to make the getValue method a little more robust
if (dow.toString().equalsIgnoreCase(dayOfWeek)) {
return dow;
}
}
return null;
}
}

We then change the valueOf method in the DayOfWeekTest to the getValue method as follows:
public class DayOfWeekTest {

public static void main(String[] args) {
DayOfWeek mon = DayOfWeek.MONDAY;
System.out.println(mon.toString());
DayOfWeek tue = DayOfWeek.getValue("Tue");
System.out.println(tue.toString());
}
}
Run the program and Voila!
$ java DayOfWeekTest
Mon
Tue

Wednesday, June 10, 2009

Mimicing "break" in a PL/SQL FOR Loop

It seems a major omission in the Oracle PL/SQL Programming language that the BREAK keyword cannot be used in FOR loops (or WHILE loops) to skip to the next iteration.

Here is a (trivial) example of how you can implement "break" functionality using exceptions:
DECLARE
e_skip_row EXCEPTION;
l_total PLS_INTEGER := 0;
BEGIN
--
dbms_output.enable(10000);
--
FOR l_index IN 1..100 LOOP
BEGIN
--
-- If the row is even then skip
IF MOD(l_index,2) = 0 THEN
RAISE e_skip_row;
END IF;
--
l_total := l_total + l_index;
--
EXCEPTION
WHEN e_skip_row THEN NULL;
END;
END LOOP;
--
dbms_output.put_line('Total is: '||l_total);
--
END;

Monday, February 16, 2009

Connecting to MySQL from BI Publisher

Since BI Publisher just uses a JDBC connection you can of course configure it connect to a MySQL database! I'm using v5.1 of the MySQL Connector/J and BI Publisher is running on Apache 5.5. Here's the instructions:

1. Download the latest MySQL JDBC driver, which can be found here
2. Copy the mysql-connector-java-5.1.7-bin.jar JAR file to $CATALINA_HOME/shared/lib directory
3. Restart you application server (Tomcat in this case)
4. Connect to BI Publisher and click on the Admin tab and then click on the JDBC Connection hyperlink
5. Select the Add Data Source button
6. The connection String should be as follows:
jdbc:mysql://<server>:<port>/<database name>
7. The database driver class should be:
com.mysql.jdbc.Driver
8. Enter the other required information such as username, password and then click on Test Connection.

Thursday, February 12, 2009

Join two lines in sed

I was trying to load a CSV file into an Oracle database using SQL*Loader today and came across an issue where some of the fields contained CR within the data. Luckily each field is enclosed with double quotes ". Knowing this I was able to run the folling sed command which finds any lines that do not end with a double quote and joins them to the next line.

sed -e :a -e '/[^\"]$/N; s/[^\"]\n//; ta' _
old_filename > new_filename

Just thought I'd share - someone might find it useful

Friday, February 6, 2009

BI Publisher API jar files

If you want to use BI Publisher Java API then you do not need to install BI Publisher server, you only need to include the following JAR files within you application:

xdocore.jar - the core BIP/XMLP library
xdoparser.jar - this is the scalable XML parser and XSLT 2.0 engine
xmlparserv2.jar (10.1.3.4) or xmlparserv2-904.jar (< 10.1.3.4) - the main XML parser/XSLT engine
aolj.jar - this is an Oracle EBS library, we need it whether you're developing in EBS or not
i18nAPI_v3.jar - this is the i18n library used for localization functions
collections.jar - you only need this if you are working with the delivery APIs or bursting engine.

Optional JARs for Charting Support
======================
bipres.jar - charting library
bicmn.jar - charting library
jewt.jar - charting support library
share.jar - charting support library

These JARs can all be found in the WEB-INF/lib directory or the xmlpserver.war (which is located in manual/generic from the installation zip archive).

Tuesday, December 2, 2008

Dates and Report Parameters

When configuring a Date Parameter in BI Publisher the Date Format String has to conform to the Java SimpleDateFormat format mask. Some commonly used examples are:


Format MaskOutput
dd-MMM-yyyy01-Jan-2008
dd/MM/yyyy HH:mm:ss01/01/2008 13:25:00
hh:mm a01:25 PM
h:mm a1:25 PM
EEE dd-MM-yyTue 01-01-08
EEEE dd-MM-yyTuesday 01-01-08

Default values for Dates
This can either be:
• A fixed date and must match the format mask specified in Date Format String
• One of the following functions:


Function NameDescription
SYSDATE()Today’s Date
FIRST_DAY_OF_MONTH()First day of the current Month
LAST_DAY_OF_MONTH()Last day of the current Month
FIRST_DAY_OF_YEAR()First day of the current Year
LAST_DAY_OF_YEAR()Last day of the current Year

When using the functions above the they need to be surrounded by a curly brace followed by a dollar sign i.e. {$FIRST_DAY_OF_MONTH()$}
Simple addition and subtraction is also supported with these functions, for example:
{$SYSDATE()+1$} would specify tomorrows date as the default parameter.

Thursday, November 13, 2008

Rendering Error: Unexpected element: :report

Ever seen the error "Unexpected element: :report" when trying to render a report in BI Publisher? This is due a a Bug/Feature where the "xmlns" attribute is not automatically inserted into the element in the xdo file for your report. To resolve the issue is quite simple.

1. Open the xdo file for you report in a text editor
2. Insert the following attribute into the element

xmlns="http://xmlns.oracle.com/oxp/xmlp"


The element should then look something like this:

<report version="1.1" xmlns="http://xmlns.oracle.com/oxp/xmlp" defaultDataSourceRef="dev">
...
</report>

Monday, November 10, 2008

Extract a line from a file

There are many times I need to extract a single line (or possibly group of lines) from a file (Usually when things have gone wrong).

The easiest way to do this is as follows:

awk 'NR==lineNumber{print;exit;} filename

Replacing:

  lineNumber - with the line you wish display

  filename - with the name of your file





I have also seen the following suggested:

sed 'lineNumberq;d' filename

Replacing:

  lineNumber - with the line you wish display

  filename - with the name of your file


After performance testing on a large file (~10,000,000+ lines) the awk command was found to be faster.

ls: Arg list too long

Ever seen the error "arg list too long" when issuing an ls with a wildcard? The simple way round this is as follows:


find . -name "regexp" -exec ls -l '{}' +

Where:

regexp is the regular expression you are searching for