How to extract properties from Ant file (build.xml) into Java code - java

Once the build.xml file is executed, I want to check some properties in the build.xml to handle some errors in my Java code.
For infos, my Ant file (build.xml) is executed this way (not all the code is present):
ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null,
ITaskLauncherConstants.LAUNCHER_NAME);
/* Configure the ILaunchConfiguration (not all setAttribute calls are presents) :*/
workingCopy.setAttribute(IExternalToolConstants.ATTR_LOCATION, "build.xml");
/* Launch the task, where monitor is a IProgressMonitor */
ILaunch lc = workingCopy.launch(ILaunchManager.RUN_MODE, monitor);
And in my build.xml file I have some properties :
<!-- In Ant File -->
<property name="fail.message" value="true" />
Is it possible to check the content of the property in Java code ? Something like :
/* In Java code */
lc.getProperty("fail.message");
Of course, this would mean that the class would "record" the build.xml properties.
Same question has been asked 6 months ago, but the answer is not working (I tried):
How to set a property in java code using build.xml
Thanks for any suggestion.

A simple approach would be using echoproperties task in your ant buildscript, means writing all or desired (via echoproperties attribute prefix) properties to a file and load that file in java afterwards.
From ant manual echoproperties, attribute destfile :
If specified, the value indicates the name of the file to send the
output of the statement to. The generated output file is compatible
for loading by any Java application as a property file. If not
specified, then the output will go to the Apache Ant log.
<echoproperties prefix="fail" destfile="what/ever/foo.properties"/>

Related

Java : How to modify config.properties in runtime?

