Eclipse CDT: How to save project-wide environment variables programmatically (permanently) - java

I am able to create project-wide environment variables programmatically to Project properties -> C/C++ Build -> Environment page. However when I restart the workspace the environment variables are vanished.
The code I use to add new project-wide environment variables is here:
Global variables:
private ICConfigurationDescription cfgd = null;
private final MultiCfgContributedEnvironment ce = new MultiCfgContributedEnvironment();
Inside method:
ICConfigurationDescription[] cfgs;
cfgs = new ICConfigurationDescription[] {cfgd};
for (ICConfigurationDescription cfg : cfgs) {
ce.addVariable("PKG_CONFIG_LIBDIR", dir,
EnvironmentVariable.ENVVAR_APPEND, SEPARATOR, cfg);
}
I am looking for a way to keep the environment variables on the 'Environment page' after the workspace is restarted.

Another solution, without using the internal classes/APIs, is:
IContributedEnvironment environment = CCorePlugin.getDefault().getBuildEnvironmentManager().getContributedEnvironment();
ICProjectDescription projectDescription = CoreModel.getDefault().getProjectDescription(project, true);
ICConfigurationDescription config = projectDescription.getActiveConfiguration(); // or any other configuration...
// Add variable to project configuration
environment.addVariable("PKG_CONFIG_LIBDIR", dir, IEnvironmentVariable.ENVVAR_APPEND, null, config);
// Update project (description)
CoreModel.getDefault().setProjectDescription(project, projectDescription);
Note that using null instead of config adds the variable to the global/workspace environment.
Also note the different "operation", as defined in IEnvironmentVariable.

I solved my own question. I include the code here if someone else has the same problem.
The solution is to use StorableEnvironment which stores env. vars to XML.
UserDefinedEnvironmentSupplier fUserSupplier = EnvironmentVariableManager.fUserSupplier;
StorableEnvironment vars = fUserSupplier.getWorkspaceEnvironmentCopy();
vars.createVariable("PKG_CONFIG_LIBDIR", dir);
fUserSupplier.setWorkspaceEnvironment(vars);
Be aware though that
org.eclipse.cdt.internal.core.envvar.EnvironmentVariableManager;
org.eclipse.cdt.internal.core.envvar.UserDefinedEnvironmentSupplier;
Are internal API classes and therefore their use is not recommended because their implementation could change and affect the functionality of your code.

Related

How to add environment variable in the resource path in #CSVFileSource java (Parameterize Tests)

I have a usecase where I want to add enviroment varaible in the resources option in CsvFileSouce as shown
#CsvFileSource(resources = "/myresource" + env , numLinesToSkip = 1)
here env is an environment variable and based on this environmnet variable I will go to load the parameterize test.
I don't want to duplicate the function.

Embedded Groovy: How to use static type checking with external variables?

I want to embed Groovy to enable scripting capabilities in my Java application. I want to use static type checking, and in addition I want to pass some additional (global) variables to the script. Here is my configuration:
String script = "println(name)"; // this script was entered by the user
// compiler configuration for static type checking
CompilerConfiguration config = new CompilerConfiguration();
config.addCompilationCustomizers(new ASTTransformationCustomizer(CompileStatic.class));
// compile the script
GroovyShell shell = new GroovyShell(config);
Script script = shell.parse(script);
// later, when we actually need to execute it...
Binding binding = new Binding();
binding.setVariable("name", "John");
script.setBinding(binding);
script.run();
As you can see, the user-provided script uses the global variable name, which is injected via script.setBinding(...). Now there is a problem:
If I declare the variable name in the user script (e.g. String name;), then the binding has no effect because the variable already exists in the script.
If I do not declare the variable in the script, the static type checker will (rightfully) complain that name was not declared.
The question is: how do I solve this? How can I tell the type checker that the script will receive a global variable of a certain type when it is called?
From the doc,
You can use extensions parameter,
config.addCompilationCustomizers(
new ASTTransformationCustomizer(
TypeChecked,
extensions:['robotextension.groovy'])
)
Then add robotextension.groovy to your classpath:
unresolvedVariable { var ->
if ('name'==var.name) {
storeType(var, classNodeFor(String))
handled = true
}
}
Here, we’re telling the compiler that if an unresolved variable is found and that the name of the variable is name, then we can make sure that the type of this variable is String.

