Saturday 31 March 2007

Linux: How many songs do I have

I have always wanted to know the exact number of music files that I own. Of course Amarok appears to have the correct answer, still I always wanted to write something like that
#!/bin/bash
# Count the music files starting form MUSIC_BASE
# Thanassis Bakalidis
# 31-03-2007

# This is the directory containing all my music
MUSIC_BASE=/mnt/Culture/My\ Mjavascript:void(0)usic
# Add more music file extentions here
MUSIC_EXTENTIONS="mp3 wma ogg flac"

echo Base directory is $MUSIC_BASE

TOTAL_FILES=0
for ext in $MUSIC_EXTENTIONS
 do 
   echo ""
   echo Saerching for $ext  files
   current=`find "$MUSIC_BASE" -type f -name "*.$ext" -print | wc -l`
   echo Located $current $ext files
   TOTAL_FILES=`expr $TOTAL_FILES + $current`
done

echo ""
echo A total of $TOTAL_FILES music files were accounted.
exit

Wednesday 28 March 2007

ABAP: Check if a day ix a holiday

Here is some sample code that allows you to determine if a date passed as parameter is a holiday or a weekend day.

FORM check_if_holiday
                USING
                  value(fact_cal) LIKE scal-fcalid
                  value(holiday_cal) LIKE scal-hcalid
                  a_date TYPE d.
  FIELD-SYMBOLS :
     TYPE casdayattr.

  DATA
    days_attr_tbl TYPE STANDARD TABLE OF casdayattr.

* get the attributes for the specified day 
  CALL FUNCTION 'DAY_ATTRIBUTES_GET'
   EXPORTING
     factory_calendar                 = fact_cal      " default 'GR'
     holiday_calendar                 = holiday_cal   " default 'GR'
     date_from                        = a_date
     date_to                          = a_date
     language                         = sy-langu
*   IMPORTING
*     YEAR_OF_VALID_FROM               =
*     YEAR_OF_VALID_TO                 =
*     RETURNCODE                       =
    TABLES
      day_attributes                   = days_attr_tbl
   EXCEPTIONS
     factory_calendar_not_found       = 1
     holiday_calendar_not_found       = 2
     date_has_invalid_format          = 3
     date_inconsistency               = 4
     OTHERS                           = 5.
  IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
            WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
  ENDIF.

  READ TABLE days_attr_tbl INDEX 1 ASSIGNING <day_attr>.

  IF NOT <day_attr>-holiday_id IS INITIAL.
    MESSAGE w888(sabapdocu) WITH a_date text-e05  <day_attr>-txt_long.
  ENDIF.

  IF <day_attr>-weekday = '6' OR  <day_attr>-weekday = '7'.
    MESSAGE w888(sabapdocu) WITH a_date text-e06 -weekday_l.
  ENDIF.
ENDFORM.                    " check_if_holiday

The parameters fact_cal and holiday_cal are two letter country code representations, so in my case, they may be hard coded to the value 'GR'.

A practical way to use the above would be :

On the screen flow logic

PROCESS AFTER INPUT.
 ...
    FIELD input_date
      MODULE input_date_changed ON REQUEST.

On the actual code

MODULE input_date_changed INPUT.
  PERFORM check_if_holiday USING 'GR' 'GR' input_date.
ENDMODULE.

Update source for Mozilla Products on openSUSE

I have always wondered why there were no updates for the SuSE provided Firefox. Looking a bit more carefully at the openSUSE site, I realized that in order to get updates for Firefox, SeaMonkey and Thunderbird, you need to add an additional YaST source.

The base directory for all Mozilla related products on SuSE Linux is http://software.opensuse.org/download/mozilla/.

You can add the correct path for your Linux distribution from there.

For example the openSUSE 10.2 the source URL is http://software.opensuse.org/download/mozilla/openSUSE_10.2/.

As far as I am concerned, there are more good news as I realised that the base address also offers versions for SLES9 and SLES10.

Wednesday 21 March 2007

Linux: A simple backup script

Here is the script I use for backing up my home directory onto the hard drive an other machine (mounted using samba). The script can be configured by changing the values of the top variables

#!/bin/bash
# Script to back up my home directory
# Created 21-03-2007
# Thanassis Bakalidis