I have a key which has a value.
autoFixBasePath=C:/myTest
I would like the autoFixBasePath to be appended to some of the keys declared down:
So I am trying to set the value of autoFixBasePath at the start and then modify the config file :
try {
PropertiesConfiguration config = new PropertiesConfiguration("config.properties");
config.setProperty("autoFixBasePath", args[2]);
config.save();
}catch (Exception exception){
}
This works locally, but when using maven assembly plugin, I have put the config file inside jar, there it fails.
How can I do this?
Read the properties file from, for example, %USER_PROFILE%\AppData\Local\YourApp\config.properties (on Windows) or ~/.yourapp/config.properties (on Unix). If that file does not exist at app startup, copy the default settings file from within your JAR to the location named above.
(Although I question how good your approach is. Users of command line tools generally expect that the tool will default to a certain behaviour, and that any command line parameters passed to it will only take effect on that single invocation of the tool. But hey, that's your choice.)
You could also use the Preferences API, documented here: https://docs.oracle.com/javase/8/docs/technotes/guides/preferences/overview.html - which takes care of OS-specific paths and changes at runtime in a way that Properties do not (because those are intended to be passed to the program at startup, and to be immutable from there on.)

Micronaut PropertySource for multiple configuration files

I have a micronaut project where I want to have an unnversioned configuration file for private data (like database connections and so on)
This information have to be loaded through #Property annotation, but since there will be more than one .yml (there will also be at least an application.yml) y want to be able to provide file's path to #Properties to be able to differentiate where to look for property.
Since it's my first micronaut project I'm a bit lost with this stuff but taking springboot as an example, what I want to do is something like:
#PropertySource("classpath:configprops.properties")
But after reading micronaut documentation(https://docs.micronaut.io/latest/guide/index.html#configurationProperties) I found myself unable to do this (except from something like just reading the plain file which I guess would not be micronaut compliant)
I do it by passing jvm arguments.
For example, If I am running it on my local machine using gradle:run, I add following to build.grade
run.jvmArgs('-Dmicronaut.environments=dev', "-Dmicronaut.config.files=${System.getProperty("user.home")}/auth-config.groovy")
For my jar deployment, I have made a deploy.sh file as follows :
#!/bin/bash
fuser -k 8181/tcp
nohup java -Xmx512m -Dmicronaut.environments=staging -Dmicronaut.config.files=<path-to-config>/config.groovy -jar application-0.1-all.jar > application.log 2>&1 &
Also note that I am passing different environment names, this helps you to include development environment config directly in code if you want.
Like
application-[environment_name].groovy
application-[environment_name].yml
application-[environment_name].properties
This will help new contributors on your project to speedup the process project setup, I generally also include note in my application-dev.groovy file
DEVELOPER NOTE:
***** DO NOT COMMIT ANY CHANGE IN THIS FILE IF YOU MAKE ANY
*******************************************************
***** CREATE <config.groovy> file in your <HOME> folder and copy paste content of this file
***** Override properties as required
*******************************************************

IntelliJ IDEA - can I have automatically incremented build (version) number?

Can I set somehow IntelliJ building process to pre-process Java source codes and give me ever incrementing build number? Something like:
int myBuildNumber = INTELLI_J_IDEA_MAGIC_WHICH_WILL_INCREMENT_EVERY_BUILD;
Ok so with hint from AtomHeartFather I got it.
First we need to write an ant xml file. This file will create file where build number will be stored and incremented and then it will look through your source code file ${src}/com/yourPath/Main.java
for variable public static final String BUILD_NUMBER = ".*"; and replace it with current build number
The xml file would look like this:
<project name="MyProject" default="init" basedir=".">
<description>
simple example increment build variable
</description>
<!-- set global properties for this build -->
<property name="src" location="../src"/>
<target name="init">
<echo file="myAntOut.txt">My first ant ${src} ${line.separator}</echo>
<buildnumber/>
<replaceregexp file="${src}/com/yourPath/Main.java"
match="public\s+static\s+final\s+String\s+BUILD_NUMBER\s+=\s+".*";"
replace="public static final String BUILD_NUMBER = "${build.number}";"
byline="true"
/>
</target>
</project>
Then in your intelliJ (I'm using 14.0.3) you click on View->Tool Windows->Ant Build. Then + and browse to your xml file (note that current path used by your xml will be the path to that xml file itself - not inteliJ project - thus you may want to correct the part location="../src" depending on where you store your xml). Than you shall see our target init you can select it and click play button. If it works you shall see BUILD_NUMBER incremented in you source code file Main.java. Now the important trick how to make it automatically: Just right click on init and select Execute on->Before Compilation. Done :)

Access build.xml properties from Java

I have an Android application that is by default built with Ant.
There is build.xml file which loads local.proerties file. I would like to add my custom property (for example Google Maps apiKey) and access it in Java classes - for example in some MainActivity.
How can I achieve it ?
Make your ant script modify the Java source file containing the API key or a properties file bundled with the application, using the replace task or the copy task with a filterset.
Ant provides a target called "sysproperty". Its like a property tag, but it sets the java System.property. So, you can do something like:
<sysproperty name="foo" value="$THE_EXTRA_PROPERTY">
where "THE_EXTRA_PROPERTY" is the extra property that you added to the properties file that gets loaded.

Android - use ant to create build configurations that change configuration values

What I want is a way to have settings that are dependent on build configuration. To give a specific example, my android application connects to a web service. In development, I want the service url to be pulled in from a configurable value. In Test, I want a different value pulled in. In production, yet another value.
So, in code I have something like this:
public class HttpRequestHelper
{
private static String GetServiceUrl(ServiceAction action)
{
return serviceUrl + action.toString();
}
}
By default (when debugging/running through eclipse), I want that url to be http://localhost:1234
In Test I want https://test.mydomain.com
In Production I want https://mydomain.com
I am new to eclipse and ant and it has been a long time since I used java. How do I go about setting this up? What should the build.xml look like? I understand that when I want to build the test/prod versions I will need to use the command line. That's okay. But I don't know how to get this serviceUrl auto-set dependent on the build. I'm not even sure the best place to put this information (a resource, a properties file?). I really want to avoid setting it, building, setting it, building, etc.
As answers mentioned above says, you have to place the URLs in a property file like dev.properties, test.properties, prod.properties etc..
Now only thing that you need to do is making your build intelligent enough to choose a property file depending upon environment.
That can be done by passing a parameter to ANT, something like:
$ ant -file MyBuild.xml -DcurrentEnv=dev (For Development environment)
$ ant -file MyBuild.xml -DcurrentEnv=test (For Test)
$ ant -file MyBuild.xml -DcurrentEnv=prod (For Production)
Inside your build script, this is how you can include your property file:
<target name="jarMe">
<jar destfile="sample.jar" basedir="src" includes="${currentEnv}.properties"/>
</target>
With this in place, whatever name you supply at the time of build, property file with that name will be picked up.
You could try to have a following property file in your build.properties file:
service.url=*
And you could have http://localhost:1234 or https://test.mydomain.com in local.properties for your development and integration testing, and it could be set to https://mydomain.com in default.properties.
By do ing this, you have will get different value for service.url in different build environment. You could use that value to generate a config file, and parse it into your code, or set it to env variable, or just put it into a resource file, and Android will read it for you:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="service-url">##toben_to_be_replaced_during_build_time##</string>
</resources>
I would start by placing the urls into a properties file that you can then place onto the classpath. Make a test and a production properties file. Then depending on the build place the correct file onto the classpath and pull the properties at runtime.
Found a tutorial which goes through all the details of using ant to automate a build system, to create and use build configurations, as well as to build the release project with one command. Here it is: http://www.androidengineer.com/2010/06/using-ant-to-automate-building-android.html
Seems a little long, but it goes through all the steps and details involved.

Categories

Resources