Thursday, 31 August 2017

How to convert Date and Time between Timezone in Java?

TimeZone represents a time zone offset, and also figures out daylight savings.

Typically, we can get a TimeZone using getDefault() method which creates a TimeZone based on the time zone where the application is running. 

For example, if the application is running in India, getDefault() method creates a TimeZone object based on Indian Standard Time (IST).

We can also get a TimeZone using getTimeZone along with a time zone ID. For instance, the time zone ID for the Indian Standard Time (IST) zone is Asia/Calcutta. So, we can get a IST TimeZone object with:

TimeZone timezone = TimeZone.getTimeZone("Asia/Calcutta");


Lets look into the code -


package com.anjan.timezone;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TimeZoneDemo {

public static String convertDateToTimeZone(Date date, TimeZone timeZoneID, String dateFmt) {

SimpleDateFormat sdf = new SimpleDateFormat(dateFmt);
sdf.setTimeZone(timeZoneID);

return sdf.format(date);

}

public static void main(String arg[]) {

Date date = new Date();

String dt = convertDateToTimeZone(date, TimeZone.getTimeZone("Asia/Calcutta"), "dd-MM-YYYY HH:mm:ss");

System.out.println("Date in Asia/Calcutta : "+dt);
dt = convertDateToTimeZone(date, TimeZone.getTimeZone("America/Los_Angeles"), "dd-MM-YYYY HH:mm:ss");
System.out.println("Date in America/Los_Angeles : "+dt);

}

}

Output -

Date in Asia/Calcutta : 31-08-2017 15:06:30

Date in America/Los_Angeles : 31-08-2017 02:36:30

Thursday, 17 August 2017

How to Convert StackTrace to String in Java

Stack Trace is a list of method calls from the point when the application was started to the point where the exception was thrown. 

Stack Trace is useful to debug the code and see from where exactly the Exception was originated and root cause of the problem. Stack trace of the exception can be printed to the standard error by calling the public void printStackTrace() method. Consider below given example.


Many times for debugging purposes, we'd like to convert the stack trace to a String so we can log it to our log file.
The following code shows how to do that -

package com.anjan.st;

import java.io.PrintWriter;
import java.io.StringWriter;

public class ConvertSTToString {

public static void main(String args[]) {
try {
int i = 10 / 0;
}catch(Exception e) {
System.out.println("Stack Trace ***\n");
e.printStackTrace();
}
try {
int i = 10 / 0;
}catch(Exception e) {
System.out.println("\nStack Trace as String **** \n"+convertToString(e));
}
}
/*
* This method will convert Stack Trace to String
*/
private static String convertToString(Throwable t) {
String strException = "";
StringWriter stringWriter = new StringWriter();
PrintWriter printWriternew PrintWriter(stringWriter);
t.printStackTrace(printWriter);
strException = stringWriter.toString();
return strException;
}
}

Output -

Stack Trace ***

java.lang.ArithmeticException: / by zero
at com.anjan.st.ConvertSTToString.main(ConvertSTToString.java:11)

Stack Trace as String **** 
java.lang.ArithmeticException: / by zero
at com.anjan.st.ConvertSTToString.main(ConvertSTToString.java:18)

Saturday, 17 June 2017

How to find Subdirectories and Files in folder in Java?

First of all, I am really very sorry as I am unable to post the articles frequently. I'll try to post the tutorials or any technical articles atleast once in a week.

As I was very busy with my work. I came across one situation of finding Sub-directories and Files in a folder. So I thought of sharing the logic of finding the files and folders inside any folder. This problem is very common and we can use File class of Java.


Here inside C:\Anjan, there are two files and one sub-folder/sub-directory. So the problem is to implement the same in Java. Let us see the program -

package com.anjan.demo;

import java.io.File;

import java.io.FilenameFilter;
import java.util.Arrays;

public class DirectoryDemo {

