How to set / get windows environment variables through Java code?

How to set / get windows environment variables through Java code?

Below simple program is self explained on how to use set / get the windows environment variables.

    import java.io.*;  
    import java.util.*;  
      
    public class Test  
    {  
        public static void main(String[] args) throws Exception  
        {  
            ProcessBuilder pb = new ProcessBuilder("CMD.exe", "/C", "SET"); // SET prints out the environment variables  
            pb.redirectErrorStream(true);  
            Map env = pb.environment();  
            String path = env.get("Path") + ";C:\\cygwin\\bin";  
            env.put("Path", path);  
            Process process = pb.start();  
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null)  
            {  
                System.out.println(line);  
            }  
        }  
    }  

Read more


Setting windows environment variable through Java code

Setting windows environment variable through Java code...

The below is a simple Java class code which will pass few parameters to a method which get's validated against null and empty conditions and then a process will be started with those values.

Basically one batch script or shell script gets run depending on the OS name found from environment .. it sets two environment variables in the operating system.
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Map;

public class IfixConfig {

 /**
  * @param args
  * @param MYPRODUCT_Home
  * @param WAS_username
  * @param WAS_password
  * @param iFixLocation
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  System.out.println("Starting IFIX configuration");
  String MYPRODUCT_Home = "C:\\Program Files\\XYZ\\MYPRODUCT";
  String WAS_username = "smadmin";
  String WAS_password = "g0vmware";
  String iFixLocation = "C:\\Program Files\\XYZ\\MYPRODUCT\\ui\\ifixes\\3.1.0.0\\0001";
  int result = ifixConfig(MYPRODUCT_Home, WAS_username, WAS_password,
    iFixLocation);
  System.out.println("Result:" + result);

 }

 private static int ifixConfig(String MYPRODUCT_Home, String wAS_username,
   String wAS_password, String iFixLocation) {
  int resultCode = -1;
  try {
   
   System.out.println(MYPRODUCT_Home + wAS_username + wAS_password
     + iFixLocation);
   ProcessBuilder pb = null;
   String postConfigScript = iFixLocation + "/post_install_configure.";
   if (wAS_username != null && !(wAS_username.isEmpty())
     && wAS_password != null && !(wAS_password.isEmpty())) {
    System.out.println("WAS username and passwords provided");
    if (System.getProperty("os.name").startsWith("Windows"))
    {
     postConfigScript = postConfigScript + "bat"; 
      pb = new ProcessBuilder("CMD.exe", "/C", postConfigScript);  
    }
    else 
    {
     postConfigScript = postConfigScript + "sh" ;
     pb = new ProcessBuilder(postConfigScript);
    }
    System.out.println("Post config script:"+postConfigScript);
    pb.directory(new File(iFixLocation));
    pb.redirectErrorStream(true);
    Map env = pb.environment();
    env.put("MYPRODUCT_WAS_USERNAME",wAS_username);
    env.put("MYPRODUCT_WAS_PASSWORD", wAS_password);
    Process process = pb.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
     System.out.println(line);
     if ( line.equals("BUILD SUCCESSFUL")){
      resultCode = 0 ;
     }
    }
    
   } else {
    System.out.println("WAS username and password should not be empty");

   }

  } catch (Exception e) {
   System.out.println(e);
  }
  return resultCode;
 }
}

Read more


Shell Script Tips -1

The below shell scripts are typical example codes which helps us to understand certain frequently used codes.

1. How to get the absolute or full path while calling another shell script from one shell script.

#!/bin/sh
source $(readlink -f "ifix_config.sh") uninstall

The above code snippet calls another shell script by name ifix_config.sh. which is available in the same directory of current script.
Abosolute path will be used with the readlink -f option there. uninstall isa parameter passed to it.

2. How to check how many parameters are passed in to a shell script..
if [ $# != "1" ]; then
    echo "Usage: ifix_config.sh install or ifix_config.sh uninstall"
    exit
else
    ....
    ....
$# represents total number of parameters passed to a shell script when called.
In the above example code if at least one parameter is not passed it throws a message and exits.

3. How to check if a variable is set or not . How to check if a viariale has empty string ?

    LOCALE_CODE=$LANG
    if [ -z $LOCALE_CODE ];
        then JAZZSM_SYSTEM_LOCALE="en_US"
    fi   

In the above example snippet we are setting some value for LOCALE_CODE if in case it is not set for some reason -z option with if condition returns true
so in above example if it( if [ -z $LOCALE_CODE ] ) is true  it will set it to en_US

4. How to get the parent directory path of a file or directory ?

    PresentDir=`dirname $PWD` 

When dirname is given a pathname, it will delete any suffix beginning with the last slash ('/') character and return the result.
For example:

 $ dirname /usr/home/carpetsmoker/dirname.wiki
   /usr/home/carpetsmoker

5. How to get the only filename when absolute path is given ?

Example

    $ basename /home/jsmith/base.wiki
    base.wiki

    $ basename /home/jsmith/base.wiki .wiki
    base

    IFIX_NO=`basename $PWD`
    0001

6.     How to read a properties file in shell script  ?

    # Reading settings.properties to find IM Install location
    IM_HOME=`sed '/^\#/d' $PropertiesFile | grep 'product.install.location'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
    echo IM Install Location is : $IM_HOME
   
    Example :
    $PropertiesFile contents are like below ..
    -------------------------------------------
    #Fri, 01 Mar 2013 02:59:37 -0500

    product.was.user=smadmin
    product.jdbc.lib.path=/opt/IBM/JazzSM/lib/db2
    product.data.location=/var/ibm/InstallationManager
    product.install.location=/opt/IBM/InstallationManager/eclipse
    -------------------------------------------
    The while process is to Scan through the file to get an individual property

    This works well if you just want to read a specific property in a Java-style properties file. Here's what it does:

    * Remove comments (lines that start with '#') >> sed '/^\#/d' myprops.properties
    * Grep for the property >>  grep 'someproperty' 
    * Get the last value using >> tail -n 1
    * Strip off the property name and the '=' (using {{cut -d "=" -f2-}) to handle values with '=' in them).

     sed '/^\#/d' myprops.properties | grep 'someproperty'  | tail -n 1 | cut -d "=" -f2-

    It can also be handy to strip off the leading and trailing blanks with this sed expression:

    s/^[[:space:]]*//;s/[[:space:]]*$//

