PGPassFiles { public static PGPass load(String path) throws IOException, IllegalArgumentException { String firstLine = Files.lines(new File(path).toPath()).findFirst().orElseThrow( () -> new IllegalArgumentException("PGPass file is empty.") ); int colonIndex1 = firstLine.indexOf(':'); int colonIndex2 = firstLine.indexOf(':', colonIndex1 + 1); int colonIndex3 = firstLine.indexOf(':', colonIndex2 + 1); int colonIndex4 = firstLine.indexOf(':', colonIndex3 + 1); if (colonIndex4 == -1) { throw new IllegalArgumentException("Could not parse the PGPass file."); } try { return new PGPassFiles.PGPass( firstLine.substring(0, colonIndex1), Integer.valueOf(firstLine.substring(colonIndex1 + 1, colonIndex2)), firstLine.substring(colonIndex2 + 1, colonIndex3), firstLine.substring(colonIndex3 + 1, colonIndex4), firstLine.substring(colonIndex4 + 1) ); } catch (NumberFormatException e) { throw new IllegalArgumentException("Could not parse PGPass file.", e); } } private  PGPassFiles(); static PGPass load(String path);  }
@Test public void shouldLoadValidPGPassFile() throws IOException { File pgPassFile = File.createTempFile("mdms", "pgpass"); pgPassFile.deleteOnExit(); Files.write( pgPassFile.toPath(), Collections.singleton("myhost:5432:mydb:user:pw"), StandardOpenOption.WRITE ); PGPassFiles.PGPass pgpass = PGPassFiles.load(pgPassFile.getAbsolutePath()); Assert.assertEquals("myhost", pgpass.hostname); Assert.assertEquals(5432, pgpass.port); Assert.assertEquals("mydb", pgpass.database); Assert.assertEquals("user", pgpass.username); Assert.assertEquals("pw", pgpass.password); }
@Test public void shouldSupportPasswordsWithColon() throws IOException { File pgPassFile = File.createTempFile("mdms", "pgpass"); pgPassFile.deleteOnExit(); Files.write( pgPassFile.toPath(), Collections.singleton("myhost:5432:mydb:user:%:%:%::%"), StandardOpenOption.WRITE ); PGPassFiles.PGPass pgpass = PGPassFiles.load(pgPassFile.getAbsolutePath()); Assert.assertEquals("myhost", pgpass.hostname); Assert.assertEquals(5432, pgpass.port); Assert.assertEquals("mydb", pgpass.database); Assert.assertEquals("user", pgpass.username); Assert.assertEquals("%:%:%::%", pgpass.password); }
@Test public void shouldLoadValidPGPassFileWithSecondLine() throws IOException { File pgPassFile = File.createTempFile("mdms", "pgpass"); pgPassFile.deleteOnExit(); Files.write( pgPassFile.toPath(), Arrays.asList("myhost:5432:mydb:user:pw", "rubbish"), StandardOpenOption.WRITE ); PGPassFiles.PGPass pgpass = PGPassFiles.load(pgPassFile.getAbsolutePath()); Assert.assertEquals("myhost", pgpass.hostname); Assert.assertEquals(5432, pgpass.port); Assert.assertEquals("mydb", pgpass.database); Assert.assertEquals("user", pgpass.username); Assert.assertEquals("pw", pgpass.password); }