List of usage examples for java.util Base64 getDecoder
public static Decoder getDecoder()
From source file:ostepu.file.fileUtils.java
/** * liefert den Inhalt einer Datei, welches sich hinter dem file-Object * befindet/*www .ja va 2 s .co m*/ * * @param context der Kontext des Servlet * @param fileObject das Dateiobjekt * @param useCache ob die Datei lokal gespeichert und abgefragt werden * soll (true = nutze Cache, false = sonst) * @param auth die Authentifizierungsdaten * @return der Inhalt der Datei */ public static byte[] getFile(ServletContext context, file fileObject, boolean useCache, authentication auth) { if (fileObject.getAddress() != null) { // das Dateiobjekt hat eine normale Adresse return getFile(context, "/" + fileObject.getAddress() + "/" + fileObject.getDisplayName(), useCache, auth); } else { if (fileObject.getBody() != null) { Object body = fileObject.getBody(); if (body.getClass() == String.class) { // es ist ein base64 inhalt Decoder dec = Base64.getDecoder(); return dec.decode((String) body); } else { // es ist eine Referenz reference ref = (reference) body; if (ref.getGlobalRef() != null) { // es gibt eine globale Adresse, welche wir verwenden knnen return getFile(context, "/" + ref.getGlobalRef() + "/" + fileObject.getDisplayName(), useCache, auth); } // wenn es keine gltige globale Adresse gibt, dann knnen // wir hier nichts weiter machen } } } return null; }
From source file:org.eclipse.che.mail.MailSender.java
public void sendMail(EmailBean emailBean) throws SendMailException { File tempDir = null;//from www . j a va 2s . c o m try { MimeMessage message = new MimeMessage(mailSessionProvider.get()); Multipart contentPart = new MimeMultipart(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType())); contentPart.addBodyPart(bodyPart); if (emailBean.getAttachments() != null) { tempDir = Files.createTempDir(); for (Attachment attachment : emailBean.getAttachments()) { // Create attachment file in temporary directory byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent()); File attachmentFile = new File(tempDir, attachment.getFileName()); Files.write(attachmentContent, attachmentFile); // Attach the attachment file to email MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(attachmentFile); attachmentPart.setContentID("<" + attachment.getContentId() + ">"); contentPart.addBodyPart(attachmentPart); } } message.setContent(contentPart); message.setSubject(emailBean.getSubject(), "UTF-8"); message.setFrom(new InternetAddress(emailBean.getFrom(), true)); message.setSentDate(new Date()); message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo())); if (emailBean.getReplyTo() != null) { message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo())); } LOG.info("Sending from {} to {} with subject {}", emailBean.getFrom(), emailBean.getTo(), emailBean.getSubject()); Transport.send(message); LOG.debug("Mail sent"); } catch (Exception e) { LOG.error(e.getLocalizedMessage()); throw new SendMailException(e.getLocalizedMessage(), e); } finally { if (tempDir != null) { try { FileUtils.deleteDirectory(tempDir); } catch (IOException exception) { LOG.error(exception.getMessage()); } } } }
From source file:Main.java
private static void serializeArrayAsXml(StringBuffer buff, Object key, Object value) { JsonArray array = (JsonArray) value; for (int i = 0; i < array.size(); i++) { JsonElement elementJson = array.get(i); if (elementJson instanceof JsonObject) { buff.append(LT).append(key); serializeObjectAttributes((JsonObject) elementJson, buff); buff.append(GT);// w ww . j a v a 2 s . co m serializeObjectAsXml((JsonObject) elementJson, buff); buff.append(LTS).append(key).append(GT); } else if (elementJson instanceof JsonArray) { serializeArrayAsXml(buff, key, elementJson); } else if (elementJson instanceof JsonPrimitive) { JsonPrimitive elementPrimitive = (JsonPrimitive) elementJson; if (ATTR_TEXT.equals(key)) { buff.append(elementPrimitive.toString().replace(EQ, EMPTY)); } else if (ATTR_CDATA.equals(key)) { buff.append(CDATA_OPEN) .append(new String( Base64.getDecoder().decode(elementPrimitive.toString().replace(EQ, EMPTY)))) .append(CDATA_CLOSE); } else { // System.err.println("ERROR: content attributes must be #text"); buff.append(LT).append(key); buff.append(GT); buff.append(elementPrimitive.toString().replace(EQ, EMPTY)); buff.append(LTS).append(key).append(GT); } } } }
From source file:com.antsdb.saltedfish.nosql.DumpRow.java
private void run(String[] args) throws Exception { CommandLine line = parse(getOptions(), args); // help/*from w w w . j a v a2 s. c om*/ if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("dumprow <table id> <row key base64>", getOptions()); return; } // arguments if (line.getArgList().size() != 2) { println("error: invalid command line arguments"); return; } this.tableId = Integer.parseInt(line.getArgList().get(0)); this.key = Base64.getDecoder().decode(line.getArgList().get(1)); this.pKey = KeyBytes.allocSet(this.heap, this.key).getAddress(); // options this.home = new File(line.getOptionValue("home")); this.isVerbose = line.hasOption('v'); this.dumpHex = line.hasOption("hex"); this.dumpValues = line.hasOption("values"); // validate if (!this.home.isDirectory()) { println("error: invalid home directory {}", this.home); return; } if (!new File(this.home, "checkpoint.bin").exists()) { println("error: invalid home directory {}", this.home); return; } // init space manager this.spaceman = new SpaceManager(this.home, false); spaceman.init(); // proceed dump(); }
From source file:org.lightjason.agentspeak.action.buildin.crypto.CDecrypt.java
@Override public final IFuzzyValue<Boolean> execute(final IContext p_context, final boolean p_parallel, final List<ITerm> p_argument, final List<ITerm> p_return, final List<ITerm> p_annotation) { final Key l_key = p_argument.get(0).raw(); final EAlgorithm l_algorithm = EAlgorithm.from(l_key.getAlgorithm()); return CFuzzyValue.from(p_argument.subList(1, p_argument.size()).stream() .map(i -> Base64.getDecoder().decode(i.<String>raw())).allMatch(i -> { try { p_return.add(CRawTerm.from( SerializationUtils.deserialize(l_algorithm.getDecryptCipher(l_key).doFinal(i)))); return true; } catch (final NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException l_exception) { return false; }/*from ww w .jav a 2s.c o m*/ })); }
From source file:org.lightjason.agentspeak.action.builtin.crypto.CDecrypt.java
/** * decrypt/*ww w .ja v a 2s.c o m*/ * * @param p_algorithm algorithm * @param p_key key * @param p_dataset base64 encoded dataset * @param p_return return argument * @return successful execution */ private static boolean decrypt(@Nonnull final EAlgorithm p_algorithm, @Nonnull final Key p_key, @Nonnull final String p_dataset, @Nonnull final List<ITerm> p_return) { try { p_return.add(CRawTerm.from(SerializationUtils.deserialize( p_algorithm.getDecryptCipher(p_key).doFinal(Base64.getDecoder().decode(p_dataset))))); return true; } catch (final IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException l_exception) { return false; } }
From source file:io.fabric8.spring.cloud.kubernetes.config.SecretsPropertySource.java
private static void putAll(Secret secret, Map<String, Object> result) { if (secret != null && secret.getData() != null) { secret.getData().forEach((k, v) -> result.put(k, new String(Base64.getDecoder().decode(v)).trim())); }//ww w .j av a2s . c o m }
From source file:com.sdm.core.filter.AuthorizationRequestFilter.java
@Override public void filter(ContainerRequestContext requestContext) throws IOException { Method method = resourceInfo.getResourceMethod(); Class<?> resourceClass = resourceInfo.getResourceClass(); //Skip Data Permission if Resource Permission is public or there is no AccessManager if (resourceClass.isAnnotationPresent(PermitAll.class) || accessManager == null) { //Auth Success requestContext.setProperty(Constants.REQUEST_TOKEN, new AuthInfo(0, "public-token", "unknown")); return;/*from w ww . j a v a 2 s. c o m*/ } if (!method.isAnnotationPresent(PermitAll.class)) { if (method.isAnnotationPresent(DenyAll.class)) { //Deny all Auth requestContext.abortWith(errorResponse(403)); return; } final MultivaluedMap<String, String> headers = requestContext.getHeaders(); final List<String> authorization = headers.get(HttpHeaders.AUTHORIZATION); final List<String> userAgents = headers.get(HttpHeaders.USER_AGENT); if (authorization == null || authorization.isEmpty() || userAgents == null || userAgents.isEmpty()) { //There is not Auth requestContext.abortWith(errorResponse(401)); return; } try { // Clean Token String settingKey = Setting.getInstance().get(Setting.JWT_KEY); String tokenString = authorization.get(0).substring(Constants.AUTH_TYPE.length()).trim(); byte[] jwtKey = Base64.getDecoder().decode(settingKey); try { Claims authorizeToken = Jwts.parser().setSigningKey(jwtKey).requireIssuer(userAgents.get(0)) .parseClaimsJws(tokenString).getBody(); if (!accessManager.validateToken(authorizeToken)) { //Auth Failed requestContext.abortWith(errorResponse(403)); return; } String token = authorizeToken.getId(); String device = authorizeToken.get("device_id").toString() + ":" + authorizeToken.get("device_os").toString(); long userId = Long.parseLong( authorizeToken.getSubject().substring(Constants.USER_PREFIX.length()).trim()); AuthInfo authInfo = new AuthInfo(userId, token, device); //Check @UserAllowed in Class UserAllowed userAllowed = resourceClass.getAnnotation(UserAllowed.class); if (userAllowed != null && userAllowed.value()) { //Skip Permission for User Allowed Class requestContext.setProperty(Constants.REQUEST_TOKEN, authInfo); return; } //Check @UserAllowed in Method userAllowed = resourceClass.getAnnotation(UserAllowed.class); if (userAllowed != null && userAllowed.value()) { //Skip Permission for User Allowed Method requestContext.setProperty(Constants.REQUEST_TOKEN, authInfo); return; } //Check permission from DB if (!accessManager.checkPermission(authorizeToken, method, requestContext.getMethod(), resourceClass)) { //Validate dynamic Permission failed requestContext.abortWith(errorResponse(403)); return; } requestContext.setProperty(Constants.REQUEST_TOKEN, authInfo); } catch (ClaimJwtException ex) { requestContext.abortWith(buildResponse(403, ex.getLocalizedMessage())); } } catch (UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { LOG.error(e); requestContext.abortWith(buildResponse(500, e.getLocalizedMessage())); } } }
From source file:org.apache.syncope.client.console.PreferenceManager.java
public String get(final Request request, final String key) { String result = null;/* www . java 2 s. c o m*/ String prefString = COOKIE_UTILS.load(COOKIE_NAME); if (prefString != null) { Map<String, String> prefs = getPrefs(new String(Base64.getDecoder().decode(prefString.getBytes()))); result = prefs.get(key); } return result; }
From source file:top.lionxxw.zuulservice.filter.BookingCarRoutingFilter.java
private String decode(String token) { byte[] decodedBytes = Base64.getDecoder().decode(token.getBytes()); //byte[] encodedBytes = Base64.getEncoder().encode(origin.getBytes()); return new String(decodedBytes); }