List of usage examples for java.util Base64 getEncoder
public static Encoder getEncoder()
From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.v2.KubernetesV2Utils.java
static public String createSecret(KubernetesAccount account, String namespace, String clusterName, String name, List<SecretMountPair> files) { Map<String, String> contentMap = new HashMap<>(); for (SecretMountPair pair : files) { String contents;/*from w w w . ja va 2 s.c o m*/ try { contents = new String( Base64.getEncoder().encode(IOUtils.toByteArray(new FileInputStream(pair.getContents())))); } catch (IOException e) { throw new HalException(Problem.Severity.FATAL, "Failed to read required config file: " + pair.getContents().getAbsolutePath() + ": " + e.getMessage(), e); } contentMap.put(pair.getName(), contents); } name = name + "-" + Math.abs(contentMap.hashCode()); TemplatedResource secret = new JinjaJarResource("/kubernetes/manifests/secret.yml"); Map<String, Object> bindings = new HashMap<>(); bindings.put("files", contentMap); bindings.put("name", name); bindings.put("namespace", namespace); bindings.put("clusterName", clusterName); secret.extendBindings(bindings); apply(account, secret.toString()); return name; }
From source file:org.wso2.identity.iml.dsl.mediators.SAMLResponseBuilder.java
private String buildSAMLResponse(AuthnRequest authnRequest, CarbonMessage carbonMessage) throws ConfigurationException, ParseException { String destination = "http://localhost:8080/travelocity.com/home.jsp"; Response response = new ResponseBuilder().buildObject(); response.setIssuer(IMLUtils.getIssuer()); response.setID(UUID.randomUUID().toString()); String inResponseTo = authnRequest.getID(); response.setInResponseTo(inResponseTo); response.setDestination(authnRequest.getAssertionConsumerServiceURL()); Status status = new StatusBuilder().buildObject(); StatusCode statCode = new StatusCodeBuilder().buildObject(); statCode.setValue("urn:oasis:names:tc:SAML:2.0:status:Success"); status.setStatusCode(statCode);//from ww w. j av a2s. c o m response.setVersion(SAMLVersion.VERSION_20); DateTime issueInstant = new DateTime(); DateTime notOnOrAfter = new DateTime(issueInstant.getMillis() + 100 * 60 * 1000); response.setIssueInstant(issueInstant); //Build assertion DateTime currentTime = new DateTime(); Assertion assertion = new AssertionBuilder().buildObject(); assertion.setID(UUID.randomUUID().toString()); assertion.setVersion(SAMLVersion.VERSION_20); assertion.setIssuer(IMLUtils.getIssuer()); assertion.setIssueInstant(currentTime); Subject subject = new SubjectBuilder().buildObject(); NameID nameId = new NameIDBuilder().buildObject(); //TODO Get NameID value from JWT SignedJWT signedJWT = (SignedJWT) carbonMessage.getProperty("signedJWT"); nameId.setValue(signedJWT.getJWTClaimsSet().getSubject()); nameId.setFormat(NameID.EMAIL); subject.setNameID(nameId); SubjectConfirmation subjectConfirmation = new SubjectConfirmationBuilder().buildObject(); subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer"); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationDataBuilder().buildObject(); subjectConfirmationData.setInResponseTo(inResponseTo); subjectConfirmationData.setNotBefore(notOnOrAfter); subjectConfirmationData.setRecipient(destination); subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData); assertion.setSubject(subject); AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject(); authnStatement.setAuthnInstant(new DateTime()); AuthnContext authnContext = new AuthnContextBuilder().buildObject(); AuthnContextClassRef authnContextClassRef = new AuthnContextClassRefBuilder().buildObject(); authnContextClassRef.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX); authnContext.setAuthnContextClassRef(authnContextClassRef); authnStatement.setAuthnContext(authnContext); authnStatement.setSessionIndex((String) carbonMessage.getProperty("sessionID")); assertion.getAuthnStatements().add(authnStatement); Map<String, String> claims = new HashMap<>(); if (claims != null && !claims.isEmpty()) { AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject(); //TODO add attributes } Conditions conditions = new ConditionsBuilder().buildObject(); conditions.setNotBefore(currentTime); conditions.setNotOnOrAfter(notOnOrAfter); AudienceRestriction audienceRestriction = new AudienceRestrictionBuilder().buildObject(); Audience audience = new AudienceBuilder().buildObject(); audience.setAudienceURI("travelocity.com"); audienceRestriction.getAudiences().add(audience); //TODO Handle multiple audience conditions.getAudienceRestrictions().add(audienceRestriction); assertion.setConditions(conditions); boolean doSignAssertion = false; boolean doEncryptAssertion = false; boolean doSignResponse = false; if (doSignAssertion) { //TODO Assertion signing } if (doEncryptAssertion) { //TODO Assertion encrypting } if (doSignResponse) { //TODO Response signing } response.getAssertions().add(assertion); String samlResponse = marshall(response); String encodedResponse = Base64.getEncoder().encodeToString(samlResponse.getBytes(StandardCharsets.UTF_8)); return encodedResponse; }
From source file:org.hawkular.agent.monitor.util.Util.java
/** * Encodes a string using Base64 encoding. * * @param plainTextString the string to encode * @return the given string as a Base64 encoded string. *///w ww .j av a 2s.c o m public static String base64Encode(String plainTextString) { String encoded = new String(Base64.getEncoder().encode(plainTextString.getBytes())); return encoded; }
From source file:com.orange.clara.cloud.servicedbdumper.controllers.ManagerControllerTest.java
@Test public void when_user_wants_to_download_dump_file_and_user_password_are_correct_it_should_download_the_content() throws Exception { //format to basic auth header String login = userShowable + ":" + passwordShowable; String loginEncoded = Base64.getEncoder().encodeToString(login.getBytes()); mockMvc.perform(/*w w w. j a va 2 s .c o m*/ get(Routes.MANAGE_ROOT + Routes.DOWNLOAD_DUMP_FILE_ROOT + "/" + databaseDumpFileShowable.getId()) .header("Authorization", "Basic " + loginEncoded)) .andExpect(status().isOk()).andExpect(content().string(textForFiler)); }
From source file:ch.ifocusit.livingdoc.plugin.publish.confluence.client.ConfluenceRestClient.java
<T> T sendRequest(HttpRequestBase httpRequest, Function<HttpResponse, T> responseHandler) { CloseableHttpResponse response = null; try {//from w ww . j a v a 2 s. co m final String encodedCredentials = "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes()); httpRequest.addHeader("Accept", "application/json"); httpRequest.addHeader("Authorization", encodedCredentials); response = this.httpClient.execute(httpRequest, httpContext()); return responseHandler.apply(response); } catch (IOException e) { throw new RuntimeException("Request could not be sent" + httpRequest, e); } finally { try { if (response != null) { response.close(); } } catch (IOException ignored) { } } }
From source file:com.amazonaws.sample.entitlement.services.AdministrationService.java
/** * Delete user/*ww w . ja va2 s. co m*/ * @throws ApplicationBadStateException if the application the current request is for is in an error state */ public void deleteUser(String email) throws ApplicationBadStateException { try { String cognitoIdentityId; String base64EncEmail; try { base64EncEmail = Base64.getEncoder().withoutPadding().encodeToString(email.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new ApplicationBadStateException("Don't know how to handle authorization."); } try { LookupDeveloperIdentityRequest req = new LookupDeveloperIdentityRequest().withMaxResults(1) .withDeveloperUserIdentifier(base64EncEmail).withIdentityPoolId(awsCognitoIdentityPool); LookupDeveloperIdentityResult res = cognitoIdentityClient.lookupDeveloperIdentity(req); cognitoIdentityId = res.getIdentityId(); } catch (NotAuthorizedException e) { log.error("No Cognito Developer Identity exists for " + email + " " + e); throw new ApplicationBadStateException(""); } UnlinkDeveloperIdentityRequest unlinkRequest = new UnlinkDeveloperIdentityRequest() .withIdentityId(cognitoIdentityId).withDeveloperUserIdentifier(base64EncEmail) .withIdentityPoolId(awsCognitoIdentityPool) .withDeveloperProviderName(awsCognitoDeveloperProviderName); cognitoIdentityClient.unlinkDeveloperIdentity(unlinkRequest); entitlementServiceUserTable.deleteItem("id", cognitoIdentityId); } catch (AmazonServiceException e) { if (e.getErrorType().equals(AmazonServiceException.ErrorType.Service)) { log.error("An error occurred while getting data from DynamoDB: " + e); } throw e; } }
From source file:com.thoughtworks.go.server.service.plugins.AnalyticsPluginAssetsServiceTest.java
private String testDataZipArchive() throws IOException { return new String(Base64.getEncoder() .encode(IOUtils.toByteArray(getClass().getResourceAsStream("/plugin_cache_test.zip")))); }
From source file:com.dulion.astatium.mesh.shredder.ContextManager.java
private void logTree() { String space = Strings.repeat(" ", 40); Context[] array = new Context[contextMap.size()]; contextMap.values().toArray(array);//from w w w. j av a2 s.c om sort(array, Context.byContext()); int maxSize = 0; for (Context context : array) { Location location = context.getRange().getLower(); BigInteger numerator = ((RationalLocation) location).getNumerator(); String num = Base64.getEncoder().encodeToString(numerator.toByteArray()); int numSize = numerator.bitLength() / 8 + 1; if (numSize > maxSize) { maxSize = numSize; } BigInteger denominator = ((RationalLocation) location).getDenominator(); String den = Base64.getEncoder().encodeToString(denominator.toByteArray()); int denSize = denominator.bitLength() / 8 + 1; if (denSize > maxSize) { maxSize = denSize; } int depth = context.getDepth() - 1; String indent = space.substring(0, depth << 1); LOG.info(String.format("[%15s|%15s]%s", num, den, indent + context.getName())); } LOG.info("Max byte size: {}", maxSize); }
From source file:com.thoughtworks.go.util.FileUtil.java
public static String sha1Digest(File file) { try (InputStream is = new BufferedInputStream(new FileInputStream(file))) { byte[] hash = DigestUtils.sha1(is); return Base64.getEncoder().encodeToString(hash); } catch (IOException e) { throw ExceptionUtils.bomb(e); }//w ww. j ava 2 s. c o m }
From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.CswMarshallHelper.java
static void writeValue(HierarchicalStreamWriter writer, MarshallingContext context, AttributeDescriptor attributeDescriptor, QName field, Serializable value) { String xmlValue = null;//w ww. jav a2 s . c o m AttributeType.AttributeFormat attrFormat = null; if (attributeDescriptor != null && attributeDescriptor.getType() != null) { attrFormat = attributeDescriptor.getType().getAttributeFormat(); } if (attrFormat == null) { attrFormat = AttributeType.AttributeFormat.STRING; } String name = null; if (!StringUtils.isBlank(field.getNamespaceURI())) { if (!StringUtils.isBlank(field.getPrefix())) { name = field.getPrefix() + CswConstants.NAMESPACE_DELIMITER + field.getLocalPart(); } else { name = field.getLocalPart(); } } else { name = field.getLocalPart(); } switch (attrFormat) { case BINARY: xmlValue = Base64.getEncoder().encodeToString((byte[]) value); break; case DATE: GregorianCalendar cal = new GregorianCalendar(); cal.setTime((Date) value); xmlValue = XSD_FACTORY.newXMLGregorianCalendar(cal).toXMLFormat(); break; case OBJECT: break; case GEOMETRY: case XML: default: xmlValue = value.toString(); break; } // Write the node if we were able to convert it. if (xmlValue != null) { writer.startNode(name); if (!StringUtils.isBlank(field.getNamespaceURI())) { if (StringUtils.isBlank(field.getPrefix())) { writer.addAttribute(XMLConstants.XMLNS_ATTRIBUTE, field.getNamespaceURI()); } } writer.setValue(xmlValue); writer.endNode(); } }