List of usage examples for java.util Base64 getDecoder
public static Decoder getDecoder()
From source file:com.streamsets.datacollector.publicrestapi.CredentialsDeploymentResource.java
private void handleKerberos(CredentialsBeanJson credentialsBeanJson) throws IOException { if (!StringUtils.isEmpty(credentialsBeanJson.getPrincipal())) { LOG.info("Kerberos credentials found, deploying.."); byte[] decodedKeytab = Base64.getDecoder().decode(credentialsBeanJson.getKeytab()); java.nio.file.Path keytab = Paths.get(runtimeInfo.getConfigDir(), "sdc.keytab"); Files.write(keytab, decodedKeytab, CREATE, WRITE); File sdcProperties = new File(runtimeInfo.getConfigDir(), "sdc.properties"); Configuration conf = new Configuration(); try (FileReader reader = new FileReader(sdcProperties)) { conf.load(reader);/*w w w.j av a 2 s . c om*/ } conf.set("kerberos.client.principal", credentialsBeanJson.getPrincipal()); conf.set("kerberos.client.enabled", true); conf.set("kerberos.client.keytab", "sdc.keytab"); try (FileWriter writer = new FileWriter(sdcProperties)) { conf.save(writer); } LOG.info("Kerberos credentials deployed."); } }
From source file:com.nike.cerberus.operation.gateway.CreateCloudFrontSecurityGroupUpdaterLambdaOperation.java
/** * Forces the lambda to run and sync the IPs for CloudFront to be white listed on the origin elb */// ww w . j ava 2 s . c o m private void forceLambdaToUpdateSgs(String arn) { String json; try { json = IOUtils.toString(this.getClass().getClassLoader() .getResourceAsStream("aws-ip-space-change-sns-sample-event.json")); } catch (IOException e) { String msg = "Failed to load mock sns message, to force Lambda first run"; logger.error(msg, e); throw new RuntimeException(msg, e); } // this will fail InvokeResult result = awsLambda.invoke(new InvokeRequest().withFunctionName(arn) .withPayload(String.format(json, BAD_HASH)).withLogType(LogType.Tail)); // collect the error so we can parse it for the latest hash String log = new String(Base64.getDecoder().decode(result.getLogResult()), Charset.forName("UTF-8")); Pattern pattern = Pattern.compile("MD5 Mismatch: got\\s(.*?)\\sexp.*?"); Matcher matcher = pattern.matcher(log); boolean matched = matcher.find(); if (!matched) { throw new RuntimeException("failed to extract hash from: " + log); } String realHash = matcher.group(1); result = awsLambda.invoke(new InvokeRequest().withFunctionName(arn) .withPayload(String.format(json, realHash)).withLogType(LogType.Tail)); logger.info("Forcing the Lambda to run and update Security Groups"); logger.info(new String(result.getPayload().array(), Charset.forName("UTF-8"))); }
From source file:org.jaqpot.algorithm.resource.Standarization.java
@POST @Path("prediction") public Response prediction(PredictionRequest request) { try {/*from w w w.ja va 2s . com*/ if (request.getDataset().getDataEntry().isEmpty() || request.getDataset().getDataEntry().get(0).getValues().isEmpty()) { return Response .status(Response.Status.BAD_REQUEST).entity(ErrorReportFactory .badRequest("Dataset is empty", "Cannot make predictions on empty dataset")) .build(); } List<String> features = request.getDataset().getDataEntry().stream().findFirst().get().getValues() .keySet().stream().collect(Collectors.toList()); String base64Model = (String) request.getRawModel(); byte[] modelBytes = Base64.getDecoder().decode(base64Model); ByteArrayInputStream bais = new ByteArrayInputStream(modelBytes); ObjectInput in = new ObjectInputStream(bais); ScalingModel model = (ScalingModel) in.readObject(); in.close(); bais.close(); List<LinkedHashMap<String, Object>> predictions = new ArrayList<>(); for (DataEntry dataEntry : request.getDataset().getDataEntry()) { LinkedHashMap<String, Object> data = new LinkedHashMap<>(); for (String feature : features) { Double stdev = model.getMaxValues().get(feature); Double mean = model.getMinValues().get(feature); Double value = Double.parseDouble(dataEntry.getValues().get(feature).toString()); if (stdev != null && stdev != 0.0 && mean != null) { value = (value - mean) / stdev; } else { value = 1.0; } data.put("Standarized " + feature, value); } predictions.add(data); } PredictionResponse response = new PredictionResponse(); response.setPredictions(predictions); return Response.ok(response).build(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } }
From source file:de.nava.informa.utils.ParserUtils.java
public static String decodeBase64(String s) { return new String(Base64.getDecoder().decode(s)); }
From source file:org.codice.ddf.security.handler.basic.AbstractBasicAuthenticationHandler.java
/** * Extract the Authorization header and parse into a username/password token. * * @param authHeader the authHeader string from the HTTP request * @return the initialized UPAuthenticationToken for this username, password, realm combination (or null) *//*from ww w . ja v a 2 s. c om*/ protected BaseAuthenticationToken extractAuthInfo(String authHeader, String realm) { BaseAuthenticationToken token = null; authHeader = authHeader.trim(); String[] parts = authHeader.split(" "); if (parts.length == 2) { String authType = parts[0]; String authInfo = parts[1]; if (authType.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC)) { byte[] decode = Base64.getDecoder().decode(authInfo); if (decode != null) { String userPass = new String(decode, StandardCharsets.UTF_8); String[] authComponents = userPass.split(":"); if (authComponents.length == 2) { token = getBaseAuthenticationToken(realm, authComponents[0], authComponents[1]); } else if ((authComponents.length == 1) && (userPass.endsWith(":"))) { token = getBaseAuthenticationToken(realm, authComponents[0], ""); } } } } return token; }
From source file:dk.dma.msinm.user.security.SecurityServletFilter.java
/** * If the request contains a Basic authentication header, the user will be logged in for this request * using the specified credentials./*w ww. j av a2 s. c o m*/ * <p> * If the authentication fails, this methods does nothing. It is left to the handler of the request, * say a Rest endpoint, to throw an error if security requirements are not met. * * @param request the servlet request * @return the request */ private HttpServletRequest attemptBasicAuthLogin(HttpServletRequest request) { try { String token = getAuthHeaderToken(request, BASIC_AUTH); if (token != null) { String[] cred = new String(Base64.getDecoder().decode(token), "UTF-8").split(":"); request = SecurityUtils.login(userService, request, cred[0], cred[1]); log.trace("Found Basic Auth user " + request.getUserPrincipal().getName()); } } catch (Exception ex) { request.setAttribute(AUTH_ERROR_ATTR, HttpServletResponse.SC_UNAUTHORIZED); log.warn("Failed logging in using Basic Authentication"); } return request; }
From source file:com.srotya.sidewinder.cluster.storage.ClusteredMemStorageEngine.java
/** * Decode proxy hops to the dbname so that recursion information can be * communicated to the smaller caller./*from ww w .jav a 2s . c om*/ * * This approach is used break recursion cycles when sending proxied * commands through the cluster. * * @param proxies * @param dbName * @return */ @SuppressWarnings("unchecked") public static String decodeDbAndProxyNames(List<String> proxies, String dbName) { String[] split = dbName.split("\\|"); if (split.length > 1 && proxies != null) { dbName = split[1]; byte[] decode = Base64.getDecoder().decode(split[0]); Input input = new Input(decode); proxies.addAll(kryoThreadLocal.get().readObject(input, ArrayList.class)); } return dbName; }
From source file:org.niord.web.map.MessageMapImageRestService.java
/** * Updates the map image with a custom image *//* w w w . ja va 2 s. c om*/ @PUT @javax.ws.rs.Path("/{folder:.+}") @Consumes("application/json;charset=UTF-8") @Produces("text/plain") @RolesAllowed(Roles.EDITOR) public String updateMessageMapImage(@PathParam("folder") String path, String image) throws Exception { // Validate that the path is a temporary repository folder path Path folder = repositoryService.validateTempRepoPath(path); if (!image.toLowerCase().startsWith(UPLOADED_IMAGE_PREFIX)) { throw new WebApplicationException(400); } // Decode the base-64 encoded image data image = image.substring(UPLOADED_IMAGE_PREFIX.length()); byte[] data = Base64.getDecoder().decode(image); // Construct the file path for the message String imageName = String.format("custom_thumb_%d.png", messageMapImageGenerator.getMapImageSize()); Path imageRepoPath = folder.resolve(imageName); messageMapImageGenerator.generateMessageMapImage(data, imageRepoPath); // Return the new thumbnail path return path + "/" + imageName; }
From source file:org.springframework.session.data.couchbase.CouchbaseSession.java
@SuppressWarnings("unchecked") public Object stringToObject(String string) throws IOException, ClassNotFoundException { if (string == null) { return null; }/*from w ww.ja v a2 s.c om*/ byte[] bytes = Base64.getDecoder().decode(string.getBytes()); Object object = null; ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); object = objectInputStream.readObject(); return object; }
From source file:org.locationtech.geomesa.bigtable.spark.BigtableInputFormatBase.java
public static BigtableExtendedScan stringToScan(String encoded) throws IOException { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(encoded))); int tableLength = dis.readInt(); byte[] table = new byte[tableLength]; dis.read(table, 0, tableLength);/*w ww . j av a 2 s .c om*/ int available = dis.available(); byte[] rowsetbytes = new byte[available]; dis.readFully(rowsetbytes); RowSet rs = RowSet.parseFrom(rowsetbytes); BigtableExtendedScan scan = new BigtableExtendedScan(); rs.getRowRangesList().forEach(scan::addRange); scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, table); return scan; }