Wednesday, December 31, 2014

Create .tar file in Linux

Following command can be used to create .tar file in Linux.

tar -cvf all.tar *.txt

Above command ceate tar files for all .txt files in the directory.


Wednesday, December 10, 2014

Find port usage

Following command can be used to check port usage.
In windows command prompt type following command.

netstat -aon |find /i "listening" |find "port"

This will return port usage.

Thursday, December 4, 2014

SSH vfs2 Change FTP Directory

Following configuration can be used to change logged user directory. In normally, FTP directory is set to logging user home. Sometimes, you have to access directories outside of the logging SFTP user home.

SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);

This code snip can be used, when you are using vfs2 SFTP client.

Now, you can FTP files in any location using following SFTP URI.

"sftp://" + userID + ":" + password + "@" + sftpHost + "/" + remoteDirectory + fileName

Change remote directory as you preferred.

Wednesday, November 12, 2014

Ubuntu Graphical Desktop

In Ubuntu VM installations, you can't get graphical desktop. It only prompt for terminal view. You can use following command to start Ubuntu in graphical view.

startx

If this command not found, hen you have to update Ubuntu desktop using following command.

sudo apt-get install ubuntu-desktop

Then use startx command.

Tuesday, October 28, 2014

SFTP in JAVA

Following JAVA functions can be used to execute SFTP(Secure FTP).

    public boolean putSFTPFile(String sftpHost, String userID, String password, String remoteDirectory, String localDirectory, String fileName) throws FileSystemException {

        boolean put = false;
        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {

            String filepath = localDirectory + fileName;
            File file = new File(filepath);
            if (!file.exists()) {
                throw new RuntimeException("Error. Local file not found.");
            }
            manager.init();

            FileSystemOptions opts = new FileSystemOptions();
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                    opts, "no");
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

            String sftpUri = "sftp://" + userID + ":" + password + "@" + sftpHost + "/" + remoteDirectory + fileName;

            FileObject localFile = manager.resolveFile(file.getAbsolutePath());
            System.out.println(file.getAbsolutePath());

            FileObject remoteFile = manager.resolveFile(sftpUri, opts);

            remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
            put = true;

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            manager.close();
        }
        return put;
    }

    public boolean getSFTPFile(String sftpHost, String userID, String password, String remoteDirectory, String localDirectory, String fileName) {

        boolean get = false;
        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {

            manager.init();

            FileSystemOptions opts = new FileSystemOptions();
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                    opts, "no");
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

            String sftpUri = "sftp://" + userID + ":" + password + "@" + sftpHost + "/"
                    + remoteDirectory + fileName;

            String filepath = localDirectory + fileName;
            File file = new File(filepath);
            FileObject localFile = manager.resolveFile(file.getAbsolutePath());

            FileObject remoteFile = manager.resolveFile(sftpUri, opts);

            localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
            get = true;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            manager.close();
        }
        return get;
    }

    public boolean deleteSFTFile(String sftpHost, String userID, String password, String remoteDirectory, String fileName) {

        boolean delete = false;
        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {

            manager.init();

            FileSystemOptions opts = new FileSystemOptions();
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                    opts, "no");
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

            String sftpUri = "sftp://" + userID + ":" + password + "@" + sftpHost + "/"
                    + remoteDirectory + fileName;

            FileObject remoteFile = manager.resolveFile(sftpUri, opts);

            if (remoteFile.exists()) {
                if (remoteFile.delete()) {
                    delete = true;
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            manager.close();
        }
        return delete;
    }

    public Collection getSFTPFileList(String sftpHost, String userID, String password, String remoteDirectory) throws FileSystemException {

        Collection fileCollection = new ArrayList();
        StandardFileSystemManager manager = new StandardFileSystemManager();

        FileObject localFileObject = manager.resolveFile("sftp://" + userID + ":" + password + "@" + sftpHost + "/" + remoteDirectory);
        FileObject[] children = localFileObject.getChildren();

        for (int i = 0; i < children.length; i++) {
            fileCollection.add(children[ i].getName().getBaseName());
        }

        return fileCollection;
    }

    public boolean isRemoteFileExist(String sftpHost, String userID, String password, String remoteDirectory, String fileName) {
        StandardFileSystemManager manager = new StandardFileSystemManager();
        boolean isExist = false;

        try {
            manager.init();

            //Setup our SFTP configuration
            FileSystemOptions opts = new FileSystemOptions();
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                    opts, "no");
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

            String sftpUri = "sftp://" + userID + ":" + password + "@" + sftpHost + "/"
                    + remoteDirectory + fileName;

            FileObject remoteFile = manager.resolveFile(sftpUri, opts);

            isExist = remoteFile.exists();

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            manager.close();
        }
        return isExist;
    }

Monday, October 27, 2014

Password Authenticate with SALT value

In password authentication, most developers use hash value generation. Hash value has a unique value for every word. If two users have same password, both has same hash value for their password. The solution is to generate salt value for password. Before proceeding hash generating, password is appended with salt value. The salt value is not a secret value. For validation, hash value and  salt value must be known from the developer.

Following article for user authentication described clearly with sources..

