Tuesday, September 22, 2009

Bash Scripting

I had some bash scripts to write a little while ago and I thought I'd share them here.

Let's start with a simple task. Say we have a load of files in a directory, e.g. null121231.xml, null3049432.xml etc. and we want to remove null from the start of the files' names:

for f in null*; do mv "$f" "${f#null}"; done

Moving onto a little more complex. I wanted to write a script that would backup these files to another machine. I felt it was more logical to trigger this script from the remote machine so I did it this way:

Remote machine: telex
Local machine (where backup is being stored): hossbox

#!/bin/bash
# Off site backup script for live database
#
#
# DATE: 27/08/2009

#################################
# Assign Date variables     #
#################################
startTime=`date`
LOGFILE=/home/java/blog_backup_jobs.txt

echo $startTime ": Starting blog backup" >> $LOGFILE

# Ping interval in seconds
PINGINTERVAL=600
numErrors=0
HOST=telex

#### functions ####
function pinghost()
{
    ping -c 1 $1 &> /dev/null
    if [ $? = 0 ]; then
        return 0
    else
        return 111
    fi
}

function notifyAdmin()
{
    # email subject
    SUBJECT="Blog backup failed, mecca failed to respond for 1 hour"
    # Email to?
    EMAIL="patrick@localhost"
    # Email text/message
    EMAILMESSAGE="/home/java/cron/emailmessage.txt"
    echo "$HOST has failed to respond for 1 hour. The blog backup script has failed" > $EMAILMESSAGE
    # Send email using /bin/mail
    /bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE
}


#### Script starts here ####

pinghost $HOST
errorCode=$?

while [ $errorCode -eq 111 ]
do
    numErrors=$(( $numErrors + 1 ))
    echo "`date +%r`: Ping error $numErrors to $HOST" >> $LOGFILE

    if [ $numErrors -eq 6 ]; then
        echo "`date +%r`: Couldn't ping $HOST for 1 hour, emailing admin.." >> $LOGFILE
        # calling a function to email someone here
        notifyAdmin
        echo "`date +%r`: mail sent....exiting." >> $LOGFILE
        exit 1
    else
        sleep $PINGINTERVAL
        pinghost $HOST
        errorCode=$?
    fi
done

# If we're here then mecca is up. Now we need to connect and
# check if the blog extraction job is finished
# returns 202 if the pid file exits
# returns 0 if it doesn't
PIDFILE=/home/java/extract_blog.pid
function checkBlogJobFinished()
{
    if ssh $HOST 'ls "'$PIDFILE'" >/dev/null'; then
        return 202;
    else
        return 0;
    fi
}

checkBlogJobFinished
errorCode=$?
numChecks=0
# time to sleep in seconds, 7200seconds = 2 hours
SLEEPTIME=7200
while [ $errorCode -eq 202 ]
do
    numChecks=$(( $numChecks + 1 ))
    echo "`date +%r`: Check $numChecks: job still running, going to sleep for $SLEEPTIME seconds" >> $LOGFILE
    sleep $SLEEPTIME
    checkBlogJobFinished
    errorCode=$?
done

# If we're here then the blog job has finished, time to get the blog xml files

########################################
# Backup Site Directory - files        #
########################################

# remote blog folder is of format: week{currentWeekNo_currentYear}
remoteBlogFolder=/home/java/extractor/blogs/week`date +%V_%Y`
localBlogFolder=/home/java/backup/mecca/blogs

if [ ! -e $localBlogFolder ]
then
    mkdir -p $localBlogFolder
fi

echo "`date +%r`: Starting retreival of $remoteBlogFolder" >> $LOGFILE
rsync -avz -e "ssh -i /home/java/cron/hossbox-rsync-key-java" java@$HOST:$remoteBlogFolder $localBlogFolder
echo "`date +%r`: Ending retreival of $remoteBlogFolder" >> $LOGFILE

currentWeek=`date +%V`
let previousWeek=$currentWeek-1

oldBackupFolder=/home/java/backup/telex/blogs/week$previousWeek

# remove old backup
if [ -e $oldBackupFolder ]
then
    rm -rf $oldBackupFolder
fi

endTime=`date`
echo $endTime ": Ending blog backup" >> $LOGFILE

This script sleeps for 2 hours if a blog extraction job is running on the remote machine. It sleeps for 10 minutes if the remote machine isn't responding.

