target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void shouldReturnAllTokens1() { final String input = "___${____${TOKEN_1}__}___${TOKEN_2}__"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(2, tokens.size()); assertEquals("TOKEN_1", tokens.get(0)); assertEquals("TOKEN_2", tokens.get(1)); } | public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } |
@Test public void shouldReturnAllTokens2() { final String input = "___${____${TOKEN_1__}___${TOKEN_2}__"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(2, tokens.size()); assertEquals("TOKEN_1__", tokens.get(0)); assertEquals("TOKEN_2", tokens.get(1)); } | public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } |
@Test public void shouldReturnAllTokens3() { final String input = "___${____${TOKEN_2}_}___${TOKEN_2}__"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(2, tokens.size()); assertEquals("TOKEN_2", tokens.get(0)); assertEquals("TOKEN_2", tokens.get(1)); } | public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } |
@Test public void shouldReturnAllTokens4() { final String input = "___${____${TOKEN_1}_${TOKEN_2}_}___${TOKEN_2}_${${TOKEN_3}}_"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter, false); assertEquals(4, tokens.size()); assertEquals("TOKEN_1", tokens.get(0)); assertEquals("TOKEN_2", tokens.get(1)); assertEquals("TOKEN_2", tokens.get(2)); assertEquals("TOKEN_3", tokens.get(3)); } | public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } |
@Test public void shouldReturnUniqueTokens1() { final String input = "___${____${TOKEN_2}_}___${TOKEN_2}__"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter, true); assertEquals(1, tokens.size()); assertEquals("TOKEN_2", tokens.get(0)); } | public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } |
@Test public void shouldReturnUniqueTokens2() { final String input = "___${____${TOKEN_1}_${TOKEN_2}_}___${TOKEN_2}_${${TOKEN_3}}_"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter, true); assertEquals(3, tokens.size()); assertEquals("TOKEN_1", tokens.get(0)); assertEquals("TOKEN_2", tokens.get(1)); assertEquals("TOKEN_3", tokens.get(2)); } | public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } | StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); } |
@Test public void shouldReadFileFromRelativePath() throws IOException { try (InputStream is = FileUtils.getStream("./src/test/files/test1.properties")) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("keyOne")); } } | public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); static final String FILE_PATH_PREFIX; static final String CLASSPATH_PREFIX; } |
@Test public void shouldReadFileFromRelativePathWithPrefix() throws IOException { try (InputStream is = FileUtils.getStream("file:src/test/files/test1.properties")) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("keyOne")); } } | public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); static final String FILE_PATH_PREFIX; static final String CLASSPATH_PREFIX; } |
@Test public void shouldReadFileFromAbsolutePath() throws IOException { final String absolutePath = new File("src/test/files/test1.properties").getAbsolutePath(); try (InputStream is = FileUtils.getStream(absolutePath)) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("keyOne")); } } | public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); static final String FILE_PATH_PREFIX; static final String CLASSPATH_PREFIX; } |
@Test public void shouldReturnEmptyOptionalInteger() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("key.two", "value.two"); final Properlty prop = buildProperlty(properties); assertFalse(prop.getInt("key.three").isPresent()); } | public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } |
@Test public void shouldReadFileFromAbsolutePathWithPrefix() throws IOException { final String absolutePath = new File("src/test/files/test1.properties").getAbsolutePath(); try (InputStream is = FileUtils.getStream("file:" + absolutePath)) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("keyOne")); } } | public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); static final String FILE_PATH_PREFIX; static final String CLASSPATH_PREFIX; } |
@Test public void shouldReadFileFromClasspath() throws IOException { try (InputStream is = FileUtils.getStream("classpath:resource1.properties")) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("name=resource1")); } } | public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); static final String FILE_PATH_PREFIX; static final String CLASSPATH_PREFIX; } |
@Test public void shouldReadFileFromClasspathFolder() throws IOException { try (InputStream is = FileUtils.getStream("classpath:./inner/resource2.properties")) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("name=resource2")); } } | public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); static final String FILE_PATH_PREFIX; static final String CLASSPATH_PREFIX; } |
@Test public void shouldThrowFileNotFoundExceptionForMissingFileFromClasspath() throws IOException { try { FileUtils.getStream("classpath:NOT_EXISTING_FILE"); fail("Should have thrown a FileNotFoundException"); } catch (final FileNotFoundException e) { assertTrue(e.getMessage().contains("NOT_EXISTING_FILE")); } } | public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); static final String FILE_PATH_PREFIX; static final String CLASSPATH_PREFIX; } |
@Test public void shouldThrowFileNotFoundExceptionForMissingFile() throws IOException { try { FileUtils.getStream("file:NOT_EXISTING_FILE"); fail("Should have thrown a FileNotFoundException"); } catch (final FileNotFoundException e) { assertTrue(e.getMessage().contains("NOT_EXISTING_FILE")); } } | public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); } | FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); static final String FILE_PATH_PREFIX; static final String CLASSPATH_PREFIX; } |
@Test public void shouldReadSystemProperties() { final String key = UUID.randomUUID().toString(); final String value = UUID.randomUUID().toString(); System.setProperty(key, value); final Map<String, PropertyValue> systemProperties = new SystemPropertiesReader().read(); assertNotNull(systemProperties); assertTrue(systemProperties.containsKey(key)); assertEquals(value, systemProperties.get(key).getValue()); } | @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> properties = new HashMap<>(); final Properties systemProperties = System.getProperties(); for(final Entry<Object, Object> x : systemProperties.entrySet()) { properties.put((String)x.getKey(), PropertyValue.of((String)x.getValue())); } return properties; } | SystemPropertiesReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> properties = new HashMap<>(); final Properties systemProperties = System.getProperties(); for(final Entry<Object, Object> x : systemProperties.entrySet()) { properties.put((String)x.getKey(), PropertyValue.of((String)x.getValue())); } return properties; } } | SystemPropertiesReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> properties = new HashMap<>(); final Properties systemProperties = System.getProperties(); for(final Entry<Object, Object> x : systemProperties.entrySet()) { properties.put((String)x.getKey(), PropertyValue.of((String)x.getValue())); } return properties; } } | SystemPropertiesReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> properties = new HashMap<>(); final Properties systemProperties = System.getProperties(); for(final Entry<Object, Object> x : systemProperties.entrySet()) { properties.put((String)x.getKey(), PropertyValue.of((String)x.getValue())); } return properties; } @Override Map<String, PropertyValue> read(); } | SystemPropertiesReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> properties = new HashMap<>(); final Properties systemProperties = System.getProperties(); for(final Entry<Object, Object> x : systemProperties.entrySet()) { properties.put((String)x.getKey(), PropertyValue.of((String)x.getValue())); } return properties; } @Override Map<String, PropertyValue> read(); } |
@Test public void shouldReturnUnresolvableEnvironmentVariables() { final Map<String, PropertyValue> var = new EnvironmentVariablesReader().read(); assertNotNull(var); assertFalse(var.isEmpty()); var.forEach((key, value) -> { assertFalse(value.isResolvable()); }); } | @Override public Map<String, PropertyValue> read() { return envSupplier.get().entrySet().stream() .collect(Collectors.toMap( e -> getKey(e.getKey()), e -> PropertyValue.of(e.getValue()).resolvable(false) )); } | EnvironmentVariablesReader implements Reader { @Override public Map<String, PropertyValue> read() { return envSupplier.get().entrySet().stream() .collect(Collectors.toMap( e -> getKey(e.getKey()), e -> PropertyValue.of(e.getValue()).resolvable(false) )); } } | EnvironmentVariablesReader implements Reader { @Override public Map<String, PropertyValue> read() { return envSupplier.get().entrySet().stream() .collect(Collectors.toMap( e -> getKey(e.getKey()), e -> PropertyValue.of(e.getValue()).resolvable(false) )); } EnvironmentVariablesReader(); EnvironmentVariablesReader(Supplier<Map<String, String>> envSupplier); } | EnvironmentVariablesReader implements Reader { @Override public Map<String, PropertyValue> read() { return envSupplier.get().entrySet().stream() .collect(Collectors.toMap( e -> getKey(e.getKey()), e -> PropertyValue.of(e.getValue()).resolvable(false) )); } EnvironmentVariablesReader(); EnvironmentVariablesReader(Supplier<Map<String, String>> envSupplier); @Override Map<String, PropertyValue> read(); EnvironmentVariablesReader replace(String from, String to); } | EnvironmentVariablesReader implements Reader { @Override public Map<String, PropertyValue> read() { return envSupplier.get().entrySet().stream() .collect(Collectors.toMap( e -> getKey(e.getKey()), e -> PropertyValue.of(e.getValue()).resolvable(false) )); } EnvironmentVariablesReader(); EnvironmentVariablesReader(Supplier<Map<String, String>> envSupplier); @Override Map<String, PropertyValue> read(); EnvironmentVariablesReader replace(String from, String to); } |
@Test public void shouldReturnEmptyMapIfEmpty() { final PriorityQueueDecoratorReader queue = new PriorityQueueDecoratorReader(); final Map<String, PropertyValue> prop = queue.read(); assertNotNull(prop); assertTrue(prop.isEmpty()); } | @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> result = new LinkedHashMap<>(); readersMap.forEach((priority, readers) -> { readers.forEach(reader -> { final Map<String, PropertyValue> entries = reader.read(); result.putAll(entries); }); }) ; return result; } | PriorityQueueDecoratorReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> result = new LinkedHashMap<>(); readersMap.forEach((priority, readers) -> { readers.forEach(reader -> { final Map<String, PropertyValue> entries = reader.read(); result.putAll(entries); }); }) ; return result; } } | PriorityQueueDecoratorReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> result = new LinkedHashMap<>(); readersMap.forEach((priority, readers) -> { readers.forEach(reader -> { final Map<String, PropertyValue> entries = reader.read(); result.putAll(entries); }); }) ; return result; } } | PriorityQueueDecoratorReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> result = new LinkedHashMap<>(); readersMap.forEach((priority, readers) -> { readers.forEach(reader -> { final Map<String, PropertyValue> entries = reader.read(); result.putAll(entries); }); }) ; return result; } @Override Map<String, PropertyValue> read(); void add(Reader reader, int priority); } | PriorityQueueDecoratorReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> result = new LinkedHashMap<>(); readersMap.forEach((priority, readers) -> { readers.forEach(reader -> { final Map<String, PropertyValue> entries = reader.read(); result.putAll(entries); }); }) ; return result; } @Override Map<String, PropertyValue> read(); void add(Reader reader, int priority); } |
@Test public void shouldReturnDefaultInteger() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "1"); final Properlty prop = buildProperlty(properties); assertEquals(1, prop.getInt("key.one", 10)); assertEquals(10, prop.getInt("key.two", 10)); } | public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } |
@Test(expected=NumberFormatException.class) public void shouldThrowExceptionParsingWrongInteger() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "not a number"); final Properlty prop = buildProperlty(properties); prop.getInt("key.one"); } | public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } | Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } |
@Test public void shouldReturnEmptyOptionalBoolean() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("key.two", "value.two"); final Properlty prop = buildProperlty(properties); assertFalse(prop.getBoolean("key.three").isPresent()); } | public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } |
@Test public void shouldReturnDefaultBoolean() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "true"); final Properlty prop = buildProperlty(properties); assertTrue(prop.getBoolean("key.one", false)); assertFalse(prop.getBoolean("key.two", false)); assertTrue(prop.getBoolean("key.two", true)); } | public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } |
@Test(expected=RuntimeException.class) public void shouldThrowExceptionParsingWrongBoolean() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "not a bool"); final Properlty prop = buildProperlty(properties); prop.getBoolean("key.one"); } | public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } | Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); } |
@Test public void testParse_success() { List<String> keyValueStrings = Arrays.asList( "SOME_VARIABLE_1=SOME_VALUE_1", "SOME_VARIABLE_2=SOME_VALUE_2", "SOME_VARIABLE_3="); Map<String, String> expectedEnvironment = new HashMap<>(); expectedEnvironment.put("SOME_VARIABLE_1", "SOME_VALUE_1"); expectedEnvironment.put("SOME_VARIABLE_2", "SOME_VALUE_2"); expectedEnvironment.put("SOME_VARIABLE_3", ""); Map<String, String> environment = MinikubeDockerEnvParser.parse(keyValueStrings); Assert.assertEquals(expectedEnvironment, environment); } | public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } private MinikubeDockerEnvParser(); } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } private MinikubeDockerEnvParser(); static Map<String, String> parse(List<String> keyValueStrings); } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } private MinikubeDockerEnvParser(); static Map<String, String> parse(List<String> keyValueStrings); } |
@Test public void testBuildMinikubeCommand() { spyAbstractMinikubeMojo.setMinikube("path/to/minikube"); spyAbstractMinikubeMojo.setFlags(ImmutableList.of("someFlag1", "someFlag2")); Mockito.when(spyAbstractMinikubeMojo.getCommand()).thenReturn("somecommand"); Mockito.when(spyAbstractMinikubeMojo.getMoreFlags()) .thenReturn(ImmutableList.of("moreFlag1", "moreFlag2")); Assert.assertEquals( Arrays.asList( "path/to/minikube", "somecommand", "someFlag1", "someFlag2", "moreFlag1", "moreFlag2"), spyAbstractMinikubeMojo.buildMinikubeCommand()); } | @VisibleForTesting List<String> buildMinikubeCommand() { List<String> execString = new ArrayList<>(); execString.add(minikube); execString.add(getCommand()); if (flags != null) { execString.addAll(flags); } execString.addAll(getMoreFlags()); return execString; } | AbstractMinikubeMojo extends AbstractMojo { @VisibleForTesting List<String> buildMinikubeCommand() { List<String> execString = new ArrayList<>(); execString.add(minikube); execString.add(getCommand()); if (flags != null) { execString.addAll(flags); } execString.addAll(getMoreFlags()); return execString; } } | AbstractMinikubeMojo extends AbstractMojo { @VisibleForTesting List<String> buildMinikubeCommand() { List<String> execString = new ArrayList<>(); execString.add(minikube); execString.add(getCommand()); if (flags != null) { execString.addAll(flags); } execString.addAll(getMoreFlags()); return execString; } } | AbstractMinikubeMojo extends AbstractMojo { @VisibleForTesting List<String> buildMinikubeCommand() { List<String> execString = new ArrayList<>(); execString.add(minikube); execString.add(getCommand()); if (flags != null) { execString.addAll(flags); } execString.addAll(getMoreFlags()); return execString; } @Override void execute(); } | AbstractMinikubeMojo extends AbstractMojo { @VisibleForTesting List<String> buildMinikubeCommand() { List<String> execString = new ArrayList<>(); execString.add(minikube); execString.add(getCommand()); if (flags != null) { execString.addAll(flags); } execString.addAll(getMoreFlags()); return execString; } @Override void execute(); } |
@Test public void testExecute() throws IOException, MojoExecutionException, InterruptedException { List<String> minikubeCommand = Arrays.asList("some", "command"); Mockito.doReturn(minikubeCommand).when(spyAbstractMinikubeMojo).buildMinikubeCommand(); spyAbstractMinikubeMojo.setCommandExecutorSupplier(() -> mockCommandExecutor); spyAbstractMinikubeMojo.setMavenBuildLogger(mockMavenBuildLogger); spyAbstractMinikubeMojo.execute(); Mockito.verify(mockCommandExecutor).setLogger(mockMavenBuildLogger); Mockito.verify(mockCommandExecutor).run(minikubeCommand); } | @Override public void execute() throws MojoExecutionException { List<String> minikubeCommand = buildMinikubeCommand(); try { commandExecutorSupplier.get().setLogger(mavenBuildLogger).run(minikubeCommand); } catch (InterruptedException | IOException ex) { throw new MojoExecutionException(getDescription() + " failed", ex); } } | AbstractMinikubeMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { List<String> minikubeCommand = buildMinikubeCommand(); try { commandExecutorSupplier.get().setLogger(mavenBuildLogger).run(minikubeCommand); } catch (InterruptedException | IOException ex) { throw new MojoExecutionException(getDescription() + " failed", ex); } } } | AbstractMinikubeMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { List<String> minikubeCommand = buildMinikubeCommand(); try { commandExecutorSupplier.get().setLogger(mavenBuildLogger).run(minikubeCommand); } catch (InterruptedException | IOException ex) { throw new MojoExecutionException(getDescription() + " failed", ex); } } } | AbstractMinikubeMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { List<String> minikubeCommand = buildMinikubeCommand(); try { commandExecutorSupplier.get().setLogger(mavenBuildLogger).run(minikubeCommand); } catch (InterruptedException | IOException ex) { throw new MojoExecutionException(getDescription() + " failed", ex); } } @Override void execute(); } | AbstractMinikubeMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { List<String> minikubeCommand = buildMinikubeCommand(); try { commandExecutorSupplier.get().setLogger(mavenBuildLogger).run(minikubeCommand); } catch (InterruptedException | IOException ex) { throw new MojoExecutionException(getDescription() + " failed", ex); } } @Override void execute(); } |
@Test public void testRun_success() throws IOException, InterruptedException { setMockProcessOutput(expectedOutput); List<String> output = testCommandExecutor.run(command); verifyProcessBuilding(command); Assert.assertEquals(expectedOutput, output); Mockito.verifyZeroInteractions(mockBuildLogger); } | public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } | CommandExecutor { public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } } | CommandExecutor { public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } } | CommandExecutor { public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } CommandExecutor setLogger(BuildLogger logger); CommandExecutor setEnvironment(Map<String, String> environmentMap); List<String> run(String... command); List<String> run(List<String> command); } | CommandExecutor { public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } CommandExecutor setLogger(BuildLogger logger); CommandExecutor setEnvironment(Map<String, String> environmentMap); List<String> run(String... command); List<String> run(List<String> command); } |
@Test public void testRun_commandError() throws InterruptedException, IOException { setMockProcessOutput(expectedOutput); Mockito.when(mockProcess.waitFor()).thenReturn(1); try { testCommandExecutor.run(command); Assert.fail("Expected an IOException to be thrown"); } catch (IOException ex) { Assert.assertEquals("command exited with non-zero exit code : 1", ex.getMessage()); verifyProcessBuilding(command); Mockito.verifyZeroInteractions(mockBuildLogger); } } | public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } | CommandExecutor { public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } } | CommandExecutor { public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } } | CommandExecutor { public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } CommandExecutor setLogger(BuildLogger logger); CommandExecutor setEnvironment(Map<String, String> environmentMap); List<String> run(String... command); List<String> run(List<String> command); } | CommandExecutor { public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } CommandExecutor setLogger(BuildLogger logger); CommandExecutor setEnvironment(Map<String, String> environmentMap); List<String> run(String... command); List<String> run(List<String> command); } |
@Test public void testParse_variableNameEmpty() { List<String> keyValueStrings = Arrays.asList("SOME_VARIABLE_1=SOME_VALUE_1", "=SOME_VALUE_2", "SOME_VARIABLE_3="); try { MinikubeDockerEnvParser.parse(keyValueStrings); Assert.fail("Expected an IllegalArgumentException to be thrown"); } catch (IllegalArgumentException ex) { Assert.assertEquals( "Error while parsing minikube's Docker environment: encountered empty environment variable name", ex.getMessage()); } } | public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } private MinikubeDockerEnvParser(); } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } private MinikubeDockerEnvParser(); static Map<String, String> parse(List<String> keyValueStrings); } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } private MinikubeDockerEnvParser(); static Map<String, String> parse(List<String> keyValueStrings); } |
@Test public void testParse_invalidFormat() { List<String> keyValueStrings = Arrays.asList("SOME_VARIABLE_1=SOME_VALUE_1", "SOME_VARIABLE_2", "SOME_VARIABLE_3="); try { MinikubeDockerEnvParser.parse(keyValueStrings); Assert.fail("Expected an IllegalArgumentException to be thrown"); } catch (IllegalArgumentException ex) { Assert.assertEquals( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format", ex.getMessage()); } } | public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } private MinikubeDockerEnvParser(); } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } private MinikubeDockerEnvParser(); static Map<String, String> parse(List<String> keyValueStrings); } | MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } private MinikubeDockerEnvParser(); static Map<String, String> parse(List<String> keyValueStrings); } |
@Test public void testDefaultMinikubeTasks() { Project project = ProjectBuilder.builder().withProjectDir(tmp.getRoot()).build(); project.getPluginManager().apply(MinikubePlugin.class); ((ProjectInternal) project).evaluate(); TaskContainer t = project.getTasks(); TaskCollection<MinikubeTask> tc = t.withType(MinikubeTask.class); Assert.assertEquals(3, tc.size()); AssertMinikubeTaskConfig(tc, "minikubeStart", "start"); AssertMinikubeTaskConfig(tc, "minikubeStop", "stop"); AssertMinikubeTaskConfig(tc, "minikubeDelete", "delete"); } | @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } @Override void apply(Project project); } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } @Override void apply(Project project); } |
@Test public void testMinikubeExtensionSetProperties() { Project project = ProjectBuilder.builder().withProjectDir(tmp.getRoot()).build(); project.getPluginManager().apply(MinikubePlugin.class); MinikubeExtension ex = (MinikubeExtension) project.getExtensions().getByName("minikube"); ex.setMinikube("/custom/minikube/path"); TaskContainer t = project.getTasks(); TaskCollection<MinikubeTask> tc = t.withType(MinikubeTask.class); Assert.assertEquals(3, tc.size()); tc.forEach( minikubeTask -> { Assert.assertEquals(minikubeTask.getMinikube(), "/custom/minikube/path"); }); } | @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } @Override void apply(Project project); } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } @Override void apply(Project project); } |
@Test public void testUserAddedMinikubeTaskConfigured() { Project project = ProjectBuilder.builder().withProjectDir(tmp.getRoot()).build(); project.getPluginManager().apply(MinikubePlugin.class); MinikubeExtension ex = (MinikubeExtension) project.getExtensions().getByName("minikube"); ex.setMinikube("/custom/minikube/path"); MinikubeTask custom = project.getTasks().create("minikubeCustom", MinikubeTask.class); custom.setCommand("custom"); Assert.assertEquals(custom.getMinikube(), "/custom/minikube/path"); Assert.assertEquals(custom.getCommand(), "custom"); Assert.assertArrayEquals(custom.getFlags(), new String[] {}); } | @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } @Override void apply(Project project); } | MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } @Override void apply(Project project); } |
@Test public void testGetDockerEnvWithDefaultProfile() throws IOException, InterruptedException { expectedCommand.add("--profile="); when(commandExecutorMock.run(expectedCommand)).thenReturn(dockerEnvOutput); Assert.assertEquals(expectedMap, minikube.getDockerEnv()); verify(commandExecutorMock).run(expectedCommand); } | public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); String getMinikube(); void setMinikube(String minikube); Property<String> getMinikubeProvider(); Map<String, String> getDockerEnv(); Map<String, String> getDockerEnv(String profile); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); String getMinikube(); void setMinikube(String minikube); Property<String> getMinikubeProvider(); Map<String, String> getDockerEnv(); Map<String, String> getDockerEnv(String profile); } |
@Test public void testGetDockerEnvWithTestProfile() throws IOException, InterruptedException { String profile = "testProfile"; expectedCommand.add("--profile=".concat(profile)); when(commandExecutorMock.run(expectedCommand)).thenReturn(dockerEnvOutput); Assert.assertEquals(expectedMap, minikube.getDockerEnv(profile)); verify(commandExecutorMock).run(expectedCommand); } | public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); String getMinikube(); void setMinikube(String minikube); Property<String> getMinikubeProvider(); Map<String, String> getDockerEnv(); Map<String, String> getDockerEnv(String profile); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); String getMinikube(); void setMinikube(String minikube); Property<String> getMinikubeProvider(); Map<String, String> getDockerEnv(); Map<String, String> getDockerEnv(String profile); } |
@Test public void testGetSameDockerEnvWithTwoDefaultProfiles() throws IOException, InterruptedException { String profile = ""; expectedCommand.add("--profile=".concat(profile)); when(commandExecutorMock.run(expectedCommand)).thenReturn(dockerEnvOutput); Assert.assertEquals(minikube.getDockerEnv(), minikube.getDockerEnv(profile)); verify(commandExecutorMock, times(2)).run(expectedCommand); } | public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); String getMinikube(); void setMinikube(String minikube); Property<String> getMinikubeProvider(); Map<String, String> getDockerEnv(); Map<String, String> getDockerEnv(String profile); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); String getMinikube(); void setMinikube(String minikube); Property<String> getMinikubeProvider(); Map<String, String> getDockerEnv(); Map<String, String> getDockerEnv(String profile); } |
@Test public void testGetDockerEnvWithNullProfile() throws IOException, InterruptedException { try { minikube.getDockerEnv(null); Assert.fail("getDockerEnv() should not permit null values"); } catch (NullPointerException ex) { Assert.assertNotNull(ex.getMessage()); Assert.assertEquals("Minikube profile must not be null", ex.getMessage()); } } | public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); String getMinikube(); void setMinikube(String minikube); Property<String> getMinikubeProvider(); Map<String, String> getDockerEnv(); Map<String, String> getDockerEnv(String profile); } | MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); String getMinikube(); void setMinikube(String minikube); Property<String> getMinikubeProvider(); Map<String, String> getDockerEnv(); Map<String, String> getDockerEnv(String profile); } |
@Test public void testEquals_true() throws MalformedURLException { DefaultedURL defaultedURL = new DefaultedURL(); DefaultedURL customURL = new DefaultedURL(); assertTrue(defaultedURL.equals(customURL)); } | @Override public boolean equals(Object o) { if (o instanceof DefaultedURL) { return url.equals(((DefaultedURL) o).getUrl()); } return false; } | DefaultedURL { @Override public boolean equals(Object o) { if (o instanceof DefaultedURL) { return url.equals(((DefaultedURL) o).getUrl()); } return false; } } | DefaultedURL { @Override public boolean equals(Object o) { if (o instanceof DefaultedURL) { return url.equals(((DefaultedURL) o).getUrl()); } return false; } DefaultedURL(); } | DefaultedURL { @Override public boolean equals(Object o) { if (o instanceof DefaultedURL) { return url.equals(((DefaultedURL) o).getUrl()); } return false; } DefaultedURL(); boolean isDefault(); void setUrl(URL url); String getDomain(); URL getUrl(); @Override String toString(); @Override boolean equals(Object o); } | DefaultedURL { @Override public boolean equals(Object o) { if (o instanceof DefaultedURL) { return url.equals(((DefaultedURL) o).getUrl()); } return false; } DefaultedURL(); boolean isDefault(); void setUrl(URL url); String getDomain(); URL getUrl(); @Override String toString(); @Override boolean equals(Object o); } |
@Test public void TestSelectN_selectFirstObfs4Connection_returnThirdGateway() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_two_openvpn_one_pt_gateways.json", null); MockHelper.mockProviderObserver(provider); mockStatic(PreferenceHelper.class); when(PreferenceHelper.getUsePluggableTransports(any(Context.class))).thenReturn(true); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("37.12.247.10", gatewaysManager.select(0).getRemoteIP()); } | public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } GatewaysManager(Context context); } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void testSelectN_selectFromPresortedGateways_returnsGatewaysInPresortedOrder() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); MockHelper.mockProviderObserver(provider); mockStatic(PreferenceHelper.class); when(PreferenceHelper.getUsePluggableTransports(any(Context.class))).thenReturn(false); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("manila.bitmask.net", gatewaysManager.select(0).getHost()); assertEquals("moscow.bitmask.net", gatewaysManager.select(1).getHost()); assertEquals("pt.demo.bitmask.net", gatewaysManager.select(2).getHost()); } | public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } GatewaysManager(Context context); } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void testSelectN_selectObfs4FromPresortedGateways_returnsObfs4GatewaysInPresortedOrder() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); MockHelper.mockProviderObserver(provider); mockStatic(PreferenceHelper.class); when(PreferenceHelper.getUsePluggableTransports(any(Context.class))).thenReturn(true); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("moscow.bitmask.net", gatewaysManager.select(0).getHost()); assertEquals("pt.demo.bitmask.net", gatewaysManager.select(1).getHost()); assertNull(gatewaysManager.select(2)); } | public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } GatewaysManager(Context context); } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void testGenerateVpnProfile_v1_tcp_udp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_tcp_udp.json"))); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 1); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertFalse(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v1_tcp_udp.trim())); } | public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); final static String TAG; } |
@Test public void testGenerateVpnProfile_v1_udp_tcp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_udp_tcp.json"))); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 1); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertFalse(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v1_udp_tcp.trim())); } | public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); final static String TAG; } |
@Test public void testGenerateVpnProfile_v2_tcp_udp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_tcp_udp.json"))); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 2); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertFalse(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v1_tcp_udp.trim())); } | public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); final static String TAG; } |
@Test public void testGenerateVpnProfile_v2_udp_tcp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_udp_tcp.json"))); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 2); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertFalse(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v1_udp_tcp.trim())); } | public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); final static String TAG; } |
@Test public void testGenerateVpnProfile_v3_obfs4() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("ptdemo.bitmask.eip-service.json"))).getJSONArray("gateways").getJSONObject(0); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 3); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertTrue(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.containsKey(OPENVPN)); System.out.println(vpnProfiles.get(OBFS4).getConfigFile(context, false)); assertTrue(vpnProfiles.get(OBFS4).getConfigFile(context, false).trim().equals(expectedVPNConfig_v3_obfs4.trim())); } | public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); final static String TAG; } |
@Test public void testGenerateVpnProfile_v3_ovpn_tcp_udp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("ptdemo_pt_tcp_udp.eip-service.json"))).getJSONArray("gateways").getJSONObject(0); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 3); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertTrue(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.containsKey(OPENVPN)); System.out.println(vpnProfiles.get(OPENVPN).getConfigFile(context, false)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v3_ovpn_tcp_udp.trim())); } | public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); final static String TAG; } |
@Test public void testGenerateVpnProfile_v3_ovpn_udp_tcp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("ptdemo_pt_udp_tcp.eip-service.json"))).getJSONArray("gateways").getJSONObject(0); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 3); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertTrue(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.containsKey(OPENVPN)); System.out.println(vpnProfiles.get(OPENVPN).getConfigFile(context, false)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v3_ovpn_udp_tcp.trim())); } | public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); } | VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); final static String TAG; } |
@Test public void testGatewayManagerFromCurrentProvider_noProvider_noGateways() { MockHelper.mockProviderObserver(null); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(0, gatewaysManager.size()); } | public int size() { return gateways.size(); } | GatewaysManager { public int size() { return gateways.size(); } } | GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); } | GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test @UseDataProvider("dataProviderTimezones") public void testSelect(int timezone, String expected) { when(ConfigHelper.getCurrentTimezone()).thenReturn(timezone); gatewaySelector = new GatewaySelector(gatewayList); assertEquals(expected, gatewaySelector.select().getName()); } | public Gateway select() { return closestGateway(); } | GatewaySelector { public Gateway select() { return closestGateway(); } } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); Gateway select(); Gateway select(int nClosest); } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); Gateway select(); Gateway select(int nClosest); } |
@Test @UseDataProvider("dataProviderSameDistanceTimezones") public void testSelectSameTimezoneDistance(int timezone, String expected1, String expected2) { when(ConfigHelper.getCurrentTimezone()).thenReturn(timezone); gatewaySelector = new GatewaySelector(gatewayList); assertTrue(gatewaySelector.select().getName().equals(expected1) || gatewaySelector.select().getName().equals(expected2)); } | public Gateway select() { return closestGateway(); } | GatewaySelector { public Gateway select() { return closestGateway(); } } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); Gateway select(); Gateway select(int nClosest); } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); Gateway select(); Gateway select(int nClosest); } |
@Test @UseDataProvider("dataProviderSameDistanceTimezones") public void testNClostest_SameTimezoneDistance_chooseGatewayWithSameDistance(int timezone, String expected1, String expected2) { when(ConfigHelper.getCurrentTimezone()).thenReturn(timezone); gatewaySelector = new GatewaySelector(gatewayList); ArrayList<String> gateways = new ArrayList<>(); gateways.add(gatewaySelector.select(0).getName()); gateways.add(gatewaySelector.select(1).getName()); assertTrue(gateways.contains(expected1) && gateways.contains(expected2)); } | public Gateway select() { return closestGateway(); } | GatewaySelector { public Gateway select() { return closestGateway(); } } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); Gateway select(); Gateway select(int nClosest); } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); Gateway select(); Gateway select(int nClosest); } |
@Test public void testNClostest_OneTimezonePerSet_choseSecondClosestTimezone() { when(ConfigHelper.getCurrentTimezone()).thenReturn(-4); gatewaySelector = new GatewaySelector(gatewayList); assertTrue("Frankfurt".equals(gatewaySelector.select(1).getName())); } | public Gateway select() { return closestGateway(); } | GatewaySelector { public Gateway select() { return closestGateway(); } } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); Gateway select(); Gateway select(int nClosest); } | GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); Gateway select(); Gateway select(int nClosest); } |
@Test public void testEquals_sameFields_returnsTrue() throws Exception { Provider p1 = TestSetupHelper.getConfiguredProvider(); Provider p2 = TestSetupHelper.getConfiguredProvider(); assertTrue("Providers should be same:", p1.equals(p2)); } | @Override public boolean equals(Object o) { if (o instanceof Provider) { Provider p = (Provider) o; return p.getDomain().equals(getDomain()) && definition.toString().equals(p.getDefinition().toString()) && eipServiceJson.toString().equals(p.getEipServiceJsonString()) && geoIpJson.toString().equals(p.getGeoIpJsonString()) && providerIp.equals(p.getProviderIp()) && providerApiIp.equals(p.getProviderApiIp()) && apiUrl.equals(p.getApiUrl()) && geoipUrl.equals(p.getGeoipUrl()) && certificatePin.equals(p.getCertificatePin()) && certificatePinEncoding.equals(p.getCertificatePinEncoding()) && caCert.equals(p.getCaCert()) && apiVersion.equals(p.getApiVersion()) && privateKey.equals(p.getPrivateKey()) && vpnCertificate.equals(p.getVpnCertificate()) && allowAnonymous == p.allowsAnonymous() && allowRegistered == p.allowsRegistered(); } else return false; } | Provider implements Parcelable { @Override public boolean equals(Object o) { if (o instanceof Provider) { Provider p = (Provider) o; return p.getDomain().equals(getDomain()) && definition.toString().equals(p.getDefinition().toString()) && eipServiceJson.toString().equals(p.getEipServiceJsonString()) && geoIpJson.toString().equals(p.getGeoIpJsonString()) && providerIp.equals(p.getProviderIp()) && providerApiIp.equals(p.getProviderApiIp()) && apiUrl.equals(p.getApiUrl()) && geoipUrl.equals(p.getGeoipUrl()) && certificatePin.equals(p.getCertificatePin()) && certificatePinEncoding.equals(p.getCertificatePinEncoding()) && caCert.equals(p.getCaCert()) && apiVersion.equals(p.getApiVersion()) && privateKey.equals(p.getPrivateKey()) && vpnCertificate.equals(p.getVpnCertificate()) && allowAnonymous == p.allowsAnonymous() && allowRegistered == p.allowsRegistered(); } else return false; } } | Provider implements Parcelable { @Override public boolean equals(Object o) { if (o instanceof Provider) { Provider p = (Provider) o; return p.getDomain().equals(getDomain()) && definition.toString().equals(p.getDefinition().toString()) && eipServiceJson.toString().equals(p.getEipServiceJsonString()) && geoIpJson.toString().equals(p.getGeoIpJsonString()) && providerIp.equals(p.getProviderIp()) && providerApiIp.equals(p.getProviderApiIp()) && apiUrl.equals(p.getApiUrl()) && geoipUrl.equals(p.getGeoipUrl()) && certificatePin.equals(p.getCertificatePin()) && certificatePinEncoding.equals(p.getCertificatePinEncoding()) && caCert.equals(p.getCaCert()) && apiVersion.equals(p.getApiVersion()) && privateKey.equals(p.getPrivateKey()) && vpnCertificate.equals(p.getVpnCertificate()) && allowAnonymous == p.allowsAnonymous() && allowRegistered == p.allowsRegistered(); } else return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); } | Provider implements Parcelable { @Override public boolean equals(Object o) { if (o instanceof Provider) { Provider p = (Provider) o; return p.getDomain().equals(getDomain()) && definition.toString().equals(p.getDefinition().toString()) && eipServiceJson.toString().equals(p.getEipServiceJsonString()) && geoIpJson.toString().equals(p.getGeoIpJsonString()) && providerIp.equals(p.getProviderIp()) && providerApiIp.equals(p.getProviderApiIp()) && apiUrl.equals(p.getApiUrl()) && geoipUrl.equals(p.getGeoipUrl()) && certificatePin.equals(p.getCertificatePin()) && certificatePinEncoding.equals(p.getCertificatePinEncoding()) && caCert.equals(p.getCaCert()) && apiVersion.equals(p.getApiVersion()) && privateKey.equals(p.getPrivateKey()) && vpnCertificate.equals(p.getVpnCertificate()) && allowAnonymous == p.allowsAnonymous() && allowRegistered == p.allowsRegistered(); } else return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); } | Provider implements Parcelable { @Override public boolean equals(Object o) { if (o instanceof Provider) { Provider p = (Provider) o; return p.getDomain().equals(getDomain()) && definition.toString().equals(p.getDefinition().toString()) && eipServiceJson.toString().equals(p.getEipServiceJsonString()) && geoIpJson.toString().equals(p.getGeoIpJsonString()) && providerIp.equals(p.getProviderIp()) && providerApiIp.equals(p.getProviderApiIp()) && apiUrl.equals(p.getApiUrl()) && geoipUrl.equals(p.getGeoipUrl()) && certificatePin.equals(p.getCertificatePin()) && certificatePinEncoding.equals(p.getCertificatePinEncoding()) && caCert.equals(p.getCaCert()) && apiVersion.equals(p.getApiVersion()) && privateKey.equals(p.getPrivateKey()) && vpnCertificate.equals(p.getVpnCertificate()) && allowAnonymous == p.allowsAnonymous() && allowRegistered == p.allowsRegistered(); } else return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); final static String API_URL; static final Parcelable.Creator<Provider> CREATOR; } |
@Test public void testEqualsThroughSetContains_differentFields_returnsFalse() throws Exception { Provider p1 = TestSetupHelper.getConfiguredProvider(); Provider p2 = TestSetupHelper.getConfiguredProvider(); p2.setMainUrl("http: Provider p3 = new Provider("https: Set<Provider> defaultProviders = new HashSet<>(); defaultProviders.add(p1); defaultProviders.add(p2); assertTrue(defaultProviders.contains(p1)); assertTrue(defaultProviders.contains(p2)); assertFalse(defaultProviders.contains(p3)); } | public void setMainUrl(URL url) { mainUrl.setUrl(url); } | Provider implements Parcelable { public void setMainUrl(URL url) { mainUrl.setUrl(url); } } | Provider implements Parcelable { public void setMainUrl(URL url) { mainUrl.setUrl(url); } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); } | Provider implements Parcelable { public void setMainUrl(URL url) { mainUrl.setUrl(url); } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); } | Provider implements Parcelable { public void setMainUrl(URL url) { mainUrl.setUrl(url); } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); final static String API_URL; static final Parcelable.Creator<Provider> CREATOR; } |
@Test public void testIsPluggableTransportsSupported_Obfs4_returnsTrue() throws Exception { Provider p1 = TestSetupHelper.getProvider( "https: null, null, null, null, null, "ptdemo.bitmask.eip-service.json", null); assertTrue(p1.supportsPluggableTransports()); } | public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } | Provider implements Parcelable { public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } } | Provider implements Parcelable { public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); } | Provider implements Parcelable { public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); } | Provider implements Parcelable { public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); final static String API_URL; static final Parcelable.Creator<Provider> CREATOR; } |
@Test public void testIsPluggableTransportsSupported_noObfs4_returnsFalse() throws Exception { Provider p1 = TestSetupHelper.getProvider( null, null, null, null, null, null, "eip-service-two-gateways.json", null); assertFalse(p1.supportsPluggableTransports()); } | public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } | Provider implements Parcelable { public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } } | Provider implements Parcelable { public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); } | Provider implements Parcelable { public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); } | Provider implements Parcelable { public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); final static String API_URL; static final Parcelable.Creator<Provider> CREATOR; } |
@Test public void testGatewayManagerFromCurrentProvider_misconfiguredProvider_noGateways() throws IOException, NullPointerException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_misconfigured_gateway.json", null); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(0, gatewaysManager.size()); } | public int size() { return gateways.size(); } | GatewaysManager { public int size() { return gateways.size(); } } | GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); } | GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void testGatewayManagerFromCurrentProvider_threeGateways() { Provider provider = getProvider(null, null, null, null,null, null, "ptdemo_three_mixed_gateways.json", null); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(3, gatewaysManager.size()); } | public int size() { return gateways.size(); } | GatewaysManager { public int size() { return gateways.size(); } } | GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); } | GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void TestGetPosition_VpnProfileExtistingObfs4_returnPositionZero() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OBFS4); profile.mGatewayIp = "37.218.247.60"; assertEquals(0, gatewaysManager.getPosition(profile)); } | public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void TestGetPosition_VpnProfileExtistingOpenvpn_returnPositionZero() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OPENVPN); profile.mGatewayIp = "37.218.247.60"; assertEquals(0, gatewaysManager.getPosition(profile)); } | public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void TestGetPosition_VpnProfileExistingObfs4FromPresortedList_returnsPositionOne() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OBFS4); profile.mGatewayIp = "37.218.247.60"; assertEquals(1, gatewaysManager.getPosition(profile)); } | public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void TestGetPosition_VpnProfileExistingOpenvpnFromPresortedList_returnsPositionOne() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OPENVPN); profile.mGatewayIp = "37.218.247.60"; assertEquals(2, gatewaysManager.getPosition(profile)); } | public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void TestGetPosition_VpnProfileDifferentIp_returnMinusOne() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OBFS4); profile.mGatewayIp = "37.218.247.61"; assertEquals(-1, gatewaysManager.getPosition(profile)); } | public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void TestGetPosition_VpnProfileMoscow_returnOne() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(1); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OBFS4); profile.mGatewayIp = "3.21.247.89"; assertEquals(1, gatewaysManager.getPosition(profile)); } | public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } | GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); } |
@Test public void testFitHarmonics() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, HARMONICS); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.tryAllOrders(ca1, axis, false); expectedHarmonics = new double[] { 0, 1.218482, 2.110836, 0.7203669, 0.8226358, 0.6092911, 0.6339138, 0.4439472, 0.4737434, }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.tryAllOrders(ca1, axis, false); expectedHarmonics = new double[] { 0, 0.5176411, 0.5359353, 0.4928912, 0.5044149, 0.4031307, 1.915722, 0.4049375, 0.4456366 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } | public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } | RotationOrderDetector implements OrderDetector { public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } } | RotationOrderDetector implements OrderDetector { public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); } | RotationOrderDetector implements OrderDetector { public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); } | RotationOrderDetector implements OrderDetector { public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; } |
@Test public void testParseInput() throws FileNotFoundException { URL url = CeSymmMainTest.class.getResource("/cesymmtest.txt"); String filename = url.getFile(); List<String> names = CeSymmMain.parseInputStructures(filename); assertEquals(6,names.size()); int i = 0; assertEquals("d1ijqa1",names.get(i++)); assertEquals("1G6S",names.get(i++)); assertEquals("1MER.A",names.get(i++)); assertEquals("d1h70a_",names.get(i++)); assertEquals("2YMS_A:,C:,B:,D:",names.get(i++)); assertEquals("1HIV",names.get(i++)); } | public static List<String> parseInputStructures(String filename) throws FileNotFoundException { File file = new File(filename); Scanner s = new Scanner(file); List<String> structures = new ArrayList<String>(); while (s.hasNext()) { String name = s.next(); if (name.startsWith("#")) { s.nextLine(); } else { structures.add(name); } } s.close(); return structures; } | CeSymmMain { public static List<String> parseInputStructures(String filename) throws FileNotFoundException { File file = new File(filename); Scanner s = new Scanner(file); List<String> structures = new ArrayList<String>(); while (s.hasNext()) { String name = s.next(); if (name.startsWith("#")) { s.nextLine(); } else { structures.add(name); } } s.close(); return structures; } } | CeSymmMain { public static List<String> parseInputStructures(String filename) throws FileNotFoundException { File file = new File(filename); Scanner s = new Scanner(file); List<String> structures = new ArrayList<String>(); while (s.hasNext()) { String name = s.next(); if (name.startsWith("#")) { s.nextLine(); } else { structures.add(name); } } s.close(); return structures; } } | CeSymmMain { public static List<String> parseInputStructures(String filename) throws FileNotFoundException { File file = new File(filename); Scanner s = new Scanner(file); List<String> structures = new ArrayList<String>(); while (s.hasNext()) { String name = s.next(); if (name.startsWith("#")) { s.nextLine(); } else { structures.add(name); } } s.close(); return structures; } static void main(String[] args); static List<String> parseInputStructures(String filename); } | CeSymmMain { public static List<String> parseInputStructures(String filename) throws FileNotFoundException { File file = new File(filename); Scanner s = new Scanner(file); List<String> structures = new ArrayList<String>(); while (s.hasNext()) { String name = s.next(); if (name.startsWith("#")) { s.nextLine(); } else { structures.add(name); } } s.close(); return structures; } static void main(String[] args); static List<String> parseInputStructures(String filename); } |
@Test public void testCalculateOrderByHarmonics() throws IOException, StructureException, RefinerFailedException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, HARMONICS); Atom[] ca1; AFPChain alignment; int order; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 2, order); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 6, order); name = "1TIM.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 1, order); } | @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } | RotationOrderDetector implements OrderDetector { @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } } | RotationOrderDetector implements OrderDetector { @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); } | RotationOrderDetector implements OrderDetector { @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); } | RotationOrderDetector implements OrderDetector { @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; } |
@Test public void testFitHarmonicsFloating() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, HARMONICS_FLOATING); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.tryAllOrders(ca1, axis, true); expectedHarmonics = new double[] { 2.597383371368633, 0.5213221707509845, 1.4121594197036587, 0.06167606937029615, 0.17901478726304354, 0.019300560598982656, 0.06908612977051289, -0.06104875791630157, -0.003831898183546225 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.tryAllOrders(ca1, axis, true); expectedHarmonics = new double[] { 1.2739427717435365, 0.2761280960318058, 0.2718581473051768, 0.22837118857649835, 0.20840059641118155, 0.10054298829557395, 1.5787950609554844, 0.06204472152219612, 0.07230120934912426 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "1TIM.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.tryAllOrders(ca1, axis, true); expectedHarmonics = new double[] { 2.835403848327179, 0.1468762702349724, 0.1159408606767334, 0.09051681783286569, 0.10420798340774699, -0.04381730637594528, 0.2023844545733075, -0.0059047948160164, 0.17631879026416564 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } | public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } | RotationOrderDetector implements OrderDetector { public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } } | RotationOrderDetector implements OrderDetector { public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); } | RotationOrderDetector implements OrderDetector { public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); } | RotationOrderDetector implements OrderDetector { public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; } |
@Test public void testCalculateOrderByHarmonicsFloating() throws IOException, StructureException, RefinerFailedException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, HARMONICS_FLOATING); Atom[] ca1; AFPChain alignment; int order; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 2, order); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 6, order); name = "1TIM.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 6, order); } | @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } | RotationOrderDetector implements OrderDetector { @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } } | RotationOrderDetector implements OrderDetector { @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); } | RotationOrderDetector implements OrderDetector { @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); } | RotationOrderDetector implements OrderDetector { @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; } |
@Test public void testTrySingleHarmonicsFloatingByAmp() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_HARMONIC_AMP); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { 0.009384193201414186, 1.1740333517311115, -0.44686757545089734, -0.2884995929083228, -0.2677652242044436, -0.19546335129315567, -0.15476867112456613, -0.09201871044036189 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { -0.09799681735927843, -0.21364824515873054, -0.11035897329374683, -0.21342288908870446, -0.1855205123692191, 1.4483981845191647, -0.14753158983373432, -0.20318262394650666 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "1TIM.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { 0.05425570731331745, -0.019746339856520342, -0.007014170110096962, -0.010253935127542774, -0.1363341693467633, 0.13180804348846586, -0.06217377718239171, 0.13580312417478568 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } | public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; } |
@Test public void testTrySingleHarmonicsFloatingBySSE() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_HARMONIC_SSE); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersBySSE(ca1, axis); expectedHarmonics = new double[] { 0.4072455479103931, 0.14067952827982602, 0.3779933525800668, 0.39480256016817444, 0.3960406707063868, 0.4012976706684556, 0.4035501028422771, 0.4059768120251738 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } | public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; } |
@Test public void testTrySingleCuspByAmp() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_CUSP_AMP); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { 0.1820283077630485, 1.0136815511756285, -0.3905901172609695, -0.26201199397108704, -0.20690437223329403, -0.1616881748238757, -0.11567568721588678, -0.08632416298270444 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { -0.1476801436899504, -0.12885346994573413, 0.16933007895862143, -0.21743126249158864, -0.18435161092570687, 1.1878594622938643, -0.13766536861375353, -0.1779357492984687 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "1TIM.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { 0.048573997778241465, -0.004122183485246968, 0.016836424264462534, 0.011565079482636204, -0.11506791209963799, 0.10046269754081401, -0.055177206937627045, 0.10338290890177872 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } | public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; } |
@Test public void testTrySingleCuspBySSE() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_CUSP_SSE); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersBySSE(ca1, axis); expectedHarmonics = new double[] { 0.4023477, 0.1620938, 0.3740037, 0.3923604, 0.3973309, 0.4011318, 0.4041583, 0.4054583 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } | public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; } |
@Test public void testTrySingleCuspFixedByAmp() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_CUSP_FIXED_AMP); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getAtomCAArray(StructureTools.getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { 0.1287134, 1.030371, -0.5324238, -0.4618442, -0.5114463, -0.4755183, -0.4395435, -0.3174656 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } | public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; } |
@Test public void testTrySingleCuspFixedBySSE() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_CUSP_FIXED_SSE); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getAtomCAArray(StructureTools.getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersBySSE(ca1, axis); expectedHarmonics = new double[] { 0.4023477, 0.1485084, 0.3794772, 0.3946517, 0.3969921, 0.4006527, 0.4033445, 0.4056923, }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-2); } | public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); } | RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; } |
@Test public void testAutoSuggestion() throws Exception { ListRolesRequest request = new ListRolesRequest().withMaxItems(1000); Role role1 = new Role().withRoleName("foobar1"); Role role2 = new Role().withRoleName("afoobar"); Role role3 = new Role().withRoleName("foooobar"); ListRolesResult mockResult = new ListRolesResult(); mockResult.withRoles(role1, role2, role3); when(mockClient.listRoles(request)).thenReturn(mockResult); List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("foobar"); assertEquals(list.size(), 2); assertEquals(list.get(0).name, "foobar1"); assertEquals(list.get(1).name, "afoobar"); verify(mockClient, times(1)).listRoles(request); } | public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } | PrincipalAutoSuggestion { public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } } | PrincipalAutoSuggestion { public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } PrincipalAutoSuggestion(AmazonIdentityManagement client); } | PrincipalAutoSuggestion { public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } PrincipalAutoSuggestion(AmazonIdentityManagement client); static PrincipalAutoSuggestion fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); List<Principal> autoSuggestion(final String name); } | PrincipalAutoSuggestion { public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } PrincipalAutoSuggestion(AmazonIdentityManagement client); static PrincipalAutoSuggestion fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); List<Principal> autoSuggestion(final String name); } |
@Test public void getAllStringSecrets() { List<StringSecretEntry> secrets = simpleSecretsGroup.getAllStringSecrets(); StringSecretEntry one = new StringSecretEntry(stringSecretIdentifier2, 1l, stringSecretValue2.asString()); StringSecretEntry two = new StringSecretEntry(stringSecretIdentifier3, 1l, stringSecretValue3.asString()); assertThat(secrets, is(Arrays.asList(one, two))); } | @Override public List<StringSecretEntry> getAllStringSecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.UTF8) .map(StringSecretEntry::of) .collect(Collectors.toList()); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<StringSecretEntry> getAllStringSecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.UTF8) .map(StringSecretEntry::of) .collect(Collectors.toList()); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<StringSecretEntry> getAllStringSecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.UTF8) .map(StringSecretEntry::of) .collect(Collectors.toList()); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<StringSecretEntry> getAllStringSecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.UTF8) .map(StringSecretEntry::of) .collect(Collectors.toList()); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<StringSecretEntry> getAllStringSecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.UTF8) .map(StringSecretEntry::of) .collect(Collectors.toList()); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void getAllByteSecrets() { List<ByteSecretEntry> secrets = simpleSecretsGroup.getAllBinarySecrets(); ByteSecretEntry one = new ByteSecretEntry(binarySecretIdentifier2, 1l, binarySecretValue2.asByteArray()); ByteSecretEntry two = new ByteSecretEntry(binarySecretIdentifier3, 1l, binarySecretValue3.asByteArray()); assertThat(secrets, is(Arrays.asList(one, two))); } | @Override public List<ByteSecretEntry> getAllBinarySecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.BINARY) .map(ByteSecretEntry::of) .collect(Collectors.toList()); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<ByteSecretEntry> getAllBinarySecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.BINARY) .map(ByteSecretEntry::of) .collect(Collectors.toList()); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<ByteSecretEntry> getAllBinarySecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.BINARY) .map(ByteSecretEntry::of) .collect(Collectors.toList()); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<ByteSecretEntry> getAllBinarySecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.BINARY) .map(ByteSecretEntry::of) .collect(Collectors.toList()); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<ByteSecretEntry> getAllBinarySecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.BINARY) .map(ByteSecretEntry::of) .collect(Collectors.toList()); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void getStringSecret() { Optional<String> result = simpleSecretsGroup.getStringSecret(stringSecretIdentifier); assertThat(result, is(Optional.of(value1))); } | @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void versioned_getStringSecret() { Optional<String> result = simpleSecretsGroup.getStringSecret(stringSecretIdentifier, version); assertThat(result, is(Optional.of(value2))); } | @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void getBinarySecret() { Optional<byte[]> result = simpleSecretsGroup.getBinarySecret(binarySecretIdentifier); assertThat(result, is(Optional.of(value3))); } | @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void versioned_getBinarySecret() { Optional<byte[]> result = simpleSecretsGroup.getBinarySecret(binarySecretIdentifier, version); assertThat(result, is(Optional.of(value4))); } | @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void not_present_getStringSecret() { Optional<String> result = simpleSecretsGroup.getStringSecret(notPresent); assertThat(result, is(Optional.empty())); } | @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void not_present_versioned_getStringSecret() { Optional<String> result = simpleSecretsGroup.getStringSecret(notPresent, version); assertThat(result, is(Optional.empty())); } | @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void not_present_getBinarySecret() { Optional<byte[]> result = simpleSecretsGroup.getBinarySecret(notPresent); assertThat(result, is(Optional.empty())); } | @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void not_present_versioned_getBinarySecret() { Optional<byte[]> result = simpleSecretsGroup.getBinarySecret(notPresent, version); assertThat(result, is(Optional.empty())); } | @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void testDetachReadonlyRole() throws Exception { Principal principal = new Principal(PrincipalType.ROLE, "awesome-service"); partiallyMockedPolicyManager.detachReadOnly(group, principal); DetachRolePolicyRequest request = new DetachRolePolicyRequest() .withPolicyArn(READONLY_POLICY_ARN) .withRoleName(principal.name); verify(mockClient, times(1)).detachRolePolicy(request); } | public void detachReadOnly(SecretsGroupIdentifier group, Principal principal) { detachPrincipal(group,principal, AccessLevel.READONLY); } | IAMPolicyManager { public void detachReadOnly(SecretsGroupIdentifier group, Principal principal) { detachPrincipal(group,principal, AccessLevel.READONLY); } } | IAMPolicyManager { public void detachReadOnly(SecretsGroupIdentifier group, Principal principal) { detachPrincipal(group,principal, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); } | IAMPolicyManager { public void detachReadOnly(SecretsGroupIdentifier group, Principal principal) { detachPrincipal(group,principal, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); } | IAMPolicyManager { public void detachReadOnly(SecretsGroupIdentifier group, Principal principal) { detachPrincipal(group,principal, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } |
@Test(expectedExceptions = EncodingException.class) public void getStringSecret_on_binary_secret() { simpleSecretsGroup.getStringSecret(binarySecretIdentifier); } | @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test(expectedExceptions = EncodingException.class) public void getBinarySecret_on_string_secret() { simpleSecretsGroup.getBinarySecret(stringSecretIdentifier); } | @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } | DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); } |
@Test public void testDetachAllPrincipals() throws Exception { } | public void detachAllPrincipals(SecretsGroupIdentifier group) { try { List<Principal> admins = listAttachedAdmin(group); admins.forEach(p -> detachAdmin(group, p)); } catch (DoesNotExistException e) { } try { List<Principal> readonly = listAttachedReadOnly(group); readonly.forEach(p -> detachReadOnly(group, p)); } catch (DoesNotExistException e) { } } | IAMPolicyManager { public void detachAllPrincipals(SecretsGroupIdentifier group) { try { List<Principal> admins = listAttachedAdmin(group); admins.forEach(p -> detachAdmin(group, p)); } catch (DoesNotExistException e) { } try { List<Principal> readonly = listAttachedReadOnly(group); readonly.forEach(p -> detachReadOnly(group, p)); } catch (DoesNotExistException e) { } } } | IAMPolicyManager { public void detachAllPrincipals(SecretsGroupIdentifier group) { try { List<Principal> admins = listAttachedAdmin(group); admins.forEach(p -> detachAdmin(group, p)); } catch (DoesNotExistException e) { } try { List<Principal> readonly = listAttachedReadOnly(group); readonly.forEach(p -> detachReadOnly(group, p)); } catch (DoesNotExistException e) { } } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); } | IAMPolicyManager { public void detachAllPrincipals(SecretsGroupIdentifier group) { try { List<Principal> admins = listAttachedAdmin(group); admins.forEach(p -> detachAdmin(group, p)); } catch (DoesNotExistException e) { } try { List<Principal> readonly = listAttachedReadOnly(group); readonly.forEach(p -> detachReadOnly(group, p)); } catch (DoesNotExistException e) { } } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); } | IAMPolicyManager { public void detachAllPrincipals(SecretsGroupIdentifier group) { try { List<Principal> admins = listAttachedAdmin(group); admins.forEach(p -> detachAdmin(group, p)); } catch (DoesNotExistException e) { } try { List<Principal> readonly = listAttachedReadOnly(group); readonly.forEach(p -> detachReadOnly(group, p)); } catch (DoesNotExistException e) { } } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } |
@Test public void testListAttachedAdminNoneAttached() throws Exception { ListEntitiesForPolicyRequest request = new ListEntitiesForPolicyRequest() .withPolicyArn(ADMIN_POLICY_ARN); ListEntitiesForPolicyResult result = new ListEntitiesForPolicyResult(); when(mockClient.listEntitiesForPolicy(request)).thenReturn(result); List<Principal> list = partiallyMockedPolicyManager.listAttachedAdmin(group); assertTrue(list.isEmpty()); } | public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } | IAMPolicyManager { public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } } | IAMPolicyManager { public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); } | IAMPolicyManager { public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); } | IAMPolicyManager { public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } |
@Test public void testListAttachedAdmin() throws Exception { ListEntitiesForPolicyRequest request = new ListEntitiesForPolicyRequest() .withPolicyArn(ADMIN_POLICY_ARN); PolicyGroup policyGroup = new PolicyGroup().withGroupName("awesome-group"); PolicyRole policyRole = new PolicyRole().withRoleName("awesome-service"); PolicyUser policyUser = new PolicyUser().withUserName("bob"); ListEntitiesForPolicyResult result = new ListEntitiesForPolicyResult() .withPolicyGroups(policyGroup) .withPolicyUsers(policyUser) .withPolicyRoles(policyRole); when(mockClient.listEntitiesForPolicy(request)).thenReturn(result); List<Principal> list = partiallyMockedPolicyManager.listAttachedAdmin(group); assertEquals(list.size(), 3); assertEquals(list.get(0), new Principal(PrincipalType.GROUP, "awesome-group")); assertEquals(list.get(1), new Principal(PrincipalType.USER, "bob")); assertEquals(list.get(2), new Principal(PrincipalType.ROLE, "awesome-service")); } | public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } | IAMPolicyManager { public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } } | IAMPolicyManager { public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); } | IAMPolicyManager { public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); } | IAMPolicyManager { public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } |
@Test public void testListAttachedReadOnly() throws Exception { ListEntitiesForPolicyRequest request = new ListEntitiesForPolicyRequest() .withPolicyArn(READONLY_POLICY_ARN); PolicyGroup policyGroup = new PolicyGroup().withGroupName("awesome-group"); PolicyRole policyRole = new PolicyRole().withRoleName("awesome-service"); PolicyUser policyUser = new PolicyUser().withUserName("alice"); ListEntitiesForPolicyResult result = new ListEntitiesForPolicyResult() .withPolicyGroups(policyGroup) .withPolicyUsers(policyUser) .withPolicyRoles(policyRole); when(mockClient.listEntitiesForPolicy(request)).thenReturn(result); List<Principal> list = partiallyMockedPolicyManager.listAttachedReadOnly(group); assertEquals(list.size(), 3); assertEquals(list.get(0), new Principal(PrincipalType.GROUP, "awesome-group")); assertEquals(list.get(1), new Principal(PrincipalType.USER, "alice")); assertEquals(list.get(2), new Principal(PrincipalType.ROLE, "awesome-service")); } | public List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.READONLY); } | IAMPolicyManager { public List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.READONLY); } } | IAMPolicyManager { public List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); } | IAMPolicyManager { public List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); } | IAMPolicyManager { public List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } |
@Test public void testGetSecretsGroupIdentifiersNoGroups() throws Exception { ListPoliciesRequest request = new ListPoliciesRequest().withMaxItems(1000).withPathPrefix("/strongbox/"); when(mockClient.listPolicies(request)).thenReturn(new ListPoliciesResult()); Set<SecretsGroupIdentifier> identifiers = partiallyMockedPolicyManager.getSecretsGroupIdentifiers(); assertTrue(identifiers.isEmpty()); } | public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } | IAMPolicyManager { public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } } | IAMPolicyManager { public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); } | IAMPolicyManager { public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); } | IAMPolicyManager { public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } |
@Test public void testGetSecretsGroupIdentifiers() throws Exception { ListPoliciesRequest request = new ListPoliciesRequest().withMaxItems(1000).withPathPrefix("/strongbox/"); Policy policyUS1 = new Policy().withPolicyName("strongbox_us-west-1_test-group1_admin"); Policy policyUS2 = new Policy().withPolicyName("strongbox_us-west-1_test-group2_admin"); Policy policyEU1 = new Policy().withPolicyName("strongbox_eu-west-1_test-group1_admin"); Policy policyEU1readonly = new Policy().withPolicyName("strongbox_eu-west-1_test-group1_readonly"); ListPoliciesResult result = new ListPoliciesResult() .withPolicies(policyUS1, policyUS2, policyEU1, policyEU1readonly); when(mockClient.listPolicies(request)).thenReturn(new ListPoliciesResult() .withPolicies(policyUS1, policyUS2, policyEU1, policyEU1readonly)); Set<SecretsGroupIdentifier> identifiers = partiallyMockedPolicyManager.getSecretsGroupIdentifiers(); assertEquals(identifiers.size(), 3); assertTrue(identifiers.contains(new SecretsGroupIdentifier(Region.US_WEST_1, "test.group1"))); assertTrue(identifiers.contains(new SecretsGroupIdentifier(Region.US_WEST_1, "test.group2"))); assertTrue(identifiers.contains(new SecretsGroupIdentifier(Region.EU_WEST_1, "test.group1"))); verify(mockClient, times(1)).listPolicies(request); } | public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } | IAMPolicyManager { public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } } | IAMPolicyManager { public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); } | IAMPolicyManager { public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); } | IAMPolicyManager { public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } |
@Test public void testCreateAdminPolicy() throws Exception { String policyDocument = new String(Files.readAllBytes(Paths.get(TEST_DATA_DIR, "test_admin_policy"))); CreatePolicyRequest request = constructCreatePolicyRequest("admin", policyDocument); CreatePolicyResult result = new CreatePolicyResult().withPolicy(new Policy().withArn(ADMIN_POLICY_ARN)); when(mockClient.createPolicy(request)).thenReturn(result); DescribeKeyRequest keyRequest = new DescribeKeyRequest().withKeyId(KMS_ALIAS_ARN); when(mockKMSClient.describeKey(keyRequest)).thenReturn(constructDescribeKeyResult()); String policyArn = partiallyMockedPolicyManager.createAdminPolicy(group, kmsEncryptor, partiallyMockedStore); verify(mockClient, times(1)).createPolicy(request); verify(mockKMSClient, times(1)).describeKey(keyRequest); assertEquals(policyArn, ADMIN_POLICY_ARN); } | public String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store) { String adminPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + kmsEncryptor.awsAdminPolicy().get() + ",\n" + storeAdminPolicyString(store) + ",\n" + listAllPolicies() + ",\n" + getPolicyInfo(group) + ",\n" + managePolicies(group) + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.ADMIN, adminPolicy); } | IAMPolicyManager { public String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store) { String adminPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + kmsEncryptor.awsAdminPolicy().get() + ",\n" + storeAdminPolicyString(store) + ",\n" + listAllPolicies() + ",\n" + getPolicyInfo(group) + ",\n" + managePolicies(group) + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.ADMIN, adminPolicy); } } | IAMPolicyManager { public String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store) { String adminPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + kmsEncryptor.awsAdminPolicy().get() + ",\n" + storeAdminPolicyString(store) + ",\n" + listAllPolicies() + ",\n" + getPolicyInfo(group) + ",\n" + managePolicies(group) + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.ADMIN, adminPolicy); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); } | IAMPolicyManager { public String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store) { String adminPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + kmsEncryptor.awsAdminPolicy().get() + ",\n" + storeAdminPolicyString(store) + ",\n" + listAllPolicies() + ",\n" + getPolicyInfo(group) + ",\n" + managePolicies(group) + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.ADMIN, adminPolicy); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); } | IAMPolicyManager { public String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store) { String adminPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + kmsEncryptor.awsAdminPolicy().get() + ",\n" + storeAdminPolicyString(store) + ",\n" + listAllPolicies() + ",\n" + getPolicyInfo(group) + ",\n" + managePolicies(group) + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.ADMIN, adminPolicy); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } |
@Test public void testCreateReadOnlyPolicy() throws Exception { String policyDocument = new String(Files.readAllBytes(Paths.get(TEST_DATA_DIR, "test_readonly_policy"))); CreatePolicyRequest request = constructCreatePolicyRequest("readonly", policyDocument); CreatePolicyResult result = new CreatePolicyResult().withPolicy(new Policy().withArn(READONLY_POLICY_ARN)); when(mockClient.createPolicy(request)).thenReturn(result); DescribeKeyRequest keyRequest = new DescribeKeyRequest().withKeyId(KMS_ALIAS_ARN); when(mockKMSClient.describeKey(keyRequest)).thenReturn(constructDescribeKeyResult()); String policyArn = partiallyMockedPolicyManager.createReadOnlyPolicy(group, kmsEncryptor, partiallyMockedStore); verify(mockClient, times(1)).createPolicy(request); verify(mockKMSClient, times(1)).describeKey(keyRequest); assertEquals(policyArn, READONLY_POLICY_ARN); } | public String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store) { String readOnlyPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + storeReadOnlyPolicyString(store) + ",\n" + kmsEncryptor.awsReadOnlyPolicy().get() + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.READONLY, readOnlyPolicy); } | IAMPolicyManager { public String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store) { String readOnlyPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + storeReadOnlyPolicyString(store) + ",\n" + kmsEncryptor.awsReadOnlyPolicy().get() + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.READONLY, readOnlyPolicy); } } | IAMPolicyManager { public String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store) { String readOnlyPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + storeReadOnlyPolicyString(store) + ",\n" + kmsEncryptor.awsReadOnlyPolicy().get() + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.READONLY, readOnlyPolicy); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); } | IAMPolicyManager { public String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store) { String readOnlyPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + storeReadOnlyPolicyString(store) + ",\n" + kmsEncryptor.awsReadOnlyPolicy().get() + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.READONLY, readOnlyPolicy); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); } | IAMPolicyManager { public String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store) { String readOnlyPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + storeReadOnlyPolicyString(store) + ",\n" + kmsEncryptor.awsReadOnlyPolicy().get() + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.READONLY, readOnlyPolicy); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } |
@Test public void testDeleteAdminPolicy() throws Exception { DeletePolicyRequest request = new DeletePolicyRequest().withPolicyArn(ADMIN_POLICY_ARN); partiallyMockedPolicyManager.deleteAdminPolicy(group); verify(mockClient, times(1)).deletePolicy(request); } | public void deleteAdminPolicy(SecretsGroupIdentifier group) { deletePolicy(group, AccessLevel.ADMIN); } | IAMPolicyManager { public void deleteAdminPolicy(SecretsGroupIdentifier group) { deletePolicy(group, AccessLevel.ADMIN); } } | IAMPolicyManager { public void deleteAdminPolicy(SecretsGroupIdentifier group) { deletePolicy(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); } | IAMPolicyManager { public void deleteAdminPolicy(SecretsGroupIdentifier group) { deletePolicy(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); } | IAMPolicyManager { public void deleteAdminPolicy(SecretsGroupIdentifier group) { deletePolicy(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } |
@Test public void testAutoSuggestionShortName() throws Exception { ListRolesRequest request = new ListRolesRequest().withMaxItems(1000); List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("fo"); assertTrue(list.isEmpty()); verify(mockClient, never()).listRoles(request); } | public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } | PrincipalAutoSuggestion { public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } } | PrincipalAutoSuggestion { public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } PrincipalAutoSuggestion(AmazonIdentityManagement client); } | PrincipalAutoSuggestion { public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } PrincipalAutoSuggestion(AmazonIdentityManagement client); static PrincipalAutoSuggestion fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); List<Principal> autoSuggestion(final String name); } | PrincipalAutoSuggestion { public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } PrincipalAutoSuggestion(AmazonIdentityManagement client); static PrincipalAutoSuggestion fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); List<Principal> autoSuggestion(final String name); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.