https://crackstation.net/hashing-security.htm#normalhashing

Wednesday, October 1, 2014

Cron to STOP/ START Program

In Linux, you can use crontab to stop/ start applications.

 Following shell script (stop.sh) can be used to grep your program & kill it.

#!/bin/bash

PGID=`ps -eaf | grep YourProgram | grep YourName | grep -v grep | awk '{print $2}'`

if [ -n $PGID ]
then 
/bin/kill -9 $PGID
else
echo "Not Running"

fi

After stopping, you can run the following program(start.sh) to restart the application. This will grep to check whether application runs or not. If runs, shell terminates with "Already Running" error. Else, it will run the application with nohup and send a mail to owner using mailx linux API.

#!/bin/bash

PRGHOME=/home/sujith/ReminderSMS

ps –eaf | grep YourProgram| grep YourName|grep -v grep | awk '{print $2}' > /home/ sujith/.tmp.ReminderAlert

if [ -s /home/ sujith/.tmp.ReminderAlert ]
then

echo "Already Running"

else

#. /home/ sujith/.bash_profile
cd $PRGHOME

echo 'program_alert_started' | mailx sujith@test1.lk
nohup java YourProgram &

rm /home/ sujith/.tmp.ReminderAlert

fi


Wednesday, September 24, 2014

JAVA Server Socket Server & Client Program

Following code can be used to run a server socket application. This socket application listen requests on "locathost" port "10225" .

Socket Server Program

public class SocketServer {

    ServerSocket m_ServerSocket;
    Logger logger;
    int SERVER_PORT = 10225;

    public SocketServer() {
        try {
            m_ServerSocket = new ServerSocket(SERVER_PORT);
        } catch (IOException ioe) {
            System.out.println("Could not create server socket " + SERVER_PORT + " Quitting. " + ioe);
            System.exit(-1);
        }
        int id = 0;
        while (true) {
            try {
                Socket clientSocket = m_ServerSocket.accept();
                ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
                cliThread.start();
            } catch (Exception ioe) {
                System.out.println("Constructor : " + ioe);
            }
        }
    }

    public String process(String input) {
        String response = "";
        // your process logic
        return response;
    }

    class ClientServiceThread extends Thread {

        Socket m_clientSocket;
        int m_clientID = -1;
        boolean m_bRunThread = true;

        ClientServiceThread(Socket s, int clientID) {
            m_clientSocket = s;
            m_clientID = clientID;
        }

        public void run() {
            BufferedReader in = null;
            PrintWriter out = null;
            System.out.println("Accepted Client ID - " + m_clientID + " |Address - " + m_clientSocket.getInetAddress().getHostName());

            try {
                in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
                out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));

                while (m_bRunThread) {
                    String clientCommand = in.readLine();
                    System.out.println("Client Says :" + clientCommand);
                    if (!clientCommand.equalsIgnoreCase("Quit")) {
                        out.println(process(clientCommand));
                    }
                    if (clientCommand.equalsIgnoreCase("quit")) {
                        m_bRunThread = false;
                    } else {
                        out.flush();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                    out.close();
                    m_clientSocket.close();
                    System.out.println("...Stopped");
                } catch (IOException ioe) {
                    System.out.println("ClientServiceThread.run " + ioe);
                }
            }
        }
    }

    public static void main(String[] args) {
        new ChargeSocket();
    }
}

Socket Client Program

    public String connectToSocket(String ip, int port, String request) {
        String response = null;
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
        } catch (UnknownHostException unknownhostexception) {
            System.out.println("Unknown Host :localhost");
            socket = null;
        } catch (IOException ioexception) {
            System.out.println("Cant connect to server at " + ip + " " + port + " Make sure it is running.");
            socket = null;
        }
        if (socket == null) {
            return null;
        }
        BufferedReader bufferedreader = null;
        PrintWriter printwriter = null;
        try {
            bufferedreader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printwriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            printwriter.println(request);
            printwriter.flush();
            response = bufferedreader.readLine();
            System.out.println("Server Says : " + response);
            printwriter.println("Quit");
            printwriter.flush();
        } catch (IOException ioexception) {
            System.out.println("Exception during communication. Server probably closed connection.");
            ioexception.printStackTrace();
        } finally {
            try {
                printwriter.close();
                bufferedreader.close();
                socket.close();
            } catch (Exception exception1) {
                exception1.printStackTrace();
            }
        }
        return response;

    }

Tuesday, August 19, 2014

WSO2 IS enable logging

In WSO2 Identity Server settings, it is deactivated logging for performance gaining. You can activate WSO2 IS logging using following command for debugging issues.

log4j.logger.org.wso2.carbon.identity.sso.saml=DEBUG

Add above log4j property in below file.

./repository/conf/log4j.prorperties

Tuesday, July 22, 2014

Set Password in PDF in Jasper Report