Monday, July 27, 2009

Accessing Oracle's Web Interface (Oracle Enterprise Manager)

I wanted to access the Oracle Web Interface for administering the database on a Cent OS system. However, I hadn't performed this oracle installation myself so I started by doing:

netstat -a | more

And looking carefully through the list to see if I could spot it but I couldn't!

Eventually I found the answer here. There is a file which contains the Oracle Enterprise Manager URL for each database installed and that file's location is:

$ORACLE_HOME/install/readme.txt

For example:
/home/oracle/app/oracle/product/11.1.0/db_1/install

Here's what mine looked like:
Enterprise Manager Database Control URL - (orcl) :
https://localhost:1158/em

Enterprise Manager Database Control URL - (bbb) :
https://localhost:5501/em

Enterprise Manager Database Control URL - (aaa) :
https://localhost:5500/em

And there you have it! Enjoy!

Monday, June 15, 2009

nmefwmi.exe stopped working and was closed

I installed Oracle 11g last week on my laptop (Windows Vista Business Edition) and had no issues except a reduction in my machine's performance.

However yeseterday windows update wanted to install some updates and one of which was Service Pack 2 which I let it install. Ever since then every 5 minutes I get this error message in a popup:

nmefwmi.exe stopped working and was closed


After doing some searching this is apparently a bug in Oracle 11g that is yet to be resolved by Oracle. I found hearing that strange since the problem only started occuring for me after a windows update.

I found this answer which explains how to fix the issue:

* nmefwimi.exe is Oracle Enterprise Manager process and it is not critical in the sense what when it stops working it will not affect the database.
* nmefwmi.exe process is associated with OracleDBConsoleorcl service.
* Go to Administrative Tools -> Services, stop the service and set the startup type to "Manual".
* When you need to use dbconsole, start the service manually, ignore the error, do what you have to do, and stop it again.

Sunday, May 10, 2009

Update & Documentation Submitted

[Week 31]

These past two weeks I've been very busy with the project and finishing off continuous assessment projects.

I started by looking at my method for generating the JTree. While taking Martin's comments on board I came up with a new method for constructing the tree correctly. This was great as I could then produce correct XPath expressions.

I moved onto to integrating Martin's code for querying. I learned about the SQL packages and classes that come with Java. More specifically which object to instantiate for passing an SQL statement, sending that to the database and collecting the results. This works well now and was a big milestone as I had then achieved all basic functionality with the project.

The meeting with Mark on Thursday was good as he gave some good suggestions on how to improve on what I had done. They were:
- Show before and after times (how my querying performs over eXist)
- Introduce the ability to specify a predicate on a node
- Introduce support for more datasets

I have managed to get basic predicates working. So a user may select a node, e.g. name and actually specify a name.

Martin provided me with lots more datasets. All XML files so I needed to write the schemas for these. I managed to complete this today. I may need to look into support attributes.

Submitted my Technical Specification, User Manual and Sample Code on Friday so good to get all that out of the way. I forgot to attach a print out of this blog, hopefully that will not be a problem. I'll contact GK tomorrow.

That's about it for now. It's time to focus on exams!

Sunday, May 3, 2009

Update on progress with XSOM

[Week 29]

I managed to parse some XML schema files with XSOM, produce a tree and XPath expressions this week so decided it was good time to meet with MOC again.

He informed me that the tree I was producing was not fully correct for the XML schema I was using. Therefore I need to look at my parsing method again and adapt it correctly. If the tree is incorrect then it will produce incorrect XPath expressions. Therefore it is critical that I get this method correct.

We did discuss the next stages in detail and Martin has written code to insert XML documents into a relational database in a specialised way. He also has code to query the relational database. As part of my project specification I do not insert any data into a relational database. I do, however query it. Therefore I will use his Index Builder program to insert some XML documents into the database and integrate his query program with mine so that the XPath expressions produced from my program can be used to query the data.

I have arranged a meeting with MR for Thursday this coming week to go over the project so my next post will discuss how the integration of Martin's code went and the outcome of the meeting with MR.

Sunday, April 19, 2009

Hello to XSOM, bye to Apache XML Schema

[Week 27]

I got a recommendation from a classmate to use XML Schema Object Model (XSOM) for the XML Schema parsing. I've looked into this and I'm glad to say after a few hours of studying the schema and search mailing list archives I'm managing to extract information from files.

