summaryrefslogtreecommitdiffstats
path: root/api/src/main/java/org/openslx/taskmanager/api/Environment.java
blob: 3942ec57768ae3725b550b2b39516dd340bc88ed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package org.openslx.taskmanager.api;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

/**
 * Holds the environment that tasks running a system command *should*
 * use. The environment is read from a config file.
 */
public class Environment
{

	private static final Logger log = Logger.getLogger( Environment.class );

	private static Map<String, String> env = null;

	public static boolean load( String fileName )
	{
		if ( env != null )
			throw new RuntimeException( "Already loaded" );
		try {
			Pattern regex = Pattern.compile( "^([a-zA-Z0-9_]+)(|=.*)$" );
			FileReader fileReader = new FileReader( fileName );
			BufferedReader bufferedReader = new BufferedReader( fileReader );

			Map<String, String> env = new LinkedHashMap<>();
			String line = null;
			while ( ( line = bufferedReader.readLine() ) != null ) {
				Matcher m = regex.matcher( line );
				if ( !m.matches() )
					continue;
				String name = m.group( 1 );
				String value = m.group( 2 );
				if ( value.isEmpty() ) {
					value = System.getenv( name );
				} else {
					value = value.substring( 1 );
				}
				if ( value != null ) {
					env.put(  name, value );
				}
			}

			bufferedReader.close();

			Environment.env = env;
			log.info( "Loaded " + env.size() + " environment lines." );
		} catch ( IOException e ) {
			log.info( "Could not load environment definition from " + fileName + ". Processes might use the same environment as this thread." );
			return false;
		}
		return true;
	}
	
	public static Map<String, String> get()
	{
		return Collections.unmodifiableMap( env );
	}

}