 private static String[] findSubdirectory(String path) {
File file = new File(
path);
String[] listDir = null;
if(
file.isFile()) {
System.out.println("Oops! It is File. Please provide Directory");
} else if (
file.isDirectory()) {
listDir file.list(new FilenameFilter() {
@Override
public boolean accept(File curFile, String name) {
return new File(curFile, name).isDirectory();
}
});
}
return 
listDir;
}


private static String[] findFiles(String path) {
File 
file = new File(path);
String[] 
listDir = null;
if(file.isFile()) {
System.out.println("Oops! It is File. Please provide Directory");
else if (file.isDirectory()) {
listFile = file.list(new FilenameFilter() {
@Override
public 
boolean accept(File curFile, String name) {
return new File(curFilename).isFile();
}
});
}
return listFile;
}

 public static void main(String args[]) {
String path = "C:\\Anjan";
String[] dir = findSubdirectory(path);
System.out.println("SubFolders : "+Arrays.toString(dir));
String[] files = findFiles(path);
System.out.println("Files in Directory : "+Arrays.toString(files));
}
}

Try the above program to see the output.

Thursday, 23 February 2017

How to Troubleshoot Oracle 11g installation in RHEL?

In my previous post, I discussed regarding the installation process of Oracle 11g EE in RHEL machine. But while installation of any product, we may face few issues.

Today i'll be discussing the issues which I faced while installing Oracle 11g DB in RHEL machine.

I am mentioning the issues which I face while installation. You may or may not get these issues. There might be chances that  you might get some different issues as well.

Lets discuss the issues one by one.

Issue 1 : After modification, the machine got slow

Solution - There might be different cases for the above issue. But for me, the issue was in /etc/hosts file one entry was missing. So I added the below entry

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

After installation, both lines should be there, but there might be chances that the second line is not there. If second line is not there, then add the second line. This will resolve the issue for slow down of system.

Issue 2 - While installation or executing the installer, you might get 

[INS-35172] Target database memory (3096MB) exceeds the systems available shared memory ({0} MB) solution

Solution -

For the above issue, increase the memory of the tmpfs (temporary file system)

Execute the below commands to allocate memory to tmpfs -

df -h /dev/shm
umount tmpfs
mount -t tmpfs shmfs -o size=4G /dev/shm

df -h /dev/shm

You can allocate memory as per your need. For me I allocated 4GB of memory to tmpfs.

Issue 3 - While installation or executing the installer, you might get 

[FATAL] [INS-13013] Target environment do not meet some mandatory requirements.

   CAUSE: Some of the mandatory prerequisites are not met. See logs for details. /tmp/OraInstall2017-02-23_12-09-38PM/installActions2017-02-23_12-09-38PM.log

Solution - 

In this case, go to the log file and check the issue. For my case, the issue with the UID. While installing DB, Oracle checks whether that multiple users do not exist with the same user id (UID).

I checked the log file and found 


If you are getting the same issue, go to /etc/passwd file and check the UID. If any other entry is present with the same UID, remove the line.

For me I deleted lodadmin:x:0:0:lodadmin:/home/lodadmin:/bin/bash from /etc/passwd file as the same UID is for root:x:0:0:root:/root:/bin/bash

Issue 4 - If firewall is not installed

Solution -

If firewall is not installed in your system, you cannot disable it. So before disabling the firewall, install the firewall and save the iptable by using below commands -

systemctl stop firewalld
systemctl mask firewalld
yum install iptables-services
systemctl enable iptables
systemctl [stop|start|restart] iptables
service iptables save

I hope the above solutions will help you to install Oracle 11g EE DB successfully in your system.

Tuesday, 21 February 2017

How to install Oracle 11g in Redhat Linux in Silent Mode?

Today we'll be installing Oracle 11g Database in Redhat Linux in Silent Mode. If we are using Silent mode installation, we have to use response file as input.

If we are installing DB using Putty or some SSH terminal, then we are not able to access UI for installation. In that case we have to use silent mode using response file.

Lets see how to configure Oracle 11g Enterprise Edition in remote machine.

Before proceeding with the installation, I assume that Java is already installed in machine.

1. Check the System information 


Here the system is 64-bit as it is mentioned as x86_64. As per the system architecture, we will download respective Oracle 11g EE.

3. Go to Downloads tab and Select the Accept Licence Agreement radio button.


4. Once you select the Accept Licence Agreement, you'll get the message like below


5. Go to Oracle Database 11g Release 2 section, and download the respective files as per the system architecture. For our case, we'll download the files under Linux x86-64.

6. Once the download is completed, there will be 2 files 


7. Go to the remote system, and execute the below command to install all the pre-requisites packages for Oracle 11g