I've am now moving on to try and build the tree to visually represent the XML schema.
I had a meeting with MOC on Thursday discussing the general progress of the project and the fact that I'm behind schedule. He encouraged me to continue working on getting the tree built so that a user may then build XPath expressions using my GUI. Once I have this working he suggested that we arrange another meeting to plan the next steps.

This sounds promising so hopefully I can get a fairly generic parsing process in place and the tree working soon.

Sunday, April 12, 2009

Apache XML Schema not so good

[Week 26]

I've been spending the last few weeks trying to get used to the Apache XML Schema API so that I can begin to extract information from XML Schema files. This is proving quite a bit more complex than I imagined and has brought me way behind schedule.

I've been emailing the developers mailing list in search of support and have received some replies however I am still having problems extracting information. I may have to look into finding a completely different API for this.

Why does this bring me so behind schedule?
There are three main parts to the project:
- Parse XML Schemas and represent them in a GUI (I plan to use JTree)
- Allow the user to select nodes and produce the XPath expression
- Convert this to SQL and send query to a relational database and display
the results to the user.

Unless I can parse files then there is no way I can create the JTree so I need to fix this part before moving on. With other assignment deadlines at the moment this is proving difficult.

Sunday, March 22, 2009

JTree Observations and Inital Screenshots

[Week 23]



This is the main screen after the application is launch. For now I've hard coded some dumb data into the JTree for testing. 


To the left of the JTree is the AWT List which is contain the names of schemas loaded into the application




Here we can see one XSD file in the AWT list on the left. Also I've added an event listener to the JTree and made use of the getSelectionPath() method which returns a TreePath object. 



We can see the TreePath object as a string displayed below the application window. It will be these paths that I will later convert to XPath and display to the user.

Sunday, March 8, 2009

Commons XML Schema Model

[Week 21]

Commons XML Schema model is a general purpose schema model that can be used when a Java object tree representation of an Xml schema is required. -http://bit.ly/SUxXC

I found this API for processing XML schemas. It sounds like it will be perfect for my needs. Quite busy with continuous assessment projects at the moment. I will continue experimenting with this API as time allows and post back on project updates as soon as possible.

Sunday, February 22, 2009

Netbeans, Basic GUI Work & Subversion Setup

[Week 18]

Last year I used Eclipse for my 3rd year project along with a plugin for designing the GUI. I started experimenting with Netbeans in September. I have found it to provide all of the functionality that Eclipse does albeit a few things are in different places, e.g. generating getters and setters for classes. However it does more out the box. The most basic version of Netbeans available for download is only 39MB and includes a graphical GUI builder. Therefore I've been using Netbeans ever since and it proved very useful for my patterns project in semester 1. I will also be making use of Netbeans for my RMI assignment due shortly.

This week I've been trying out various GUI components and deciding on suitable ones for the project. I will post a screenshot as soon as I have some basic functionality working. Anyway I've decided to use a JTree for representing the XML schema to the user. Also I decided an awt List would be handier than a JList. This will be the list of schemas the user has loaded into the application. The user will be able to select a schema from the list and this will update the JTree appropriately. An awt list is handier because of its add(String item) and add(String item, int index) methods. Whereas with JList a data model must be constructed and this is not needed for this list. Of course a JTree will need a data model but this is worth constructing for the schema and the task of doing this will be delegated to a different class.

Finally I've setup a subversion repository for my project on my redbrick account and synchronised it with the project in Netbeans. I ran into a few connection issues. This was fixed after I setup the DCU proxy in Netbeans. Using subversion will no doubt be invaluable in keeping track of project changes with the ability to compare source files with previous versions and revert if need be.

This coming week I plan to continue with GUI development and research into XML schema parsing.

Sunday, February 8, 2009

Adobe AIR / Flex

[Week 16]

Been playing around with Adobe AIR and Flex the past week. I'm trying to find effective GUI libraries for the project. Flex is very nice and quite powerful. As with all new things there is a little learning curve though! I'm still getting used to the components. I have learned that it may not be possible to integrate an Adobe AIR application with Java unless I used web services, ie. JSPs, tomcat server etc. 

Therefore this week I'll start researching Swing/AWT libraries for this project. They might not be as easy on the eyes but may be better to stay in familiar ground for now until I get the basics working.