How to read Environment Variable in Java.
Hi,
I am trying to read a environment variable $TMP which has a value of /apps/bea/pt847/psoft5/tmp in UNIX.
I have written the following code and getting Null pointer exception when calling the method logmessage. Any help with reading environment variable is appreciated.
public static void logMessage(String message) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
Date now = new Date();
Properties p = null;
try
p = getEnvVars("$TMP");
System.out.println("the current value of TEMP is : " + p.getProperty("$TMP"));
catch (Throwable e) {
e.printStackTrace();
try
BufferedWriter os = new BufferedWriter(new FileWriter("/tmp/pscas_signon_log.txt", true));
os.write(formatter.format(now));
os.write(message);
os.write("\n");
os.write("tmp_env = " + p.getProperty("$TMP"));
os.write("\n");
os.close();
catch(IOException _ex) { }
public static Properties getEnvVars(String env_var) throws Throwable {
Properties envVars = new Properties();
Process p = Runtime.getRuntime().exec(env_var);
BufferedReader br = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
String line = null;
while( (line = br.readLine()) != null ) {
int idx = line.indexOf( '=' );
String key = line.substring( 0, idx );
String value = line.substring( idx+1 );
envVars.setProperty( key, value );
// System.out.println( key + " = " + value );
return envVars;
}
Updated code:
public static void logMessage(String message) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
Date now = new Date();
Properties p = null;
try
p = getEnvVars("$TMP");
System.out.println("the current value of TEMP is : " + System.getProperty("$TMP"));
catch (Throwable e) {
e.printStackTrace();
try
BufferedWriter os = new BufferedWriter(new FileWriter("/tmp/pscas_signon_log.txt", true));
os.write(formatter.format(now));
os.write(message);
os.write("\n");
os.write("tmp_env = " + System.getProperty("$TMP"));
os.write("\n");
os.close();
catch(IOException _ex) { }
public static Properties getEnvVars(String env_var) throws Throwable {
Properties envVars = new Properties();
Process p = Runtime.getRuntime().exec(env_var);
BufferedReader br = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
String line = null;
while( (line = br.readLine()) != null ) {
int idx = line.indexOf( '=' );
String key = line.substring( 0, idx );
String value = line.substring( idx+1 );
envVars.setProperty( key, value );
// System.out.println( key + " = " + value );
return envVars;
}and this is the error message..
java.io.IOException: $TMP: not found
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:72)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Runtime.java:602)
at java.lang.Runtime.exec(Runtime.java:461)
at java.lang.Runtime.exec(Runtime.java:397)
at java.lang.Runtime.exec(Runtime.java:359)
at SimpleCasValidator.getEnvVars(SimpleCasValidator.java:108)
at SimpleCasValidator.logMessage(SimpleCasValidator.java:81)
Similar Messages
-
How to read environment variable
How do I read an environment variable within TS?
I was thinking of calling getenv("VARIABLE_NAME") except it returns a char * and TS only allows Boolean or Numeric return type.
I wonder if LV has any function for doing the same thing.With the new ability in TestStand 4.2 to get the standard output from a command line, you can do this with a call executable step.
Simply call cmd.exe as the executable, and pass it the following expression. Then all you have to do is set Locals.EnvironmentVariableName to the name of the environment variable you want the value of and define where you want the standard output to be stored.
"/C \"echo %"+Locals.EnvironmentVariableName+"%\""
I'm attaching a sequence file that shows this. The attachment is necessarily saved in TestStand 4.2, since it uses a feature introduced in that version.
Josh W.
Certified TestStand Architect
Formerly blue
Attachments:
get env var.seq 6 KB -
How to set environment variables using java program
Hi all
I want to set environment variables on windows 98/200/xp system, such as path and classpath using a java program.
How to do this using a java program.
Any body plz helppppppppp.#1 05-02-2003, 07:38 AM
Goodz13 Join Date: Jan 2002, Posts: 985
Location: Halifax, NS, Canada
Reputation:
Java FAQ's and tutorials
Java FAQ's
Path and ClassPath:
PATH
In Windows 9x you would set it up in the autoexec.bat file
ie.
SET PATH=%PATH%;c:\jdk1.4.2\bin\;
where c:\jdk1.4.2\ is the path where you installed Java.
In Windows 2000 and XP
Right click on My Computer->Properties->Advanced Tab->Environment Variables... Button.
If you see a PATH in System Variables, click that and edit it. If you don't, you will need to create a new System variable.
It should look something like this:
%SystemRoot%\system32;%SystemRoot%;c:\jdk1.4.2\bin\;
Any querry email me to [email protected]
Answer by
Rajasekhar Goli
DS UNICS Infotech -
How to read static variable defined java class from flex?
This is a beginner question. If I use remoteClass to map a java class and a flex class, how can I access a static variable defined in java class from the flex code?
Thanks!Static propeties are by default ignored in the blazeds for serialization. You can try using another global property in the java bean which maps to the value stored in the static property( Hopefully it should work)
eg,
public String instanceValue = ClassName.staticValue;
Ref: http://livedocs.adobe.com/blazeds/1/blazeds_devguide/help.html?content=serialize_data_3.ht ml -
How to use Environment variables in Context Settings
I need to set some Preferences using a Context, and in the value of the preference I need to use a path which may change depending on the OS.
I need to use environment variables or java variables to create the relative path for the value.
Is possible to access env variables from a Context Setting?
Just to give an example, I'm trying to set the M2_REPO variable in the classpath settings in the preferences menu.
to user.home + /.m2/repository
How can I access the user.home from there?Hi Matias,
Sure, you can use substitute-variables command for this purpose.
See the example below:
concat [substitute-variables "${system_property:user.home}" | str] "/.m2/repository"]
Kind regards,
Ulyana. -
How to access environment variables from Oracle Forms
Hi,
Any idea how to use the Environment variables from Oracle Forms.
My basic problem is that from Oracle form I am calling Batch file which calls excel file with a macro.
So i want to check whether the macro was successful or not.
So in my batch file i will set %errorlevel% which I should be able to read from Oracle Forms.
I am able to read the registry from oracle forms, so is there anyway to read environment variable as well?
Thanks!
Avinash.Hello,
Use the TOOL_ENV.Getvar() built-in
Francois -
How To Read RTF file in JAVA? Using iText?
How To Read RTF file in JAVA? Using iText?.....
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.rtf.*;
public class RTF3 {
public static void main(String[] args) {
// System.out.println("This example generate a RTF file name Sample.rtf");
// Create Document object
Document myDoc = new Document();
try {
// Create writer to listen document object
// and directs RTF Stream to the file Sample.rtf
RtfWriter2.getInstance(myDoc, new FileOutputStream("Sample.rtf"));
// open the document object
myDoc.open();
// Create a paragraph
Paragraph p = new Paragraph();
p.add("Helloworld in Rtf file..amazing isn't");
// Add the paragraph to document object
myDoc.add(p);
catch(Exception e) {
System.out.println(e);
//close the document
myDoc.close();
Exception in thread "main" java.lang.NoSuchMethodError: com.lowagie.text.Rectangle.width()F
at com.lowagie.text.rtf.document.RtfPageSetting.rectEquals(RtfPageSetting.java:433)
at com.lowagie.text.rtf.document.RtfPageSetting.guessFormat(RtfPageSetting.java:362)
at com.lowagie.text.rtf.document.RtfPageSetting.setPageSize(RtfPageSetting.java:341)
at com.lowagie.text.rtf.RtfWriter2.setPageSize(RtfWriter2.java:248)
at com.lowagie.text.Document.open(Unknown Source)
at view.RTF3.main(RTF3.java:23)
CAN you HELP me?import com.lowagie.text.Document;
import com.lowagie.text.rtf.parser.RtfParser;
import java.io.FileInputStream;
String inputFile = "sample.rtf";
Document document = new Document();
document.open();
RtfParser parser = new RtfParser(null);
parser.convertRtfDocument(new FileInputStream(inputFile), document); -
How to read url variable javascript problem
How to read the variable of latitude 1.22 and longitude 103.56.
This is my website: 127.0.0.1/1/map2.htm?latitude=1.22&longitude=103.56
function getUrl_Map()
//Get the variables in the URL
var vars = [], hash;
var latitude = getUrlVars()["latitude"];
//To get the second parameter
var longitude= getUrlVars()["longitude"];
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
alert('DEBUG: hashes= ' + hashes);
// read the file http://127.0.0.1/1/map2.htm
// read the file http://127.0.0.1/1/map2.htm? -->hashes
for(var i = 0; i < hashes.length; i++)
hash = hashes.split('=');
//alert('DEBUG: i= ' + i);
//i=0
alert('DEBUG: i= ' + i + 'hash = ' + hash );
vars.push(hash [0]);
vars[hash [0]] = hash [1];by the way you know that 127.0.0.1 is the address you use to get to your own computer right? It's the loopback address. so posting it doesn't really help anybody see the page, if that was what you were hoping.
-
How to read system eventlog using java program in windows?
How to read system eventlog using java program in windows?
is there any java class available to do this ? or any one having sample code for this?
Your friend ZoeHi,
There is no java class for reading event log in windows, so we can do one thing we can use windows system 32 VBS script to read the system log .
The output of this command can be read using java program....
we can use java exec for executing this system32 vbs script.
use the below program and pass the command "eventquery"
plz refer cscript,wscript
import java.io.*;
public class CmdExec {
public static void main(String argv[]) {
try {
String line;
Process p = Runtime.getRuntime().exec("Command");
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
input.close();
catch (Exception err) {
err.printStackTrace();
This sample program will list all the system log information....
Zoe -
How to read system evenlog using java program in windows
How to read system evenlog using java program in windows???
is there any java class available to do this ? or any one having sample code for this?
Your friend ZoeWelcome to the Sun forums.
>
How to read system evenlog using java program in windows???>
JNI. (No.)
>
is there any java class available to do this ? or any one having sample code for this?>You will generally get better help around here if you read the documentation, try some sample code and come back with a specific question (hopefully with an SSCCE included).
>
Your friend Zoe>(raised eyebrow) Thank you for sharing that with us.
Note also that one '?' denotes a question, while 2 or more generally denotes a dweeb. -
How to read a variable within a VC code. I am using BADI based VC code.
How to read a variable within a VC code. I am using BADI based VC code.
Lets say I have a variable for a fiscal period that holds cumulative month.
If user enters 03/2014 in that variable, it will have month starting from Jan till March.
Within VC code I would like to read the last month which is
03/2014 and based on this month I would like to do some calculation on all the records using the last month.
Since VC code runs for one record at a time and there is no way I can store this value.
Is there a way to go about it....any suggestions would be of great help.
Thanks.Any suggestions would be highly appreciated.
Thanks! -
How to set environment variables in WL ?
Hi,
How to set environment variables in WL ?
Thanks,
SriviHi,
You can set the environmet variable in Weblogic by using the below commands
setWLSEnv.cmd/sh ==>Set the CLASSPATH to include the WebLogic Server classes.
Overview of WebLogic Server Domains
or you can use to set the Environment variable along with domain specific varables using the SetDomainEnv.cmd
To run SetDomainEnv.sh in Linux please use
. ./setDomainEnv.sh it require two dots (Dont miss it )
http://docs.oracle.com/cd/E28280_01/web.1111/e13749/weblogicserver.htm#ADMRF205
Hope it helps -
How to set environment variable ORACLE_HOME ?
Hi
I trying to install SAP Solution manager 4.0 SR3:
OS: Linux RHEL4u4
DB: Oracle
SAPinst now stops the installation.
To proceed with the installation, install the Oracle database as follows:
1.Log in as user orassm.
2.Set the DISPLAY variable.
3.Change to directory /oracle/stage/102_32/database/SAP.
4.Start './RUNINSTALLER'.
After you installed the Oracle database software, proceed with the database instance
installation by choosing 'OK' in this dialog box.
./RUNINSTALLER
oracle_stage is not set (OK)
oracle_base is not set (OK)
oracle_home is not set (OK)
oracle_sid is not set (OK)
oracle_home_name is not set (OK)
oracle_inst_group is not set (OK)
from_location is not set (OK)
tmp_netca_file is not set (OK)
tmp_dbca_file is not set (OK)
Working in /oracle/stage/102_32/database/SAP ...
The environment variable ORACLE_HOME is not set! abort ...
How to set environment variable ORACLE_HOME ?
Regards
Erici
Switch shell to bash:
orassm:x:502:503:SAP Database Administrator:/oracle/SSM:/bin/bash
[root@csp-p-sm00 ~]# su - orassm
[orassm@csp-p-sm00 ~]$
But when try to run ./RUNINSTALL
[orassm@csp-p-sm00 SAP]$ ./RUNINSTALLER
oracle_stage is not set (OK)
oracle_base is not set (OK)
oracle_home is not set (OK)
oracle_sid is not set (OK)
oracle_home_name is not set (OK)
oracle_inst_group is not set (OK)
from_location is not set (OK)
tmp_netca_file is not set (OK)
tmp_dbca_file is not set (OK)
Working in /oracle/stage/102_32/database/SAP ...
The environment variable ORACLE_HOME is not set! abort ...
Additionaly I've post csh.cshrc and csh.login
/etc/cshrc
csh configuration for all shell invocations.
by default, we want this to get set.
Even for non-interactive, non-login shells.
[ "`id -gn`" = "`id -un`" -a `id -u` -gt 99 ]
if $status then
umask 022
else
umask 002
endif
if ($?prompt) then
if ($?tcsh) then
set prompt='[%n@%m %c]$ '
else
set prompt=\[`id -nu`@`hostname -s`\]\$\
endif
endif
if ( $?tcsh ) then
bindkey "^[[3~" delete-char
endif
setenv MAIL "/var/spool/mail/$USER"
limit coredumpsize 0
if ( -d /etc/profile.d ) then
set nonomatch
foreach i ( /etc/profile.d/*.csh )
if ( -r $i ) then
source $i
endif
end
unset i nonomatch
endif
/etc/csh.login
System wide environment and startup programs, for login setup
if ($?PATH) then
if ( "$" !~ /usr/X11R6/bin ) then
setenv PATH "$:/usr/X11R6/bin"
endif
else
if ( $uid == 0 ) then
setenv PATH "/sbin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin"
else
setenv PATH "/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin"
endif
endif
setenv HOSTNAME `/bin/hostname`
set history=1000
if ( ! -f $HOME/.inputrc ) then
setenv INPUTRC /etc/inputrc
endif
Regards
Eric -
Setting persitent system environment variables using java program
hai,
Iam tryng to write installation for an application,which require to set some persistent system environment variables using java program. I have tried using set command Runtime.getRuntime().exec("cmd /c set blah blah "),but this applies only to that particular DOS promt only,i presume.And this is not perisistent.please do help.
BijuThe solution I proposed worked only on Windows XP/2003.
The following solution will work on Windows NT/2000/XP/2003 with JDK 1.2+.
1- Download the [url http://www.gjt.org/download/time/java/jnireg/registry-3.1.3.zip]JNIRegistry zipped archive.
2- Open the registry-3.1.3.zip file and extract in the folder of your choice ( Eg. c:\setenv ) only the 2 first files (when sorted by path): ICE_JNIRegistry.dll and registry.jar.
You don't need to keep the folder tree in the extraction.
3- Create the following SetEnv.java file in the same folder ( Eg. c:\setenv ).
import com.ice.jni.registry.Registry;
import com.ice.jni.registry.RegistryKey;
import com.ice.jni.registry.RegStringValue;
import com.ice.jni.registry.RegistryValue;
public class SetEnv
static final String REG_HKLM_SUBKEY_NAME = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
public static void main(String[] args)
throws Exception
new SetEnv().exec(args);
void exec(String[] args)
throws Exception
if (args.length != 2)
throw new IllegalArgumentException("\n\nUsage: java SetEnv {varName} {varValue}\n\n");
String varName = args[0];
String varValue = args[1];
RegistryKey key = null;
RegStringValue value;
try
key = Registry.HKEY_LOCAL_MACHINE.openSubKey(REG_HKLM_SUBKEY_NAME, RegistryKey.ACCESS_ALL);
value = new RegStringValue(key, varName, RegistryValue.REG_EXPAND_SZ);
value.setData(varValue);
key.setValue(value);
key.flushKey();
finally
try { key.closeKey(); }
catch (Exception e) {}
}4- Compile it.
javac -classpath .;registry.jar SetEnv.java
5- Run it. varName and varValue are strings of your choice.
java -classpath .;registry.jar -Djava.library.path=. SetEnv varName varValue -
Setting windows environment variables from Java program
Is there any way to set environment variables from Java program in Windows? Any help is appreciated.
Here is my situation:
I need to decrypt an encrypted Oracle user password in a batch file which will be used while running a sql script with sqlplus. I was planning to have bat file which will call a Java program decrypt the password and set it as an env variable in windows which will be available while calling sqlplus.
thanksRuntime.exec has a lot of overloadings. Two of them
allows you to specify the environment variables.
exec
public Process exec(String[] cmdarray,
String[] envp,
File dir)
throws IOExceptionExecutes the specified command and
arguments in a separate process with the specified
environment and working directory.
cmdarray - array containing the command to call and
its arguments.
envp - array of strings, each element of which has
environment variable settings in format name=value.
dir - the working directory of the subprocess, or null
if the subprocess should inherit the working directory
of the current process.
I had this sample program:
public class SetVarExample {
public static void main (String[] args) throws Exception {
String[] cmd_env= new String[] {"password="+"ABCD","Path=C:\\Sun\\AppServer\\jdk\\bin"};
String cmd = "cmd /c SET ";
Runtime.getRuntime().exec(cmd,cmd_env);
System.out.println( "Finish ...." );
I tried it in a command prompt. But looks like when the program exits, it's a whole new process and so it does not retain the env variables set in the java program.
Any suggestions? Am I doing it worng?
thanks
Maybe you are looking for
-
Preflight color image resolution warning
I've designed a book cover in ID CS3 for a client who wants to publish her book with Createspace.com. I've exported the file to pdf per Createspace's speciifcation. When doing a preflight in Acrobat 9, using a profile provided by Createspace, I get a
-
I have used RunState.ProcessModelClient.Data.Seq["MainSequence"].Locals.MyVariable to set Locals variables in client sequences running in a sequential model but it doesn't seem to work with the batch model. Using a breakpoint I found that RunState.Pr
-
E71 compatibility with MAC!!
I bought today an E71 convinced that it was compatible with mac...would it be possible to know if software will be developed to make it compatible with isync? Thankshttp://discussions.europe.nokia.com/discussions/board/post?board.id=communicators#
-
Direct ethernet bridging g4 and macbook
well i posted this on the using tiger forum and got no replies, now i see the networking forum here... i want to connect my old 2nd gen g4 to the macbook via ethernet. I have a x over cable and it looks like i may need it as i believe the g4 to be ov
-
Is the digital waveform graph supported in Measurement Studio?
I have an application that could really use the LV-style digital waveform graph in Visual C++. Are there any plans to support the digital graph in Measurement Studio? Thanks, Bob