0

I am using testResource to filter data in pom.xml. But instead of printing the data, I am getting back the variable itself as shown in the code. Looks resource filtering is not happening. Can someone please advise me what am I doing wrong here and how to correct it.

pom.xml

<project 

  <properties>
    <local.buildNumber>${local.bhuildNumber}</local.buildNumber>
  </properties>

  <dependencies></dependencies

  <build>
    <testResources>
      <testResource>
        <directory>/src/test/java/resources</directory>
        <filtering>true</filtering>
      </testResource>
    </testResources>

        <plugins></plugins>

  </build>
</project>

global.properties

local.buildNumber=${local.buildNumber}

A.java

public void finish() throws IOException {

        Properties prop = new Properties();
        FileInputStream fileInput = new FileInputStream("src/test/java/resources/global.properties");
        prop.load(fileInput);
        String value = prop.getProperty("local.buildNumber");

        //it prints ${local.buildNumber} though I am expecting 40
        System.out.println(value); }

Project structure:

Project
-src
--main
----java
--test
----java
----resources
------global.properties
--pom.xml
--target/
pk786
  • 2,140
  • 3
  • 18
  • 24
  • First you directory layout looks a bit strange..`src/test/resources` and `src/main/resources` and `src/test/java` and `src/main/java` are the correct locations.furthermore the properties file should be put into `src/test/resources` in case you want to have it only for testing. Furthermore don't access the source location go via `getClass().getResourcesAsStream("/global.properties")`... – khmarbaise Apr 24 '20 at 18:24
  • @khmarbaise project structure updated, but yes I will take out the resource folder from java package. – pk786 Apr 24 '20 at 18:42

1 Answers1

1

Config


<build>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
    </build>

And for load file try working with the ClassLoader class:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("global.properties").getFile());
System.out.println(file.getAbsolutePath());
CodeScale
  • 3,046
  • 1
  • 12
  • 20
  • thanks for answering. There is one disadvantage to this, with each mvn call I have to pass a variable as well. Example, mvn clean -Dlocal.buildNumber=40 or mvn test -Dlocal.buildNumber=40 If I don't pass a variable with each command it throws NullPointerException. Is there a way to avoid it? – pk786 Apr 24 '20 at 21:10
  • yes it is working now but created another issue i just mentioned above – pk786 Apr 24 '20 at 21:24
  • You can set a default value via the default profile ```xml Default true - 1 ``` – CodeScale Apr 24 '20 at 21:25