            1. wget http://public-yum.oracle.com/public-yum-ol6.repo
            2. yum install oracle-rdbms-server-11gR2-preinstall
Note : If you are getting exception like GPG key retrieval failed: [Errno 14] curl#37 - "Couldn't open file /etc/pki/rpm-gpg/RPM-GPG-KEY-oracle" then in that case execute  yum install --nogpgcheck oracle-rdbms-server-11gR2-preinstall
            3. yum update


8. Once you execute the above command, it will install all the pre-requisite packages and automatically configure the Oracle 11g DB.

9. Edit the file /etc/sysctl.conf and add the following lines if it does not exists –

fs.aio-max-nr = 1048576
fs.file-max = 6815744                              
kernel.shmmni = 4096
# semaphores: semmsl, semmns, semopm, semmni
kernel.sem = 250 32000 100 128
net.ipv4.ip_local_port_range = 9000 65500
net.core.rmem_default=262144
net.core.rmem_max=4194304
net.core.wmem_default=262144
net.core.wmem_max=1048586

If you made some changes to the above file, then execute /sbin/sysctl -p to change kernel parameters.

10. Edit the file /etc/security/limits.conf and add the following lines if it does not exists -

                 oracle              soft    nproc   2047
                 oracle              hard    nproc   16384
                 oracle              soft    nofile  4096
                 oracle              hard    nofile  65536

                 oracle              soft    stack   10240

11. Edit the file /etc/pam.d/login and add the following lines if it does not exists -

                session    required     pam_limits.so

12. Install the below mandatory packages -

            make-3.80  
            binutils-2.15.92.0.2  
            gcc-3.4.6  
            libaio-0.3.105 (x86_64) 
            libaio-0.3.105 (i386) 
            glibc-2.3.4-2.41 (x86_64)
            glibc-2.3.4-2.41 (i386)
            compat-libstdc++-33-3.2.3 (x86_64) 
            compat-libstdc++-33-3.2.3 (i386) 
            elfutils-libelf-0.97  
            elfutils-libelf-devel-0.97  
            glibc-common-2.3.4  
            glibc-devel-2.3.4  
            glibc-headers-2.3.4  
            gcc-c++-3.4.6  
            libaio-devel-0.3.105 (x86_64) 
            libaio-devel-0.3.105 (i386) 
            libgcc-3.4.6 (x86_64) 
            libgcc-3.4.6  
            libstdc++-3.4.6 (x86_64) 
            libstdc++-3.4.6 (i386) 
            libstdc++-devel-3.4.6  
            sysstat-5.0.5  
            unixODBC-2.2.11 (x86_64) 
            unixODBC-2.2.11 (i386) 
            unixODBC-devel-2.2.11 (x86_64) 
            unixODBC-devel-2.2.11 (i386) 
            pdksh-5.2.14  
            expat-1.95.7  

To install a package, execute yum install <package-name> or yum install --nogpgcheck <package-name>

13. Once the packages are installed/updated, create the new user and groups -

          groupadd -g 54321 oinstall
          groupadd -g 54322 dba
          groupadd -g 54323 oper
         useradd -g oinstall -G dba,oper oracle

14. Now set the password oracle user 


15. Set the secure linux to Permissive by editing /etc/selinux/config file -

          SELINUX=permissive

Once the change is complete,restart the server or execute the following command to reflect the changes -

         setenforce Permissive

16. If Linux firewall is enabled, then disable the firewall by issuing the following command -

         service iptables stop
         chkconfig iptables off

17. Create the directories in which Oracle Software will be installed by executing following commands -

        mkdir -p /u01/app/oracle/product/11.2.0.4/db_1
        chown -R oracle:oinstall /u01
        chmod -R 775 /u01

18. Add the following lines at the end of the /home/oracle/.bash_profile file

         # Oracle 11g Settings
        TMP=/tmp; export TMP
        TMPDIR=$TMP; export TMPDIR

       ORACLE_HOSTNAME=<system_ip>; export ORACLE_HOSTNAME
       ORACLE_UNQNAME=<sid>; export ORACLE_UNQNAME
       ORACLE_BASE=/u01/app/oracle; export ORACLE_BASE 
       ORACLE_HOME=$ORACLE_BASE/product/11.2.0.4/db_1; export ORACLE_HOME
       ORACLE_SID=<sid>; export ORACLE_SID
       ORACLE_TERM=xterm; export ORACLE_TERM
       PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin; export PATH
       PATH=$PATH:$ORACLE_HOME/bin; export PATH

       LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib; export LD_LIBRARY_PATH
     CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib; export CLASSPATH

     JAVA_HOME=<java_home_path>; export JAVA_HOME

Change the value of highlighted attributes.

19. Add the entry of hostname in /etc/hosts file.
20. Login to Oracle user in separate terminal
21. Copy installer zip to /home/oracle and extract it
22. Once you unzip both the zip files, all files will be extracted to database folder
23. Give Read, Write and Execute permission to database folder.
24. Check the permission for .oui file in database/install. Give Read, Write and Execute permission to the file if it not there.
25. Download the response file from the below link and save it to /home/oracle 
https://drive.google.com/file/d/0B2sK45HTTdS_ejRNNmhsdWRNQzQ/view

Update the values of following fields -

ORACLE_HOSTNAME, 
oracle.install.db.config.starterdb.globalDBName
oracle.install.db.config.starterdb.SID
oracle.install.db.config.starterdb.password.SYS
oracle.install.db.config.starterdb.password.SYSTEM
oracle.install.db.config.starterdb.password.SYSMAN
oracle.install.db.config.starterdb.password.DBSNMP

26. Now go to /home/oracle/database and execute the runInstaller for installing Oracle 11g 

        ./runInstaller -silent -responseFile /home/oracle/db_new.rsp



Note : Warnings can be ignored. Check the log file from the log location. 

27. Once the installation is completed, you will get few instructions in the terminal. Follow the instructions -



28. To execute the configuration script, you need to login as root user and execute the root.sh from the given location.


29. Once you execute the root.sh, go to the previous terminal and hit enter. After hitting enter, you will get message "Successfully Setup Software." in the terminal.

30. Now verify whether your database is running or not


Here verify the Hostname and SID of Oracle DB.

31. Now test the Database connection using SQL Developer client

32. Enter Username, Password, Hostname, Port and SID to the connection window of SQL Developer and click on Test. 
33. If you get Status as Success, Congratulations, you have successfully installed Oracle 11g EE. If you are not getting Success as Status then troubleshoot as per the error message you are getting.

Friday, 17 February 2017

How to convert simple JSON String to Pretty Print in Java?

Today we'll see how to convert a simple JSON String to Pretty Print using Java and GSON. Sometimes we may be required to indent a simple JSON String for displaying in proper format.

We will be converting the simple JSON String using GSON (GSON is a Java API, developed by Google, used to convert between Java objects and JSON objects). We will be using gson-2.2.2.jar in our example for GSON API.

Now let us see the example -

package com.anjan.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class JSONIndentDemo {

public static String indentJSON(String jsonString) {

JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonString).getAsJsonObject();

Gson gson new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(json);

return prettyJson;

}

public static void main(String args[]) {

String str = "{\"attributes\":[{\"nm\":\"ACCOUNT\",\"lv\":[{\"vt\":\"java.util.Map\",\"cn\":1}],\"vt\":\"java.util.Map\",\"status\":\"SUCCESS\",\"lmd\":13585},{\"nm\":\"PROFILE\",\"lv\":[{\"vt\":\"java.util.Map\",\"cn\":2}],\"vt\":\"java.util.Map\",\"status\":\"SUCCESS\",\"lmd\":41962}]}";
System.out.println("Simple String :\n"+str);
String output = indentJSON(str);
System.out.println("\n\nIndented String :\n"+output);

}

}


Output -

Simple String :
{"attributes":[{"nm":"ACCOUNT","lv":[{"vt":"java.util.Map","cn":1}],"vt":"java.util.Map","status":"SUCCESS","lmd":13585},{"nm":"PROFILE","lv":[{"vt":"java.util.Map","cn":2}],"vt":"java.util.Map","status":"SUCCESS","lmd":41962}]}


Indented String :
{
  "attributes": [
    {
      "nm": "ACCOUNT",
      "lv": [
        {
          "vt": "java.util.Map",
          "cn": 1
        }
      ],
      "vt": "java.util.Map",
      "status": "SUCCESS",
      "lmd": 13585
    },
    {
      "nm": "PROFILE",
      "lv": [
        {
          "vt": "java.util.Map",
          "cn": 2
        }
      ],
      "vt": "java.util.Map",
      "status": "SUCCESS",
      "lmd": 41962
    }
  ]
}