Search code examples
javawindowsseleniumcucumber

Java location path regex split


I've "inherited" existing Java Selenium & Cucumber framework which was written mostly for OS usage. I'm using Windows and I'm trying to fix & run it on Windows.

My first problem is specifing corrent file path, this is how it was written for OS:

private String getProjectName(Scenario scenario) {
    return Arrays.asList(scenario.getUri().getPath().replace(System.getProperty("user.dir"), "").split("/")).get(5);
}

Error which I'm receiving is: java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 1

As for Windows we're using backlashes I've tried switching "/" into "" but as error appears (+ after my investigations) I've tried with "\\\\" but actually error remains the same as above.

I'm aware that providing only portion of my code and it may be hard but for the first glance can you tell me:

  • If that method may work on Windows or this should be completely refactored?
  • Is System.getProperty("user.dir") correct solution?
  • How to correctly pass backslashes?
  • Why they're taking .get(5)?

Solution

  • I can guess:

    This method is taking the project name that is likely the name of a certain folder in the folder structure where scenario file located.

    This is why they took 5th element. Because on the 5th level there was the folder which represented the project.

    The used approach look very arguable. At least because there are some redundent steps like converting to list.

    Now. How would you go:

    The proper way is to use java.nio.file.Path (starts from Java 7) that takes care of differnt OS-specific things.

    So your code might look like:

    private String getProjectName(Scenario scenario) {
      return Path.of(scenario.getUri()).getName(5)
    }
    

    P.S. - of course you have to change 5 to catch a proper position of the required folder in your structure.