List of usage examples for java.util Base64 getEncoder
public static Encoder getEncoder()
From source file:org.wso2.carbon.apimgt.core.impl.AMDefaultKeyManagerImpl.java
/** * This method is to generate a new application access token * * @param tokenRequest AccessTokenRequest which encapsulates parameters sent from Store UI. * @return AccessTokenInfo which wraps application access token data * @throws KeyManagementException -throws KeyManagementException type *///from w w w . j a v a 2s .com @Override public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws KeyManagementException { String newAccessToken; long validityPeriod; AccessTokenInfo tokenInfo = null; if (tokenRequest == null) { log.warn("No information available to generate Token."); return null; } //TO-DO -ADD A CONFIG FOR TOKEN ENDPOINT String tokenEndpoint = System.getProperty("TokenEndpoint", "https://localhost:9443/oauth2/token"); //TO-DO -ADD A CONFIG FOR REVOKE ENDPOINT String revokeEndpoint = System.getProperty("RevokeEndpoint", "https://localhost:9443/oauth2/revoke"); ; // Call the /revoke only if there's a token to be revoked. URL url; HttpURLConnection urlConn = null; if (tokenRequest.getTokenToRevoke() != null && !"".equals(tokenRequest.getTokenToRevoke())) { //Revoke the Old Access Token try { createSSLConnection(); url = new URL(revokeEndpoint); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestMethod("POST"); String postParams = KeyManagerConstants.OAUTH_CLIENT_ID + "=" + tokenRequest.getClientId() + KeyManagerConstants.OAUTH_CLIENT_SECRET + "=" + tokenRequest.getClientSecret() + KeyManagerConstants.OAUTH_TOKEN + "=" + tokenRequest.getTokenToRevoke(); urlConn.getOutputStream().write((postParams).getBytes("UTF-8")); int responseCode = urlConn.getResponseCode(); if (responseCode != 200) { //If token revoke failed throw new RuntimeException("Token revoke failed : HTTP error code : " + responseCode); } else { APIUtils.logDebug( "Successfully submitted revoke request for old application token. HTTP status : 200", log); } } catch (IOException e) { String msg = "Error while revoking the existing token."; log.error(msg, e); throw new KeyManagementException(msg + e.getMessage(), e, ExceptionCodes.APPLICATION_TOKEN_GENERATION_FAILED); } catch (NoSuchAlgorithmException | java.security.KeyManagementException e) { String msg = "Error while connecting with the revoke endpoint for revoking the existing token."; log.error(msg, e); throw new KeyManagementException(msg + e.getMessage(), e, ExceptionCodes.APPLICATION_TOKEN_GENERATION_FAILED); } finally { if (urlConn != null) { urlConn.disconnect(); } } } //get default application access token name from config. //TO-DO -DEFINE APPICATION TOKEN SCOPES String applicationTokenScope = ""; // When validity time set to a negative value, a token is considered never to expire. if (tokenRequest.getValidityPeriod() == -1L) { // Setting a different -ve value if the set value is -1 (-1 will be ignored by TokenValidator) tokenRequest.setValidityPeriod(-2); } //Generate New Access Token by client credentials grant type with calling Token API try { createSSLConnection(); url = new URL(tokenEndpoint); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String clientEncoded = Base64.getEncoder() .encodeToString((tokenRequest.getClientId() + ":" + tokenRequest.getClientSecret()) .getBytes(StandardCharsets.UTF_8)); urlConn.setRequestProperty("Authorization", "Basic " + clientEncoded); StringBuilder builder = new StringBuilder(); builder.append(applicationTokenScope); for (String scope : tokenRequest.getScopes()) { builder.append(' ').append(scope); } String postParams = KeyManagerConstants.OAUTH_CLIENT_GRANT + "=" + GRANT_TYPE_VALUE; // + "&" + // GRANT_TYPE_PARAM_VALIDITY + "=" + Long.toString(tokenRequest.getValidityPeriod()) + "&" + // KeyManagerConstants.OAUTH_CLIENT_ID + "=" + tokenRequest.getClientId() + "&" + // KeyManagerConstants.OAUTH_CLIENT_SECRET + "=" + tokenRequest.getClientSecret() + "&" + // KeyManagerConstants.OAUTH_CLIENT_SCOPE + "=" + builder.toString(); urlConn.getOutputStream().write((postParams).getBytes("UTF-8")); int responseCode = urlConn.getResponseCode(); if (responseCode != 200) { //If token generation failed throw new RuntimeException( "Error occurred while calling token endpoint: HTTP error code : " + responseCode); } else { APIUtils.logDebug( "Successfully submitted token request for old application token. HTTP status : 200", log); tokenInfo = new AccessTokenInfo(); String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), "UTF-8"); JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(responseStr).getAsJsonObject(); newAccessToken = obj.get(OAUTH_RESPONSE_ACCESSTOKEN).getAsString(); validityPeriod = Long.parseLong(obj.get(OAUTH_RESPONSE_EXPIRY_TIME).toString()); if (obj.has(KeyManagerConstants.OAUTH_CLIENT_SCOPE)) { tokenInfo.setScopes( (obj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_SCOPE).getAsString()) .split(" ")); } tokenInfo.setAccessToken(newAccessToken); tokenInfo.setValidityPeriod(validityPeriod); } } catch (IOException e) { String msg = "Error while creating the new token for token regeneration."; log.error(msg, e); throw new KeyManagementException(msg + e.getMessage(), e, ExceptionCodes.APPLICATION_TOKEN_GENERATION_FAILED); } catch (JsonSyntaxException e) { String msg = "Error while processing the response returned from token generation call."; log.error(msg, e); throw new KeyManagementException(msg + e.getMessage(), e, ExceptionCodes.APPLICATION_TOKEN_GENERATION_FAILED); } catch (NoSuchAlgorithmException | java.security.KeyManagementException e) { String msg = "Error while connecting to the token generation endpoint."; log.error(msg, e); throw new KeyManagementException(msg + e.getMessage(), e, ExceptionCodes.APPLICATION_TOKEN_GENERATION_FAILED); } finally { if (urlConn != null) { urlConn.disconnect(); } } return tokenInfo; }
From source file:com.simiacryptus.util.Util.java
/** * To inline image string./*w ww . j av a 2 s .co m*/ * * @param img the img * @return the string */ public static String toInlineImage(@javax.annotation.Nonnull final LabeledObject<BufferedImage> img) { @javax.annotation.Nonnull final ByteArrayOutputStream b = new ByteArrayOutputStream(); try { ImageIO.write(img.data, "PNG", b); } catch (@javax.annotation.Nonnull final RuntimeException e) { throw e; } catch (@javax.annotation.Nonnull final Exception e) { throw new RuntimeException(e); } final byte[] byteArray = b.toByteArray(); final String encode = Base64.getEncoder().encodeToString(byteArray); return "<img src=\"data:image/png;base64," + encode + "\" alt=\"" + img.label + "\" />"; }
From source file:ro.cs.products.Executor.java
private static int execute(CommandLine commandLine) throws Exception { int retCode = ReturnCode.OK; CommandLineParser parser = new DefaultParser(); String logFile = props.getProperty("master.log.file"); String folder;//from w ww .j a v a 2 s. c om boolean debugMode = commandLine.hasOption(Constants.PARAM_VERBOSE); Logger.CustomLogger logger; SensorType sensorType = commandLine.hasOption(Constants.SENSOR) ? Enum.valueOf(SensorType.class, commandLine.getOptionValue(Constants.SENSOR)) : SensorType.S2; if (commandLine.hasOption(Constants.PARAM_INPUT_FOLDER)) { folder = commandLine.getOptionValue(Constants.PARAM_INPUT_FOLDER); Utilities.ensureExists(Paths.get(folder)); Logger.initialize(Paths.get(folder, logFile).toAbsolutePath().toString(), debugMode); logger = Logger.getRootLogger(); if (commandLine.hasOption(Constants.PARAM_VERBOSE)) { printCommandLine(commandLine); } if (sensorType == SensorType.L8) { logger.warn("Argument --input will be ignored for Landsat8"); } else { String rootFolder = commandLine.getOptionValue(Constants.PARAM_INPUT_FOLDER); FillAnglesMethod fillAnglesMethod = Enum.valueOf(FillAnglesMethod.class, commandLine.hasOption(Constants.PARAM_FILL_ANGLES) ? commandLine.getOptionValue(Constants.PARAM_FILL_ANGLES).toUpperCase() : FillAnglesMethod.NONE.name()); if (!FillAnglesMethod.NONE.equals(fillAnglesMethod)) { try { Set<String> products = null; if (commandLine.hasOption(Constants.PARAM_PRODUCT_LIST)) { products = new HashSet<>(); for (String product : commandLine.getOptionValues(Constants.PARAM_PRODUCT_LIST)) { if (!product.endsWith(".SAFE")) { products.add(product + ".SAFE"); } else { products.add(product); } } } ProductInspector inspector = new ProductInspector(rootFolder, fillAnglesMethod, products); inspector.traverse(); } catch (IOException e) { logger.error(e.getMessage()); retCode = ReturnCode.DOWNLOAD_ERROR; } } } } else { folder = commandLine.getOptionValue(Constants.PARAM_OUT_FOLDER); Utilities.ensureExists(Paths.get(folder)); Logger.initialize(Paths.get(folder, logFile).toAbsolutePath().toString(), debugMode); logger = Logger.getRootLogger(); printCommandLine(commandLine); String proxyType = commandLine.hasOption(Constants.PARAM_PROXY_TYPE) ? commandLine.getOptionValue(Constants.PARAM_PROXY_TYPE) : nullIfEmpty(props.getProperty("proxy.type", null)); String proxyHost = commandLine.hasOption(Constants.PARAM_PROXY_HOST) ? commandLine.getOptionValue(Constants.PARAM_PROXY_HOST) : nullIfEmpty(props.getProperty("proxy.host", null)); String proxyPort = commandLine.hasOption(Constants.PARAM_PROXY_PORT) ? commandLine.getOptionValue(Constants.PARAM_PROXY_PORT) : nullIfEmpty(props.getProperty("proxy.port", null)); String proxyUser = commandLine.hasOption(Constants.PARAM_PROXY_USER) ? commandLine.getOptionValue(Constants.PARAM_PROXY_USER) : nullIfEmpty(props.getProperty("proxy.user", null)); String proxyPwd = commandLine.hasOption(Constants.PARAM_PROXY_PASSWORD) ? commandLine.getOptionValue(Constants.PARAM_PROXY_PASSWORD) : nullIfEmpty(props.getProperty("proxy.pwd", null)); NetUtils.setProxy(proxyType, proxyHost, proxyPort == null ? 0 : Integer.parseInt(proxyPort), proxyUser, proxyPwd); List<ProductDescriptor> products = new ArrayList<>(); Set<String> tiles = new HashSet<>(); Polygon2D areaOfInterest = new Polygon2D(); ProductStore source = Enum.valueOf(ProductStore.class, commandLine.getOptionValue(Constants.PARAM_DOWNLOAD_STORE, ProductStore.SCIHUB.toString())); if (sensorType == SensorType.S2 && !commandLine.hasOption(Constants.PARAM_FLAG_SEARCH_AWS) && !commandLine.hasOption(Constants.PARAM_USER)) { throw new MissingOptionException("Missing SciHub credentials"); } String user = commandLine.getOptionValue(Constants.PARAM_USER); String pwd = commandLine.getOptionValue(Constants.PARAM_PASSWORD); if (user != null && pwd != null && !user.isEmpty() && !pwd.isEmpty()) { String authToken = "Basic " + new String(Base64.getEncoder().encode((user + ":" + pwd).getBytes())); NetUtils.setAuthToken(authToken); } ProductDownloader downloader = sensorType.equals(SensorType.S2) ? new SentinelProductDownloader(source, commandLine.getOptionValue(Constants.PARAM_OUT_FOLDER), props) : new LandsatProductDownloader(commandLine.getOptionValue(Constants.PARAM_OUT_FOLDER), props); TileMap tileMap = sensorType == SensorType.S2 ? SentinelTilesMap.getInstance() : LandsatTilesMap.getInstance(); if (commandLine.hasOption(Constants.PARAM_AREA)) { String[] points = commandLine.getOptionValues(Constants.PARAM_AREA); for (String point : points) { areaOfInterest.append(Double.parseDouble(point.substring(0, point.indexOf(","))), Double.parseDouble(point.substring(point.indexOf(",") + 1))); } } else if (commandLine.hasOption(Constants.PARAM_AREA_FILE)) { areaOfInterest = Polygon2D.fromWKT(new String( Files.readAllBytes(Paths.get(commandLine.getOptionValue(Constants.PARAM_AREA_FILE))), StandardCharsets.UTF_8)); } else if (commandLine.hasOption(Constants.PARAM_TILE_SHAPE_FILE)) { String tileShapeFile = commandLine.getOptionValue(Constants.PARAM_TILE_SHAPE_FILE); if (Files.exists(Paths.get(tileShapeFile))) { logger.info(String.format("Reading %s tiles extents", sensorType)); tileMap.fromKmlFile(tileShapeFile); logger.info(String.valueOf(tileMap.getCount() + " tiles found")); } } else { if (tileMap.getCount() == 0) { logger.info(String.format("Loading %s tiles extents", sensorType)); tileMap.read(Executor.class.getResourceAsStream(sensorType + "tilemap.dat")); logger.info(String.valueOf(tileMap.getCount() + " tile extents loaded")); } } if (commandLine.hasOption(Constants.PARAM_TILE_LIST)) { Collections.addAll(tiles, commandLine.getOptionValues(Constants.PARAM_TILE_LIST)); } else if (commandLine.hasOption(Constants.PARAM_TILE_LIST_FILE)) { tiles.addAll( Files.readAllLines(Paths.get(commandLine.getOptionValue(Constants.PARAM_TILE_LIST_FILE)))); } if (commandLine.hasOption(Constants.PARAM_PRODUCT_LIST)) { String[] uuids = commandLine.getOptionValues(Constants.PARAM_PRODUCT_UUID_LIST); String[] productNames = commandLine.getOptionValues(Constants.PARAM_PRODUCT_LIST); if (sensorType == SensorType.S2 && (!commandLine.hasOption(Constants.PARAM_DOWNLOAD_STORE) || ProductStore.SCIHUB.toString() .equals(commandLine.getOptionValue(Constants.PARAM_DOWNLOAD_STORE))) && (uuids == null || uuids.length != productNames.length)) { logger.error("For the list of product names a corresponding list of UUIDs has to be given!"); return -1; } for (int i = 0; i < productNames.length; i++) { ProductDescriptor productDescriptor = sensorType == SensorType.S2 ? new SentinelProductDescriptor(productNames[i]) : new LandsatProductDescriptor(productNames[i]); if (uuids != null) { productDescriptor.setId(uuids[i]); } products.add(productDescriptor); } } else if (commandLine.hasOption(Constants.PARAM_PRODUCT_LIST_FILE)) { for (String line : Files .readAllLines(Paths.get(commandLine.getOptionValue(Constants.PARAM_PRODUCT_LIST_FILE)))) { products.add(sensorType == SensorType.S2 ? new SentinelProductDescriptor(line) : new LandsatProductDescriptor(line)); } } double clouds; if (commandLine.hasOption(Constants.PARAM_CLOUD_PERCENTAGE)) { clouds = Double.parseDouble(commandLine.getOptionValue(Constants.PARAM_CLOUD_PERCENTAGE)); } else { clouds = Constants.DEFAULT_CLOUD_PERCENTAGE; } String sensingStart; if (commandLine.hasOption(Constants.PARAM_START_DATE)) { String dateString = commandLine.getOptionValue(Constants.PARAM_START_DATE); LocalDate startDate = LocalDate.parse(dateString, DateTimeFormatter.ISO_DATE); long days = ChronoUnit.DAYS.between(startDate, LocalDate.now()); sensingStart = String.format(Constants.PATTERN_START_DATE, days); } else { sensingStart = Constants.DEFAULT_START_DATE; } String sensingEnd; if (commandLine.hasOption(Constants.PARAM_END_DATE)) { String dateString = commandLine.getOptionValue(Constants.PARAM_END_DATE); LocalDate endDate = LocalDate.parse(dateString, DateTimeFormatter.ISO_DATE); long days = ChronoUnit.DAYS.between(endDate, LocalDate.now()); sensingEnd = String.format(Constants.PATTERN_START_DATE, days); } else { sensingEnd = Constants.DEFAULT_END_DATE; } int limit; if (commandLine.hasOption(Constants.PARAM_RESULTS_LIMIT)) { limit = Integer.parseInt(commandLine.getOptionValue(Constants.PARAM_RESULTS_LIMIT)); } else { limit = Constants.DEFAULT_RESULTS_LIMIT; } if (commandLine.hasOption(Constants.PARAM_DOWNLOAD_STORE)) { String value = commandLine.getOptionValue(Constants.PARAM_DOWNLOAD_STORE); if (downloader instanceof SentinelProductDownloader) { ((SentinelProductDownloader) downloader) .setDownloadStore(Enum.valueOf(ProductStore.class, value)); logger.info("Products will be downloaded from %s", value); } else { logger.warn("Argument --store will be ignored for Landsat8"); } } downloader.shouldCompress(commandLine.hasOption(Constants.PARAM_FLAG_COMPRESS)); downloader.shouldDeleteAfterCompression(commandLine.hasOption(Constants.PARAM_FLAG_DELETE)); if (commandLine.hasOption(Constants.PARAM_FILL_ANGLES)) { if (downloader instanceof SentinelProductDownloader) { ((SentinelProductDownloader) downloader) .setFillMissingAnglesMethod(Enum.valueOf(FillAnglesMethod.class, commandLine.hasOption(Constants.PARAM_FILL_ANGLES) ? commandLine.getOptionValue(Constants.PARAM_FILL_ANGLES).toUpperCase() : FillAnglesMethod.NONE.name())); } else { logger.warn("Argument --ma will be ignored for Landsat8"); } } int numPoints = areaOfInterest.getNumPoints(); tiles = tiles.stream().map(t -> t.startsWith("T") ? t.substring(1) : t).collect(Collectors.toSet()); if (products.size() == 0 && numPoints == 0 && tileMap.getCount() > 0) { Rectangle2D rectangle2D = tileMap.boundingBox(tiles); areaOfInterest.append(rectangle2D.getX(), rectangle2D.getY()); areaOfInterest.append(rectangle2D.getMaxX(), rectangle2D.getY()); areaOfInterest.append(rectangle2D.getMaxX(), rectangle2D.getMaxY()); areaOfInterest.append(rectangle2D.getX(), rectangle2D.getMaxY()); areaOfInterest.append(rectangle2D.getX(), rectangle2D.getY()); } numPoints = areaOfInterest.getNumPoints(); if (products.size() == 0 && numPoints > 0) { String searchUrl; AbstractSearch searchProvider; logger.debug("No product provided, searching on the AOI"); if (sensorType == SensorType.L8) { logger.debug("Search will be done for Landsat"); searchUrl = props.getProperty(Constants.PROPERTY_NAME_LANDSAT_SEARCH_URL, Constants.PROPERTY_NAME_DEFAULT_LANDSAT_SEARCH_URL); if (!NetUtils.isAvailable(searchUrl)) { logger.warn(searchUrl + " is not available!"); } searchProvider = new LandsatSearch(searchUrl); if (commandLine.hasOption(Constants.PARAM_START_DATE)) { searchProvider.setSensingStart(commandLine.getOptionValue(Constants.PARAM_START_DATE)); } if (commandLine.hasOption(Constants.PARAM_END_DATE)) { searchProvider.setSensingEnd(commandLine.getOptionValue(Constants.PARAM_END_DATE)); } if (commandLine.hasOption(Constants.PARAM_TILE_LIST)) { searchProvider.setTiles(tiles); } ((LandsatSearch) searchProvider).limit(limit); } else if (!commandLine.hasOption(Constants.PARAM_FLAG_SEARCH_AWS)) { logger.debug("Search will be done on SciHub"); searchUrl = props.getProperty(Constants.PROPERTY_NAME_SEARCH_URL, Constants.PROPERTY_DEFAULT_SEARCH_URL); if (!NetUtils.isAvailable(searchUrl)) { logger.warn(searchUrl + " is not available!"); searchUrl = props.getProperty(Constants.PROPERTY_NAME_SEARCH_URL_SECONDARY, Constants.PROPERTY_DEFAULT_SEARCH_URL_SECONDARY); } searchProvider = new SciHubSearch(searchUrl); SciHubSearch search = (SciHubSearch) searchProvider; if (user != null && !user.isEmpty() && pwd != null && !pwd.isEmpty()) { search = search.auth(user, pwd); } String interval = "[" + sensingStart + " TO " + sensingEnd + "]"; search.filter(Constants.SEARCH_PARAM_INTERVAL, interval).limit(limit); if (commandLine.hasOption(Constants.PARAM_RELATIVE_ORBIT)) { search.filter(Constants.SEARCH_PARAM_RELATIVE_ORBIT_NUMBER, commandLine.getOptionValue(Constants.PARAM_RELATIVE_ORBIT)); } } else { logger.debug("Search will be done on AWS"); searchUrl = props.getProperty(Constants.PROPERTY_NAME_AWS_SEARCH_URL, Constants.PROPERTY_DEFAULT_AWS_SEARCH_URL); searchProvider = new AmazonSearch(searchUrl); searchProvider.setTiles(tiles); Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt(sensingStart.replace("NOW", "").replace("DAY", ""))); searchProvider.setSensingStart(dateFormat.format(calendar.getTime())); calendar = Calendar.getInstance(); String endOffset = sensingEnd.replace("NOW", "").replace("DAY", ""); int offset = endOffset.isEmpty() ? 0 : Integer.parseInt(endOffset); calendar.add(Calendar.DAY_OF_MONTH, offset); searchProvider.setSensingEnd(dateFormat.format(calendar.getTime())); if (commandLine.hasOption(Constants.PARAM_RELATIVE_ORBIT)) { searchProvider.setOrbit( Integer.parseInt(commandLine.getOptionValue(Constants.PARAM_RELATIVE_ORBIT))); } } if (searchProvider.getTiles() == null || searchProvider.getTiles().size() == 0) { searchProvider.setAreaOfInterest(areaOfInterest); } searchProvider.setClouds(clouds); products = searchProvider.execute(); } else { logger.debug("Product name(s) present, no additional search will be performed."); } if (downloader instanceof SentinelProductDownloader) { ((SentinelProductDownloader) downloader).setFilteredTiles(tiles, commandLine.hasOption(Constants.PARAM_FLAG_UNPACKED)); } downloader.setProgressListener(batchProgressListener); downloader.setFileProgressListener(fileProgressListener); retCode = downloader.downloadProducts(products); } return retCode; }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void testTokenTypeRefreshAccessTokenInHeader() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();//w w w .jav a 2 s . com ExternalApplication externalApp = new ExternalApplication(); externalApp.setAuthor(user1); externalApp.setName("Test External Application"); externalApp.setDescription("This is a test external application"); externalApp.setRedirectUrl("http://test.url/callback"); externalApp.addScopes(externalApplicationScope); ApplicationUserSession applicationUserSession = new ApplicationUserSession(); applicationUserSession.setTokens(generateToken(applicationUserSession), generateToken(applicationUserSession)); ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user1, externalApp); applicationUserAuthorization.addSession(applicationUserSession); externalApp.addApplicationUserAuthorization(applicationUserAuthorization); String clientSecret = externalApp.getExternalId() + ":" + externalApp.getSecret(); req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8))); req.addParameter(REFRESH_TOKEN, applicationUserSession.getRefreshToken()); req.addParameter(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); req.setMethod("POST"); req.setPathInfo("/refresh_token"); try { oauthServlet.service(req, res); Assert.assertEquals("must return status OK", 200, res.getStatus()); String tokenJson = res.getContentAsString(); final JsonObject token = new JsonParser().parse(tokenJson).getAsJsonObject(); Assert.assertTrue("response must be a valid json and have access_token field", token.has(ACCESS_TOKEN) && token.get(ACCESS_TOKEN).getAsString().length() > 0); Assert.assertTrue("response must be a valid json and have " + TOKEN_TYPE + " field", token.has(TOKEN_TYPE) && token.get(TOKEN_TYPE).getAsString().length() > 0); String accessToken = token.get(ACCESS_TOKEN).getAsString(); String tokenType = token.get(TOKEN_TYPE).getAsString(); String result = target("bennu-oauth").path("test").path("test-scope").request() .header(HttpHeaders.AUTHORIZATION, tokenType + " " + accessToken).get(String.class); Assert.assertEquals("this is an endpoint with TEST scope user1", result); } catch (ServletException | IOException e) { Assert.fail(e.getMessage()); } }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditorTest.java
License:asdf
private void replaceSystemStores(String fqdn) throws Exception { KeystoreEditor keystoreEditor = new KeystoreEditor(); Assert.assertThat(keystoreEditor.getKeystore().size(), Is.is(0)); Assert.assertThat(keystoreEditor.getTruststore().size(), Is.is(0)); try (FileInputStream keystoreInputStream = new FileInputStream(systemKeystoreFile); FileInputStream truststoreInputStream = new FileInputStream(systemTruststoreFile)) { byte[] keystoreCrtBytes = IOUtils.toByteArray(keystoreInputStream); byte[] keystoreEncodedBytes = Base64.getEncoder().encode(keystoreCrtBytes); byte[] truststoreCrtBytes = IOUtils.toByteArray(truststoreInputStream); byte[] truststoreEncodedBytes = Base64.getEncoder().encode(truststoreCrtBytes); List<String> errors = keystoreEditor.replaceSystemStores(fqdn, password, password, new String(keystoreEncodedBytes), systemKeystoreFile.getName(), password, new String(truststoreEncodedBytes), systemTruststoreFile.getName()); Assert.assertThat(errors.size(), Is.is(1)); }/*w w w . j a va 2s . c o m*/ }
From source file:org.codice.ddf.security.idp.client.LogoutRequestService.java
private Response getSamlpPostLogoutResponse(String relayState, LogoutResponse samlResponse) throws WSSecurityException, SimpleSign.SignatureException { LOGGER.debug("Configuring SAML Response for POST."); Document doc = DOMUtils.createDocument(); doc.appendChild(doc.createElement("root")); LOGGER.debug("Signing SAML POST Response."); simpleSign.signSamlObject(samlResponse); LOGGER.debug("Converting SAML Response to DOM"); String assertionResponse = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(samlResponse, doc)); String encodedSamlResponse = Base64.getEncoder() .encodeToString(assertionResponse.getBytes(StandardCharsets.UTF_8)); return Response.ok(HtmlResponseTemplate.getPostPage(idpMetadata.getSingleLogoutLocation(), SamlProtocol.Type.RESPONSE, encodedSamlResponse, relayState)).build(); }
From source file:cn.nukkit.Server.java
@SuppressWarnings("unchecked") Server(MainLogger logger, final String filePath, String dataPath, String pluginPath) { Preconditions.checkState(instance == null, "Already initialized!"); currentThread = Thread.currentThread(); // Saves the current thread instance as a reference, used in Server#isPrimaryThread() instance = this; this.logger = logger; this.filePath = filePath; if (!new File(dataPath + "worlds/").exists()) { new File(dataPath + "worlds/").mkdirs(); this.getLogger().info(TextFormat.AQUA + dataPath + "worlds/ was created!"); }/*from w w w . ja v a2 s . c o m*/ if (!new File(dataPath + "players/").exists()) { new File(dataPath + "players/").mkdirs(); this.getLogger().info(TextFormat.AQUA + dataPath + "players/ was created!"); } if (!new File(pluginPath).exists()) { new File(pluginPath).mkdirs(); this.getLogger().info(TextFormat.AQUA + pluginPath + "plugins/ was created!"); this.getLogger().info(TextFormat.AQUA + dataPath + "worlds/ ?????"); } if (!new File(dataPath + "players/").exists()) { new File(dataPath + "players/").mkdirs(); this.getLogger().info(TextFormat.AQUA + dataPath + "players/ ?????"); } if (!new File(pluginPath).exists()) { new File(pluginPath).mkdirs(); this.getLogger().info(TextFormat.AQUA + pluginPath + " ?????"); } if (!new File(dataPath + "unpackedPlugins/").exists()) { new File(dataPath + "unpackedPlugins/").mkdirs(); this.getLogger().info(TextFormat.AQUA + pluginPath + "unpackedPlugins/ ?????"); } if (!new File(dataPath + "compileOrder/").exists()) { new File(dataPath + "compileOrder/").mkdirs(); this.getLogger().info(TextFormat.AQUA + pluginPath + "compileOrder/ ?????"); } this.dataPath = new File(dataPath).getAbsolutePath() + "/"; this.pluginPath = new File(pluginPath).getAbsolutePath() + "/"; this.console = new CommandReader(); //todo: VersionString ?? if (!new File(this.dataPath + "nukkit.yml").exists()) { this.getLogger().info(TextFormat.GREEN + "Welcome! Please choose a language first!"); try { String[] lines = Utils .readFile(this.getClass().getClassLoader().getResourceAsStream("lang/language.list")) .split("\n"); for (String line : lines) { this.getLogger().info(line); } } catch (IOException e) { throw new RuntimeException(e); } String fallback = BaseLang.FALLBACK_LANGUAGE; String language = null; while (language == null) { String lang = this.console.readLine(); InputStream conf = this.getClass().getClassLoader() .getResourceAsStream("lang/" + lang + "/lang.ini"); if (conf != null) { language = lang; } } InputStream advacedConf = this.getClass().getClassLoader() .getResourceAsStream("lang/" + language + "/nukkit.yml"); if (advacedConf == null) { advacedConf = this.getClass().getClassLoader() .getResourceAsStream("lang/" + fallback + "/nukkit.yml"); } try { Utils.writeFile(this.dataPath + "nukkit.yml", advacedConf); } catch (IOException e) { throw new RuntimeException(e); } } this.console.start(); this.logger.info(TextFormat.GREEN + "nukkit.yml" + TextFormat.WHITE + "?????..."); this.config = new Config(this.dataPath + "nukkit.yml", Config.YAML); this.logger .info(TextFormat.GREEN + "server.properties" + TextFormat.WHITE + "?????..."); this.properties = new Config(this.dataPath + "server.properties", Config.PROPERTIES, new ConfigSection() { { put("motd", "Jupiter Server For Minecraft: PE"); put("server-port", 19132); put("server-ip", "0.0.0.0"); put("view-distance", 10); put("white-list", false); put("achievements", true); put("announce-player-achievements", true); put("spawn-protection", 16); put("max-players", 20); put("allow-flight", false); put("spawn-animals", true); put("spawn-mobs", true); put("gamemode", 0); put("force-gamemode", false); put("hardcore", false); put("pvp", true); put("difficulty", 1); put("generator-settings", ""); put("level-name", "world"); put("level-seed", ""); put("level-type", "DEFAULT"); put("enable-query", true); put("enable-rcon", false); put("rcon.password", Base64.getEncoder() .encodeToString(UUID.randomUUID().toString().replace("-", "").getBytes()).substring(3, 13)); put("auto-save", true); put("force-resources", false); } }); this.logger.info(TextFormat.GREEN + "jupiter.yml" + TextFormat.WHITE + "?????..."); if (!new File(this.dataPath + "jupiter.yml").exists()) { InputStream advacedConf = this.getClass().getClassLoader().getResourceAsStream("lang/jpn/jupiter.yml"); if (advacedConf == null) this.getLogger().error( "Jupiter.yml????????????????"); try { Utils.writeFile(this.dataPath + "jupiter.yml", advacedConf); } catch (IOException e) { throw new RuntimeException(e); } } this.loadJupiterConfig(); InputStream advacedConf1 = this.getClass().getClassLoader().getResourceAsStream("lang/jpn/jupiter.yml"); if (advacedConf1 == null) this.getLogger().error( "Jupiter.yml????????????????"); try { Utils.writeFile(this.dataPath + "jupiter1.yml", advacedConf1); } catch (IOException e) { throw new RuntimeException(e); } //get Jupiter.yml in the jar Config jupiter = new Config(this.getDataPath() + "jupiter1.yml"); Map<String, Object> jmap = jupiter.getAll(); Collection<Object> objj = jmap.values(); Object[] objj1 = objj.toArray(); Object objj2 = objj1[objj1.length - 1]; BidiMap mapp = new DualHashBidiMap(jmap); String keyy = (String) mapp.getKey(objj2); //get JupiterConfig key in the delectory Collection<Object> obj = jupiterconfig.values(); Object[] obj1 = obj.toArray(); Object obj2 = obj1[obj1.length - 1]; BidiMap map = new DualHashBidiMap(jupiterconfig); String key1 = (String) map.getKey(obj2); //delete jupiter1.yml File jf = new File(this.dataPath + "jupiter1.yml"); jf.delete(); if (!keyy.equals(key1)) { File conf = new File(this.dataPath + "jupiter.yml"); conf.delete(); InputStream advacedConf = this.getClass().getClassLoader().getResourceAsStream("lang/jpn/jupiter.yml"); if (advacedConf == null) this.getLogger().error( "Jupiter.yml????????????????"); try { Utils.writeFile(this.dataPath + "jupiter.yml", advacedConf); } catch (IOException ex) { throw new RuntimeException(ex); } this.getLogger() .info(TextFormat.AQUA + "Jupiter.yml????????????"); this.loadJupiterConfig(); } if (this.getJupiterConfigBoolean("destroy-block-particle")) { Level.sendDestroyParticle = true; } else { Level.sendDestroyParticle = false; } this.forceLanguage = (Boolean) this.getConfig("settings.force-language", false); this.baseLang = new BaseLang((String) this.getConfig("settings.language", BaseLang.FALLBACK_LANGUAGE)); this.logger.info(this.getLanguage().translateString("language.selected", new String[] { getLanguage().getName(), getLanguage().getLang() })); this.logger.info(this.getLanguage().translateString("nukkit.server.start", TextFormat.AQUA + this.getVersion() + TextFormat.WHITE)); Object poolSize = this.getConfig("settings.async-workers", "auto"); if (!(poolSize instanceof Integer)) { try { poolSize = Integer.valueOf((String) poolSize); } catch (Exception e) { poolSize = Math.max(Runtime.getRuntime().availableProcessors() + 1, 4); } } ServerScheduler.WORKERS = (int) poolSize; int threshold; try { threshold = Integer.valueOf(String.valueOf(this.getConfig("network.batch-threshold", 256))); } catch (Exception e) { threshold = 256; } if (threshold < 0) { threshold = -1; } Network.BATCH_THRESHOLD = threshold; this.networkCompressionLevel = (int) this.getConfig("network.compression-level", 7); this.networkCompressionAsync = (boolean) this.getConfig("network.async-compression", true); this.networkCompressionLevel = (int) this.getConfig("network.compression-level", 7); this.networkCompressionAsync = (boolean) this.getConfig("network.async-compression", true); this.autoTickRate = (boolean) this.getConfig("level-settings.auto-tick-rate", true); this.autoTickRateLimit = (int) this.getConfig("level-settings.auto-tick-rate-limit", 20); this.alwaysTickPlayers = (boolean) this.getConfig("level-settings.always-tick-players", false); this.baseTickRate = (int) this.getConfig("level-settings.base-tick-rate", 1); this.scheduler = new ServerScheduler(); if (this.getPropertyBoolean("enable-rcon", false)) { this.rcon = new RCON(this, this.getPropertyString("rcon.password", ""), (!this.getIp().equals("")) ? this.getIp() : "0.0.0.0", this.getPropertyInt("rcon.port", this.getPort())); } this.entityMetadata = new EntityMetadataStore(); this.playerMetadata = new PlayerMetadataStore(); this.levelMetadata = new LevelMetadataStore(); this.operators = new Config(this.dataPath + "ops.txt", Config.ENUM); this.whitelist = new Config(this.dataPath + "white-list.txt", Config.ENUM); this.banByName = new BanList(this.dataPath + "banned-players.json"); this.banByName.load(); this.banByIP = new BanList(this.dataPath + "banned-ips.json"); this.banByIP.load(); this.maxPlayers = this.getPropertyInt("max-players", 20); this.setAutoSave(this.getPropertyBoolean("auto-save", true)); if (this.getPropertyBoolean("hardcore", false) && this.getDifficulty() < 3) { this.setPropertyInt("difficulty", 3); } Nukkit.DEBUG = (int) this.getConfig("debug.level", 1); if (this.logger instanceof MainLogger) { this.logger.setLogDebug(Nukkit.DEBUG > 1); } this.logger.info(this.getLanguage().translateString("nukkit.server.networkStart", new String[] { this.getIp().equals("") ? "*" : this.getIp(), String.valueOf(this.getPort()) })); this.serverID = UUID.randomUUID(); this.network = new Network(this); this.network.setName(this.getMotd()); this.logger.info(this.getLanguage().translateString("nukkit.server.info", this.getName(), TextFormat.YELLOW + this.getNukkitVersion() + TextFormat.WHITE, TextFormat.AQUA + this.getCodename() + TextFormat.WHITE, this.getApiVersion())); this.logger.info(this.getLanguage().translateString("nukkit.server.license", this.getName())); this.consoleSender = new ConsoleCommandSender(); this.commandMap = new SimpleCommandMap(this); this.registerEntities(); this.registerBlockEntities(); Block.init(); Enchantment.init(); Item.init(); Biome.init(); Effect.init(); Potion.init(); Attribute.init(); this.craftingManager = new CraftingManager(); this.resourcePackManager = new ResourcePackManager(new File(Nukkit.DATA_PATH, "resource_packs")); this.pluginManager = new PluginManager(this, this.commandMap); this.pluginManager.subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this.consoleSender); this.pluginManager.registerInterface(JavaPluginLoader.class); this.queryRegenerateEvent = new QueryRegenerateEvent(this, 5); this.network.registerInterface(new RakNetInterface(this)); Calendar now = Calendar.getInstance(); int y = now.get(Calendar.YEAR); int mo = now.get(Calendar.MONTH) + 1; int d = now.get(Calendar.DATE); int h = now.get(Calendar.HOUR_OF_DAY); int m = now.get(Calendar.MINUTE); int s = now.get(Calendar.SECOND); this.logger.info(TextFormat.AQUA + "=================================================================================="); this.logger.info(TextFormat.AQUA + ""); this.logger.info( " || || || || || || || ||"); this.logger.info(" | | | | | | | || | | | | | | | | || |"); this.logger.info(" | | | | | | | | | | | | | | | | "); this.logger.info(" _| | | | | | | | | | | | | | | | "); this.logger.info(" |____| |_____| |_| |__| |__| | | |_| _|"); this.logger.info(""); this.logger.info(TextFormat.AQUA + ""); this.logger.info(TextFormat.AQUA + "----------------------------------------------------------------------------------"); this.logger.info(TextFormat.GREEN + "Jupiter - Nukkit Fork"); this.logger.info(TextFormat.YELLOW + "JupiterDevelopmentTeam "); this.logger.info(TextFormat.AQUA + "----------------------------------------------------------------------------------"); this.logger.info( ": " + TextFormat.BLUE + y + "/" + mo + "/" + d + " " + h + "" + m + "" + s + ""); this.logger.info("???: " + TextFormat.GREEN + this.getMotd()); this.logger.info("ip: " + TextFormat.GREEN + this.getIp()); this.logger.info("?: " + TextFormat.GREEN + this.getPort()); this.logger.info("Nukkit?: " + TextFormat.LIGHT_PURPLE + this.getNukkitVersion()); this.logger.info("API?: " + TextFormat.LIGHT_PURPLE + this.getApiVersion()); this.logger.info("?: " + TextFormat.LIGHT_PURPLE + this.getCodename()); this.logger.info(TextFormat.AQUA + "=================================================================================="); if (this.getJupiterConfigBoolean("jupiter-compiler-mode")) { this.logger.info(TextFormat.YELLOW + "----------------------------------------------------------------------------------"); getLogger().info(TextFormat.AQUA + "?????..."); File f = new File(dataPath + "compileOrder/"); File[] list = f.listFiles(); for (int i = 0; i < list.length; i++) { if (new PluginCompiler().Compile(list[i])) getLogger().info(list[i].toPath().toString() + " :" + TextFormat.GREEN + ""); else getLogger().info(list[i].toPath().toString() + " :" + TextFormat.RED + ""); } this.logger.info(TextFormat.YELLOW + "----------------------------------------------------------------------------------"); } this.logger.info(TextFormat.LIGHT_PURPLE + "----------------------------------------------------------------------------------"); getLogger().info(TextFormat.AQUA + "?????..."); this.pluginManager.loadPlugins(this.pluginPath); this.enablePlugins(PluginLoadOrder.STARTUP); LevelProviderManager.addProvider(this, Anvil.class); LevelProviderManager.addProvider(this, McRegion.class); LevelProviderManager.addProvider(this, LevelDB.class); Generator.addGenerator(Flat.class, "flat", Generator.TYPE_FLAT); Generator.addGenerator(Normal.class, "normal", Generator.TYPE_INFINITE); Generator.addGenerator(Normal.class, "default", Generator.TYPE_INFINITE); Generator.addGenerator(Nether.class, "nether", Generator.TYPE_NETHER); //todo: add old generator and hell generator for (String name : ((Map<String, Object>) this.getConfig("worlds", new HashMap<>())).keySet()) { if (!this.loadLevel(name)) { long seed; try { seed = ((Integer) this.getConfig("worlds." + name + ".seed")).longValue(); } catch (Exception e) { seed = System.currentTimeMillis(); } Map<String, Object> options = new HashMap<>(); String[] opts = ((String) this.getConfig("worlds." + name + ".generator", Generator.getGenerator("default").getSimpleName())).split(":"); Class<? extends Generator> generator = Generator.getGenerator(opts[0]); if (opts.length > 1) { String preset = ""; for (int i = 1; i < opts.length; i++) { preset += opts[i] + ":"; } preset = preset.substring(0, preset.length() - 1); options.put("preset", preset); } this.generateLevel(name, seed, generator, options); } } if (this.getDefaultLevel() == null) { String defaultName = this.getPropertyString("level-name", "world"); if (defaultName == null || "".equals(defaultName.trim())) { this.getLogger().warning("level-name cannot be null, using default"); defaultName = "world"; this.setPropertyString("level-name", defaultName); } if (!this.loadLevel(defaultName)) { long seed; String seedString = String.valueOf(this.getProperty("level-seed", System.currentTimeMillis())); try { seed = Long.valueOf(seedString); } catch (NumberFormatException e) { seed = seedString.hashCode(); } this.generateLevel(defaultName, seed == 0 ? System.currentTimeMillis() : seed); } this.setDefaultLevel(this.getLevelByName(defaultName)); } this.properties.save(true); if (this.getDefaultLevel() == null) { this.getLogger().emergency(this.getLanguage().translateString("nukkit.level.defaultError")); this.forceShutdown(); return; } if ((int) this.getConfig("ticks-per.autosave", 6000) > 0) { this.autoSaveTicks = (int) this.getConfig("ticks-per.autosave", 6000); } this.enablePlugins(PluginLoadOrder.POSTWORLD); this.logger.info(TextFormat.LIGHT_PURPLE + "----------------------------------------------------------------------------------"); this.start(); }
From source file:com.mercer.cpsg.swarm.oidc.deployment.OIDCAuthenticationMechanism.java
protected String persistState(String state, HttpServerExchange exchange) throws Exception { // if NoOnce is checked based on session value restore redirect URL the // same way/* ww w . j a va2s . com*/ if (oidcProvider.isCheckNonce()) { getSession(exchange).setAttribute(LOCATION_KEY, state); return state; } else { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, stateKey); byte[] secureReturnURL = cipher.doFinal(state.getBytes()); return Base64.getEncoder().encodeToString(secureReturnURL); } }
From source file:SdkUnitTests.java
@Test public void DownLoadEnvelopeDocumentsTest() { byte[] fileBytes = null; try {/*from w ww .j a v a 2 s .c om*/ // String currentDir = new java.io.File(".").getCononicalPath(); String currentDir = System.getProperty("user.dir"); Path path = Paths.get(currentDir + SignTest1File); fileBytes = Files.readAllBytes(path); } catch (IOException ioExcp) { Assert.assertEquals(null, ioExcp); } // create an envelope to be signed EnvelopeDefinition envDef = new EnvelopeDefinition(); envDef.setEmailSubject("DownLoadEnvelopeDocumentsTest"); envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope."); // add a document to the envelope Document doc = new Document(); String base64Doc = Base64.getEncoder().encodeToString(fileBytes); doc.setDocumentBase64(base64Doc); doc.setName("TestFile.pdf"); doc.setDocumentId("1"); List<Document> docs = new ArrayList<Document>(); docs.add(doc); envDef.setDocuments(docs); // Add a recipient to sign the document Signer signer = new Signer(); signer.setEmail(UserName); String name = "Pat Developer"; signer.setName(name); signer.setRecipientId("1"); // this value represents the client's unique identifier for the signer String clientUserId = "2939"; signer.setClientUserId(clientUserId); // Create a SignHere tab somewhere on the document for the signer to sign SignHere signHere = new SignHere(); signHere.setDocumentId("1"); signHere.setPageNumber("1"); signHere.setRecipientId("1"); signHere.setXPosition("100"); signHere.setYPosition("100"); List<SignHere> signHereTabs = new ArrayList<SignHere>(); signHereTabs.add(signHere); Tabs tabs = new Tabs(); tabs.setSignHereTabs(signHereTabs); signer.setTabs(tabs); // Above causes issue envDef.setRecipients(new Recipients()); envDef.getRecipients().setSigners(new ArrayList<Signer>()); envDef.getRecipients().getSigners().add(signer); // send the envelope (otherwise it will be "created" in the Draft folder envDef.setStatus("sent"); try { ApiClient apiClient = new ApiClient(); apiClient.setBasePath(BaseUrl); String creds = createAuthHeaderCreds(UserName, Password, IntegratorKey); apiClient.addDefaultHeader("X-DocuSign-Authentication", creds); Configuration.setDefaultApiClient(apiClient); AuthenticationApi authApi = new AuthenticationApi(); LoginInformation loginInfo = authApi.login(); Assert.assertNotSame(null, loginInfo); Assert.assertNotNull(loginInfo.getLoginAccounts()); Assert.assertTrue(loginInfo.getLoginAccounts().size() > 0); List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts(); Assert.assertNotNull(loginAccounts.get(0).getAccountId()); String accountId = loginInfo.getLoginAccounts().get(0).getAccountId(); EnvelopesApi envelopesApi = new EnvelopesApi(); EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef); Assert.assertNotNull(envelopeSummary); EnvelopeId = envelopeSummary.getEnvelopeId(); Assert.assertNotNull(EnvelopeId); System.out.println("EnvelopeSummary: " + envelopeSummary); byte[] pdfBytes = envelopesApi.getDocument(accountId, EnvelopeId, "combined"); try { File pdfFile = File.createTempFile("ds_", "pdf", null); FileOutputStream fos = new FileOutputStream(pdfFile); fos.write(pdfBytes); // show the PDF Desktop.getDesktop().open(pdfFile); } catch (Exception ex) { Assert.fail("Could not create pdf File"); } } catch (ApiException ex) { System.out.println("Exception: " + ex); Assert.assertEquals(null, ex); } }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditorTest.java
License:asdf
@Test public void testAddCert() throws KeystoreEditor.KeystoreEditorException, IOException { KeystoreEditor keystoreEditor = new KeystoreEditor(); FileInputStream fileInputStream = new FileInputStream(crtFile); byte[] crtBytes = IOUtils.toByteArray(fileInputStream); IOUtils.closeQuietly(fileInputStream); keystoreEditor.addTrustedCertificate("asdf", password, "", new String(Base64.getEncoder().encode(crtBytes)), KeystoreEditor.PEM_TYPE, crtFile.toString()); List<Map<String, Object>> truststore = keystoreEditor.getTruststore(); Assert.assertThat(truststore.size(), Is.is(1)); Assert.assertThat(truststore.get(0).get("alias"), Is.is("asdf")); List<Map<String, Object>> keystore = keystoreEditor.getKeystore(); Assert.assertThat(keystore.size(), Is.is(0)); }