BKP_FILE="/mnt/KomUsers/bakalidi/LinuxBackups/my_home.tar.bz2"
BKP_ROOT="/home/thanassis"
LOG_FILE="/home/thanassis/backup_output.txt"
EXCLUDE_FILES_FILE="/home/thanassis/.files_to_exclude"
ERROR_FILE="/home/thanassis/backup_errors.txt"

EXCLUDE_DIRS="/home/thanassis/mp3 /home/thanassis/java"

# remove file if existing
if [ -f $EXCLUDE_FILES_FILE ]; then
 rm $EXCLUDE_FILES_FILE
fi

# get a list of all file patterns that do not need be backed up
for path in $EXCLUDE_DIRS
do
 echo $path/\* >> $EXCLUDE_FILES_FILE
done

# finally append the log file in the list of excluded files
echo $LOG_FILE >> $EXCLUDE_FILES_FILE
echo $EXCLUDE_FILES_FILE >> $EXCLUDE_FILES_FILE

# start the log File
echo Backup of $BKP_ROOT Starting at `date` > $LOG_FILE

# after creating the list of files to be excluded perform the actual backup
/bin/tar -jcvf $BKP_FILE -X $EXCLUDE_FILES_FILE --exclude-caches  $BKP_ROOT  1>> $LOG_FILE 2>$ERROR_FILE

# mark the end time stamp on the log file and exit
echo Backup of $BKP_ROOT finished at  `date` >> $LOG_FILE
exit 0

It is true that one could directly edit the $EXCLUDE_FILES_FILE and add the patterns of the files that should not be backed up. Personally, I prefer the approach shown above, because that way I keep all my information regarding backups in one place and thus have less configuration files to worry about-- Of course there is always more than one way to do things right.

Finally I have added the following in my crontab config :

thanassis@lxbakalidis:~> crontab -l
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (/tmp/crontab.XXXXhnhNTc installed on Wed Mar 21 11:52:39 2007)
# (Cron version V5.0 -- $Id: crontab.c,v 1.12 2004/01/23 18:56:42 vixie Exp $)
30 18 * * * /home/thanassis/bin/tarbackup.sh

The /mnt/KomUsers speciffied as target in script file directory points to the users folder of a Windows 2003 server on my local area network. The company administrator runs tape backup jobs at exactly 19:00 everyday, so starting my backup at 18:30 allows me to keep a copy of my data every day in a separate tape following the day, week, month company schedule.

Linux: How to mount Windows Shares with Samba at startup

This posting applies for SuSE systems only. If you are using Red Hat or any of its clones like CentOS or OEL for example, then information required for mounting windows shares at startup can be found at this very neat and precise article at the CentOS Wiki website.

Install the samba-client package. After installation you end up with a directory named /etc/samba.

thanassis@lxbakalidis:~> rpm -q samba-client
samba-client-3.0.23d-19.2

Create the mount points for the new directories. Mine are at /mnt

Add appropriate entries inside the file named smbfstab located inside /etc/samba.

The entries in /etc/samba/smbfstab must have the following form :

//my_windows_pc/my_share  /mnt/my_dir  cifs   username=windows_user,
password=win_pasword,uid=thanassis,gid=dba,file_mode=0644,dir_mode=0755,
iocharset=iso8859-7

Note that the the above statement should be placed in a single line. You need one sutch line per mount point. It is also a good idea to use case sensitive references to windows shares especially if mounting drives from Windows NT.

Next, use the iocharset addition only if your Linux machine is not configured for UTF-8.

Reboot

Sunday 18 March 2007

Linux: How to use iptables in order to deny access to speciffic IP's

Eventually I had to deal with that as well. Somebody trying to start DOS attacks on my site. Asking the experts revealed th at the safest way to deal such cases is to use iptables. The command works on the kernel level for any kind of access to your entire web space. To get things started let's suppose that the offending IP address is 192.167.250.1. To block out this address completely enter the following as root.

iptables -A INPUT -s 192.167.250.1 -j DROP

Naturally attacks do not come from just one IP. Their usual sources are entire ISP address blocks so it is much better to block out the entire IP range. The correct syntax for this command is :

iptables -A INPUT -s 192.167.250.0/24 -j DROP

Listing all active iptables rules is performed by the following command.

iptables -L

I will update this post with more info as soon as I 've learned more. For the moment here is a link for more info on the subject

Monday 12 March 2007

Sending mail using Java Mail

In addition to the previous article, I shall provide here a slightly changed version of Sudhir Ancha's code as presented in his Sending Email From Your Application Using Java Mail article at javacomerice.com.

