Pages

2011-07-29

Recompile virtual box kernel modules after kernel update

If Virtualbox or guest aditions are not starting ater a kernel update, just recompile the kernel modules:


o On a Virtualbox server

    /etc/init.d/vboxdrv setup


o On a Virtualbox guest


    /etc/init.d/vboxadd setup

Grub2: Set default boot option

o Get the string of the menu entry you desire to be default

  fgrep menuentry /boot/grub/grub.cfg
  ...
  menuentry "Some OS" {
  ...
 

o Add menu entry to /etc/default/grub
  
  vi /etc/default/grub 

  GRUB_DEFAULT="Some OS"

o Update grub


  update-grub

Enhance Adobe flash player performance in Linux

These settings will slightly improve the performance of the adobe flash
plugin:

o Customize /etc/X11/xorg.conf
     
  Section "Extensions"
    # for 3D, alpha desktop effects
    Option "Composite" "Enable"
  EndSection

  Section "DRI"
    # helps flash performance
    Mode 0666
  EndSection

o Override GPU Validation

   - Sytem wide

    sudo mkdir /etc/adobe
    echo "OverrideGPUValidation=true" > /etc/adobe/mms.cfg

- Or user wide

    echo OverrideGPUValidation=true > ~/.adobe/mms.cfg


Get SOAP communication using tcpdump

Assume you have a Tomcat running on localhost on port 8080 and want see the content of the SOAP messages of the communication:
tcpdump -i lo0 -A -s 1024 -l 'dst host localhost and port 8080'

2011-03-30

Drop Oracle Database

Since 10g, It is possible to drop a database in Oracle 10g with the new SQL statement drop database.
The command gets rid of datafiles online redo log files, controlfiles and spfile:
sqlplus / as sysdba
shutdown abort;
startup mount exclusive restrict;
drop database;
exit

2011-03-29

Debian Squeeze: Black screen or freeze on the console after stopping Xserver

Atom powered device


Solution -- add i915.modeset=0 to kernel options in Grub

JayBird - Firebird JDBC link

/**
*
*/
package link.db.my;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* @author E. Kaparulin
*/
public class JayBird {
        private Connection conn = null;
        private String Url = "jdbc:firebirdsql:127.0.0.1/3050:mydb";
        private String dbUserName = "user";
        private String dbUserPass = "password";
        private String dbCharSet = "ASCII";
        static final Logger logger = Logger.getLogger("org.firebirdsql");
        public JayBird() {
                System.setProperty("FBLog4j", "true");
                Properties props = new Properties();
                props.setProperty("user", dbUserName);
                props.setProperty("password", dbUserPass);
                props.setProperty("encoding", dbCharSet);
                try {
                        Class.forName("org.firebirdsql.jdbc.FBDriver");
                        try {
                                conn = DriverManager.getConnection(Url, props);
                        } catch (SQLException e) {
                                logger.fatal(e.getMessage());
                        }
                } catch (ClassNotFoundException e) {
                        logger.fatal(e.getMessage());
                }
        }
        private Connection getConnection(){
                return conn;
        }
        public int UpdateQuery(String Query) throws SQLException {
                int ret = -1;
                Connection sqlConn = getConnection();
                Statement Statement = sqlConn.createStatement();
                ret = Statement.executeUpdate(Query);
                Statement.close();
                return ret;
        }
        public ResultSet SelectQuery(String Query) throws SQLException {
                Connection sqlConn = getConnection();
                Statement Statement = sqlConn.createStatement();
                ResultSet rs = Statement.executeQuery(Query);
                return rs;
        }
}

Get properties file from WEB-INF/classes

        PropertyResourceBundle   p = (PropertyResourceBundle)           
         ResourceBundle.getBundle(CONF_FILE);
        String myValue = p.getString("myKey");

Trim String (remove tabs and white spaces)

        private String trimValue(String inputStr) {
                String patternStr = "(( |\t)*$|^( |\t)*)";
                String replacementStr = "";
                // Compile regular expression
                Pattern pattern = Pattern.compile(patternStr);
                // Replace all occurrences of pattern in input
                Matcher matcher = pattern.matcher(inputStr);
                return matcher.replaceAll(replacementStr);
        }

Calculate a MD5 sum of a string

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
   public String getMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

Create a random string

import java.util.Random;
/**
* @author E. Kaparulin
*/
public class RandomString {
        private final char[] alphanumeric=alphanumeric();
            private final Random rand;
            public RandomString(){this(null);}
            public RandomString(Random rand){
              this.rand=(rand!=null) ? rand : new Random();
            }
            public String get(int len){
                StringBuffer out=new StringBuffer();
                while(out.length() < len){
                    int idx=Math.abs(( rand.nextInt() % alphanumeric.length ));
                    out.append(alphanumeric[idx]);
                }
                return out.toString();
            }
            // create alphanumeric char array
            private char[] alphanumeric(){
                StringBuffer buf=new StringBuffer(128);
                for(int i=48; i<= 57;i++)buf.append((char)i); // 0-9
                for(int i=65; i<= 90;i++)buf.append((char)i); // A-Z
                for(int i=97; i<=122;i++)buf.append((char)i); // a-z
                return buf.toString().toCharArray();
            }
}

Simple SMTP Email

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class SmtpSimple {
        private DataOutputStream os = null;
        private BufferedReader is = null;
        private String sRt = "";
        public synchronized final String sendEmail(
                        String sSmtpServer,String sFromAdr,String sToAdr,String sSubject,String sText)
                        throws IOException, Exception {
                Socket so = null;
                try {
                        sRt = "";
                        if (null == sSmtpServer
                                        || 0 >= sSmtpServer.length()
                                        || null == sFromAdr
                                        || 0 >= sFromAdr.length()
                                        || null == sToAdr
                                        || 0 >= sToAdr.length()
                                        || ((null == sSubject || 0 >= sSubject.length()) && (null == sText || 0 >= sText
                                                        .length())))
                                throw new Exception(
                                                "Invalid Parameters for SmtpSimple.sendEmail().");
                        so = new Socket(sSmtpServer, 25);
                        os = new DataOutputStream(so.getOutputStream());
                        is = new BufferedReader(new InputStreamReader(so.getInputStream()));
                        so.setSoTimeout(10000);
                       
                        writeRead(true, "220", null);
                        writeRead(true, "250", "HELO " + sSmtpServer + "\n");
                        writeRead(true, "250", "RSET\n");
                        writeRead(true, "250", "MAIL FROM:<" + sFromAdr + ">\n");
                        writeRead(true, "250", "RCPT TO:<" + sToAdr + ">\n");
                        writeRead(true, "354", "DATA\n");
                        writeRead(false, null, "To: " + sToAdr + "\n" );
                        writeRead(false, null, "From: " + sFromAdr + "\n");
                        writeRead(false, null, "Subject: " + sSubject + "\n");
                        writeRead(false, null, "Mime-Version: 1.0\n");
                        writeRead(false, null, "Content-Type: text/plain; charset=\"iso-8859-1\"\n");
                        //writeRead(false, null, "Content-Transfer-Encoding: quoted-printable\n\n");
                        writeRead(false, null, "Content-Transfer-Encoding: 7bit\n\n");
                        writeRead(false, null, sText + "\n");
                        writeRead(true, "250", ".\n");
                        writeRead(true, "221", "QUIT\n");
                        return sRt;
                } finally {
                        if (is != null)
                                try {
                                        is.close();
                                } catch (Exception ex) {
                                }
                        if (os != null)
                                try {
                                        os.close();
                                } catch (Exception ex) {
                                }
                        if (so != null)
                                try {
                                        so.close();
                                } catch (Exception ex) {
                                }
                        is = null;
                        os = null;
                }
        }
        private final void writeRead(boolean bReadAnswer,
                        String sAnswerMustStartWith, String sWrite) throws IOException,
                        Exception {
                if (null != sWrite && 0 < sWrite.length()) {
                        sRt += sWrite;
                        os.writeBytes(sWrite);
                }
                if (bReadAnswer) {
                        String sRd = is.readLine() + "\n";
                        sRt += sRd;
                        if (null != sAnswerMustStartWith
                                        && 0 < sAnswerMustStartWith.length()
                                        && !sRd.startsWith(sAnswerMustStartWith))
                                throw new Exception(sRt);
                }
        }
}

Parse XML file

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document myXML = docBuilder.parse(xmlFile);
// normalize text representation
myXML.getDocumentElement().normalize ();
//System.out.println ("Root element of the doc is " + myXML.getDocumentElement().getNodeName());
// Dive into XML Structure
NodeList myNode =  myXML.getDocumentElement().getChildNodes();
for(int i=0;i<myNode.getLength();i++) { …

2011-01-12

Generate a random number from a range


      public int getRandomNumberFromRange(int Min, int Max) {
            Random rn = new Random();
            int Delta = Max - Min + 1;
            int Offset = rn.nextInt() % Delta;
            int RandVal = Min + Offset;
            if (RandVal == 0)
                  return Min;
            return (RandVal > 0) ? RandVal : (RandVal * -1);
      }

That's it!