Following code snip can be used to create protected PDF. This authentication is enabled in jasper report 5.6 onward.

   SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
                
  configuration.setEncrypted(true);
  configuration.set128BitKey(true);
  configuration.setUserPassword("jasper");
  configuration.setOwnerPassword("reports");
  configuration.setPermissions(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
  exporter.setConfiguration(configuration);
  exporter.exportReport(); 

Friday, July 11, 2014

Change default JAVA path

Once you installed JAVA 1.7 or 1.8, your default JAVA path is changed. But, it is not listed in Environment Variable Properties. To change to another JAVA path, you can simply do the following.

In Windows,

  1. go to "C:\Windows\System32" 
  2. delete "java.exe"
  3. add JAVA path to environment variable
  4. open command prompt
  5. check JAVA version (java -version)

Sunday, June 22, 2014

Find Disk size of directories in Linux

Following Linux command can be used to filter size of gigabytes of directories in Linux.

du -hs * | grep G

du -hs * == calculates disk sizes
grep G   == filters gigabyte size

Friday, May 30, 2014

FIND_IN_SET vs IN SQL commands

IN
This keyword is used to get data values equals to IN clause values.

Example :-

Select * from test_table where field_1 IN ('123','abc','873','345')

Above SQL returns values equals to 123,abc,873,345 in field_1.

FIND_IN_SET

Suppose you have a String values like "123,abc,873,345". You can use FIND_IN_SET to get IN clause supported string as '123','abc','873','345'.

Select * from test_table where field_1 FIND_IN_SET (',','123,abc,873,345')

This SQL is also return above IN SQL results.

Check highlighted values.

Wednesday, May 28, 2014

Split pipe separated column in Linux

Suppose you have a file that have pipe ("|") separated values.

122344|093462|45836
472391|093742|23444

If you want to split column 2 values, you can use the following command to get second column values easily.

cat log.txt | awk -F"|" '{print $2}'>second_column_log.txt

This will create a file called "second_column_log.txt" that contains column two values.

093462
093742

Check file differences in Linux

Following Linux command can be used to check two file line differences.
Before using the command you must sort the file using sort Linux command.

1.) sort err_file_1.txt > sorted_file_1.txt
2.) sdiff err_file_1.txt err_file_2.txt

Output will be shown in Linux terminal. You can write output to file using following command.

1.) sdiff err_file_1.txt err_file_2.txt >output.txt

Thursday, March 20, 2014

HTTP GET/POST Example

Following example can be used to send HTTP GET or POST request to web server using JAVA application.

// HTTP GET request
private void sendGet() throws Exception {

String url = "http://seguide.blogspot.com";

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);

request.addHeader("User-Agent", USER_AGENT);

HttpResponse response = client.execute(request);

System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + 
                       response.getStatusLine().getStatusCode());

BufferedReader rd = new BufferedReader(
                       new InputStreamReader(response.getEntity().getContent()));

StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}

System.out.println(result.toString());

}

// HTTP POST request
private void sendPost() throws Exception {

String url = "http://seguide.blogspot.com";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

post.setHeader("User-Agent", USER_AGENT);

List urlParameters = new ArrayList();
urlParameters.add(new BasicNameValuePair("name", "sujith"));
urlParameters.add(new BasicNameValuePair("pass", "abc123"));
urlParameters.add(new BasicNameValuePair("param1", "param1"));
urlParameters.add(new BasicNameValuePair("param2", "param2"));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + 
                                    response.getStatusLine().getStatusCode());

BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}

System.out.println(result.toString());

}

Wednesday, March 19, 2014

Change permission for user in Linux

Following set of commands can be used to change the permission of a user.

Change directory
           sujithde@ewaps1:~> cd delight/

Change permission for user oracle
           sujithde@ewaps1:~/delight> setfacl –R -m user:oracle:rwx .

Add user a mask
           sujithde@ewaps1:~/delight> setfacl –R -m mask:rwx .

Note : –R will recursively change permission for sub folders. 

Wednesday, March 5, 2014

Run SQL script in Background in MySQL server

Following command can be used to run SQL script in background in MySQL server.

mysql --user=sujith --pass=123suji --database=postdb --host=localhost script_file results.out &

This will return output of script  to result.out file.

Tuesday, March 4, 2014

JAVA 8 Lambda Expression

Following example explain how Lambda Expression can be implemented in JAVA 8.

    interface MathOperation {

        int execute(int a, int b);
    }

    public int calculate(int a, int b, MathOperation op) {
        return op.execute(a, b);
    }

    public static void main(String[] args) {
        Lamda lamda = new Lamda();
        MathOperation addition = (a, b) -> (a + b);
        MathOperation substract = (a, b) -> (a - b);

        System.out.println(lamda.calculate(4, 5, addition));
        System.out.println(lamda.calculate(4, 5, substract));
    }

Thursday, February 20, 2014

Add words to file in linux

Following Linux commands can be used to add words to file.

1) open file in Linux vi editor
2) ESC and type following command as you referred

:/s/^/0/g
add zero(0) to in front of each line
^ defines the start of the line

:/s/$/0/g
add zero(0) to end of each line 
$ defines the end of the line

:/s/718/0/g
replace "718" with zero(0)

Wednesday, January 1, 2014

Update MySQL table appending text

Following SQL command can be used to update MySQL table with appending text "text" for field "field".

update table set field=concat('text',field);