The only notable difference is the Charset = .. addition to the setContent() method of the message class, that allows sending the message using the iso8859-7 Greek character set.

package utils.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
 * @class SendMail
 * Encapsulates a simple mail sending using a specific SMTP Server
 */
public class SendMail {
    // put you server here
    public static final String SMTP_HOST = "smtp.mydomain.com";

    public void post(String to, // recipient for the message
        String subject,         // subject
        String message,         // actual mesage text
        String from)            // address of sender
        throws MessagingException 
    {

        String[] recipients = new String[1];
        recipients[0] = to;

        postToMany(recipients, subject, message, from);
    }

    public void postToMany( String[] recipients, // list of recipients for the message
        String subject, // subject
        String message, // actual mesage text
        String from) // address of sender
        throws MessagingException 
    {
        boolean debug = false;

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);

        // create some properties and get the default Session
        Session session = Session.getDefaultInstance(props, null);
        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) 
            addressTo[i] = new InternetAddress(recipients[i]);
        
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Content-type: text/html; charset=utf-8\r\n
        // Optional : You can also set your custom headers in the Email if you Want
        // msg.addHeader("Content-type", "text/html; charset=utf-8");

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain; Charset=iso8859-7");
        Transport.send(msg);
    }

    private static final String emailMsgTxt = "Δοκιμαστικό μύνημα σταλμένο από Java.";
    private static final String emailSubjectTxt = "EMail from Java";
    private static final String emailFromAddress = "me@mydomain.gr";
    private static final String[] emailList = {
            "he@hisdomain.com",
            "she@herdomain.gr" 
    };
    

    public static void main(String[] args) throws Exception 
    {
        SendMail smtpMailSender = new SendMail();
        smtpMailSender.post("me@mydomain.om", emailSubjectTxt, emailMsgTxt,
                            emailFromAddress);
        System.out.println("Sucessfully Sent mail to All Users");
    }
}

Send email from PHP

Here is some sample code I came across over the net. It demonstrates two things:

One how to send email using PHP the second one is how to change the mail headers in order to send Unicode UTF-8 mail.

<?php
   $from = 'me@mydomain.com';
   $to = 'you@yourdomain.com';
   $subject = 'Sending Unicode e-mail';
   $message = '
            <p>
               Hello!
            </p>
            <p> 
                This message contains and displays unicode characters like 
                the Greek Α, Γ and Ω
             </p>';
    $header = "Content-type: text/html; charset=utf-8\r\nFrom: $from\r\nReply-to: $from";
 
    if ( mail($to, $subject, $message, $header) ) 
        echo "Email sent to $to!";
    else
        echo "Error occurred while sending email to $to!";

?>

Remember that for the mail function to work correctly the SMTP Server must be correctly specified in PHP.ini.

I will come back with more precise info as soon as I have completed my tests

Thursday 8 March 2007

Installation of SAP JCo on an Oracle IAS 10.1.3.x on Linux

1) Unpack sapjco to /opt/SAP/SAPJCo.

2) Create the following symbolic links in $ORACLE_HOME/lib

oracle@barbara:~> ln -sf /opt/SAP/SAPJCo/librfccm.so $ORACLE_HOME/lib/librfccm.so
oracle@barbara:~> ln -sf /opt/SAP/SAPJCo/libsapjcorfc.so $ORACLE_HOME/lib/libsapjcorfc.so
3) Create an additional OC4J instance to host SAP enabled Java apps.
oracle@barbara:~> createinstance -instanceName OC4J_SAP
Creating OC4J instance "OC4J_SAP"...
Set OC4J administrator's password for "OC4J_SAP" (password text will not be displayed as it is entered)
Enter password:
Confirm password:
The password for OC4J administrator "oc4jadmin" has been set.
New OC4J instance "OC4J_SAP" has been created.
oracle@lachesis:~>

4) Navigate to the instance home page. Start the new instance and then click on the administration tab and select the Shared libraries.

5) Click on the Create button at the bottom of the page.

5.1) On the Create shared library attributes page enter SAPJCo for the library name and the corresponding SAPJCo version (eg 2.1.6) for the version. Click next

5.2) The following page is entitled “Create Shared Library: Add Archives”. Click on the Add button and insert the /opt/SAP/SAPJCo/sapjco.jar file. Click next

5.3) The final step is the page entitled “Create Shared Library: Import Shared Libraries”. You do not need any adjustments here. Just click finish.

... and that does it.