How can I access variable resolving of Eclipse run configurations for an Eclipse plugin?

I want to extend the Sysdeo Tomcat Plugin to be capable of resolving variables like you can specify in run configurations for Java applications, e.g. ${workspace_loc}.
I have tried to use this, but the resulting array has no contents:
ResourcesPlugin.getWorkspace().getPathVariableManager().getPathVariableNames();
Using this one does not give me the wanted variables:
JavaCore.getClasspathVariableNames();
Further I search for the code doing the actual variable replacement in a string.
Use the IStringVariableManager to access variables such as ${workspace_loc}. You get the manager with:
IStringVariableManager manager = VariablesPlugin.getDefault().getStringVariableManager();
To process the variables in a string use:
String newString = manager.performStringSubstitution(string);
You can also use the org.eclipse.core.variables.dynamicVariables and org.eclipse.core.variables.valueVariables extension points to add new variables.

Can we read the OS environment variables in Java?

My OS is windows7. I want to read the environment variables in my Java application. I have searched google and many people's answer is to use the method System.getProperty(String name) or System.getenv(String name). But it doesn't seem to work. Through the method, I can read some variable's value that defined in the JVM.
If I set an environment variable named "Config", with value "some config information", how can I get the value in Java?
You should use System.getenv(), for example:
import java.util.Map;
public class EnvMap {
public static void main (String[] args) {
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
}
}
When running from an IDE you can define additional environment variable which will be passed to your Java application. For example in IntelliJ IDEA you can add environment variables in the "Environment variables" field of the run configuration.
Notice (as mentioned in the comment by #vikingsteve) that the JVM, like any other Windows executable, system-level changes to the environment variables are only propagated to the process when it is restarted.
For more information take a look at the "Environment Variables" section of the Java tutorial.
System.getProperty(String name) is intended for getting Java system properties which are not environment variables.
In case anyone is coming here and wondering how to get a specific environment variable without looping through all of your system variables you can use getenv(String name). It returns "the string value of the variable, or null if the variable is not defined in the system environment".
String myEnv = System.getenv("env_name");

How do I set the MONGOHQ_URL environment variable in the run configuration of Netbeans?

We're working on deploying a Java project to Heroku that uses MongoDB. According to the Heroku docs, the DB connection parameters are read from an environment variable, MONGOHQ_URL. When I run the project in Netbeans on my laptop, how do I set this variable?
I tried adding it as a VM option with -DMONGOHQ_URL=... in Run -> Set Project Configuration -> Customize -> Run and as well in Actions -> Run project and Run file via main(), but to no avail. When the program reads it with System.getvar it's not set.
You can set it in your netbeans.conf file. Add the line:
export MONGOHQ_URL=...
There's an example here: http://sunng.info/blog/2009/12/setting-environment-variables-for-netbeans/.
Ok, I figured it out. This may be obvious to Java coders, but I'm not one, so here is what I cobbled together.
String mongo_url = System.getenv("MONGOHQ_URL");
// If env var not set, try reading from Java "system properties"
if (mongo_url == null) {
mongo_url = System.getProperty("MONGOHQ_URL");
}
MongoURI mongoURI = new MongoURI(mongo_url);
this.db = mongoURI.connectDB();
// Only authenticate if username or password provided
if (!"".equals(mongoURI.getUsername()) || mongoURI.getPassword().length > 0) {
Boolean success = this.db.authenticate(mongoURI.getUsername(), mongoURI.getPassword());
if (!success) {
System.out.println("MongoDB Authentication failed");
return;
}
}
this.my_collection = db.getCollection("my_collection");

Categories

Resources