    Which makes the whole thing look like this:

    sed '/^\#/d' myprops.properties | grep 'someproperty'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'

Reference

7.  How to check file existance before running it ?

[ -f "$SCRIPT_LOCATION/myshellscript.sh" ] && . "$SCRIPT_LOCATION/myshellscript.sh"   

Having quotes for the file path eliminates issues arise out of spaces in the path.

8. How to read input values through shell script ?

    # Ask for WAS credentials
    if [ -z "${JAZZSM_WAS_USERNAME}" ]
    then
      echo -n "${wasUserNamePrompt}: "
      read JAZZSM_WAS_USERNAME
    fi

echo -n "${wasUserNamePrompt}: "     >> it helps to prompt user with particular string before commandline prompt while running shell script, in order to resolve wasUserNamePrompt string we need to run its correspinding properties file before this call .
For example config_messages.sh has text like below , and when it is run before the above command it will resolve this value.

#!/bin/sh

#NLS_MESSAGEFORMAT_NONE
#NLS_ENCODING=UTF-8

wasUserNamePrompt="Enter the Websphere Application Server user name:"

wasPasswordPrompt="Enter the Websphere Application Server password:"

Read more

Translate

Enter your email address:

Buffs ...

Visitors


hits counter
View My StatsCheck Google Page Rank

Add to Google Reader or Homepage

Bookmark and Share

Tags


Powered by WidgetsForFree