List of usage examples for org.apache.commons.codec.binary Base64OutputStream Base64OutputStream
public Base64OutputStream(OutputStream out)
From source file:FormularioGuardarEstudio.java
private void guardarEstudioEnBase(Estudio estudio) { Connection connection = ProcesamientoImagen.connectToDb(); if (connection != null) { ByteArrayOutputStream os = new ByteArrayOutputStream(); OutputStream b64 = new Base64OutputStream(os); Histograma histograma = new Histograma(); int[][] histogramaArray = histograma.completarHistograma(estudio.getImagen()); Color colorPromedio = ProcesamientoImagen.obtenerColorPromedio(estudio.getImagen()); try {/*from ww w.j ava 2s .c o m*/ ImageIO.write(estudio.getImagen(), "png", b64); String base64 = os.toString("UTF-8"); ejecutarInsertQuery(estudio, base64, histogramaArray, colorPromedio, connection); } catch (Exception e) { mostrarMensaje("NO SE PUDO GUARDAR EN LA BASE", Color.RED); e.printStackTrace(); } } else { mostrarMensaje("Fallo la conexion", Color.RED); } }
From source file:cloudeventbus.pki.CertificateUtils.java
/** * Saves a collection of certificates to the specified file. * * @param fileName the file to which the certificates will be saved * @param certificates the certificate to be saved * @throws IOException if an I/O error occurs *//*from w w w . j ava 2 s . c o m*/ public static void saveCertificates(String fileName, Collection<Certificate> certificates) throws IOException { final Path path = Paths.get(fileName); final Path directory = path.getParent(); if (directory != null && !Files.exists(directory)) { Files.createDirectories(directory); } try (final OutputStream fileOut = Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); final OutputStream out = new Base64OutputStream(fileOut)) { CertificateStoreLoader.store(out, certificates); } }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
@Override public String generatePKCS12KeystoreString(String password) throws CertificateException { KeyStore keyStore = loadKeyStore(); KeyStore newKeyStore = loadKeyStore(PKCS12_KEYSTORE_TYPE, null, password); copyNodeChain(keyStore, getKeyStorePassword(), newKeyStore, password); ByteArrayOutputStream byos = new ByteArrayOutputStream(); saveKeyStore(newKeyStore, password, new Base64OutputStream(byos)); try {//from w w w . j a v a 2s . co m return byos.toString("US-ASCII"); } catch (UnsupportedEncodingException e) { // should never get here throw new RuntimeException(e); } }
From source file:com.seleniumtests.driver.CustomEventFiringWebDriver.java
/** * Returns a Base64 string of the desktop * @param driverMode//ww w. j a v a 2s .c om * @param gridConnector * @return */ public static String captureDesktopToBase64String(DriverMode driverMode, SeleniumGridConnector gridConnector) { if (driverMode == DriverMode.LOCAL) { BufferedImage bi = captureDesktopToBuffer(); ByteArrayOutputStream os = new ByteArrayOutputStream(); OutputStream b64 = new Base64OutputStream(os); try { ImageIO.write(bi, "png", b64); return os.toString("UTF-8"); } catch (IOException e) { return ""; } } else if (driverMode == DriverMode.GRID && gridConnector != null) { return gridConnector.captureDesktopToBuffer(); } else { throw new ScenarioException("driver supports captureDesktopToBase64String only in local and grid mode"); } }
From source file:net.wastl.rdfdot.web.RDFDotWebService.java
@POST @Path("/render") public Response renderRDF(@QueryParam("input") String input, @QueryParam("output") String output, @QueryParam("backend") String backend, @QueryParam("base64") Boolean base64, @QueryParam("uri_shape") Shapes uri_shape, @QueryParam("uri_fill") String uri_fill, @QueryParam("uri_style") Styles uri_style, @QueryParam("bnode_shape") Shapes bnode_shape, @QueryParam("bnode_fill") String bnode_fill, @QueryParam("bnode_style") Styles bnode_style, @QueryParam("literal_shape") Shapes literal_shape, @QueryParam("literal_fill") String literal_fill, @QueryParam("literal_style") Styles literal_style, @QueryParam("arrow_shape") Arrows arrow_shape, @QueryParam("arrow_color") String arrow_color, @QueryParam("arrow_style") Styles arrow_style, @Context HttpServletRequest request) { if (backend == null) { backend = "native"; }//from www. java2 s. com if (output == null) { output = "png"; } if (input == null) { input = "turtle"; } GraphConfiguration configuration = new GraphConfiguration(); if (uri_shape != null) configuration.setUriShape(uri_shape); if (uri_fill != null) configuration.setUriFill(parseColor(uri_fill)); if (uri_style != null) configuration.setUriStyle(uri_style); if (bnode_shape != null) configuration.setBnodeShape(bnode_shape); if (bnode_fill != null) configuration.setBnodeFill(parseColor(bnode_fill)); if (bnode_style != null) configuration.setBnodeStyle(bnode_style); if (literal_shape != null) configuration.setLiteralShape(literal_shape); if (literal_fill != null) configuration.setLiteralFill(parseColor(literal_fill)); if (literal_style != null) configuration.setLiteralStyle(literal_style); if (arrow_shape != null) configuration.setArrowShape(arrow_shape); if (arrow_color != null) configuration.setArrowColor(parseColor(arrow_color)); if (arrow_style != null) configuration.setArrowStyle(arrow_style); try { GraphvizSerializer serializer; if (StringUtils.equalsIgnoreCase(backend, "native")) { serializer = new GraphvizSerializerNative(configuration); } else { File tmpFile = File.createTempFile("rdfdot", ".png"); serializer = new GraphvizSerializerCommand(configuration, tmpFile.getAbsolutePath()); tmpFile.deleteOnExit(); } RDFParser parser = Rio.createParser(RDFFormat.forMIMEType(getRDFMimeType(input))); parser.setRDFHandler(new GraphvizHandler(serializer)); parser.parse(request.getInputStream(), "http://localhost/"); if (base64 != null && base64) { return Response .ok((StreamingOutput) stream -> IOUtils.write(serializer.getResult(), new Base64OutputStream(stream))) .header("Content-Type", "application/base64").build(); } else { return Response.ok((StreamingOutput) stream -> IOUtils.write(serializer.getResult(), stream)) .header("Content-Type", getImageMimeType(output)).build(); } } catch (IOException e) { return Response.serverError().entity(e.getMessage()).build(); } catch (RDFHandlerException e) { return Response.serverError().entity(e.getMessage()).build(); } catch (RDFParseException e) { return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } catch (MaxSizeException e) { return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } }
From source file:org.apache.ignite.console.agent.handlers.AbstractListener.java
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override// w ww . j a va2 s. com public final void call(Object... args) { final Ack cb = safeCallback(args); args = removeCallback(args); try { final Map<String, Object> params; if (args == null || args.length == 0) params = Collections.emptyMap(); else if (args.length == 1) params = fromJSON(args[0], Map.class); else throw new IllegalArgumentException("Wrong arguments count, must be <= 1: " + Arrays.toString(args)); if (pool == null) pool = newThreadPool(); pool.submit(new Runnable() { @Override public void run() { try { Object res = execute(params); // TODO IGNITE-6127 Temporary solution until GZip support for socket.io-client-java. // See: https://github.com/socketio/socket.io-client-java/issues/312 // We can GZip manually for now. if (res instanceof RestResult) { RestResult restRes = (RestResult) res; ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); Base64OutputStream b64os = new Base64OutputStream(baos); GZIPOutputStream gzip = new GZIPOutputStream(b64os); gzip.write(restRes.getData().getBytes()); gzip.close(); restRes.zipData(baos.toString()); } cb.call(null, toJSON(res)); } catch (Exception e) { cb.call(e, null); } } }); } catch (Exception e) { cb.call(e, null); } }
From source file:org.apache.nifi.processors.standard.Base64EncodeContent.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { FlowFile flowFile = session.get();//from w w w. j av a 2s .c o m if (flowFile == null) { return; } final ComponentLog logger = getLogger(); boolean encode = context.getProperty(MODE).getValue().equalsIgnoreCase(ENCODE_MODE); try { final StopWatch stopWatch = new StopWatch(true); if (encode) { flowFile = session.write(flowFile, new StreamCallback() { @Override public void process(InputStream in, OutputStream out) throws IOException { try (Base64OutputStream bos = new Base64OutputStream(out)) { int len = -1; byte[] buf = new byte[8192]; while ((len = in.read(buf)) > 0) { bos.write(buf, 0, len); } bos.flush(); } } }); } else { flowFile = session.write(flowFile, new StreamCallback() { @Override public void process(InputStream in, OutputStream out) throws IOException { try (Base64InputStream bis = new Base64InputStream(new ValidatingBase64InputStream(in))) { int len = -1; byte[] buf = new byte[8192]; while ((len = bis.read(buf)) > 0) { out.write(buf, 0, len); } out.flush(); } } }); } logger.info("Successfully {} {}", new Object[] { encode ? "encoded" : "decoded", flowFile }); session.getProvenanceReporter().modifyContent(flowFile, stopWatch.getElapsed(TimeUnit.MILLISECONDS)); session.transfer(flowFile, REL_SUCCESS); } catch (ProcessException e) { logger.error("Failed to {} {} due to {}", new Object[] { encode ? "encode" : "decode", flowFile, e }); session.transfer(flowFile, REL_FAILURE); } }
From source file:org.beaconmc.BeaconServer.java
public BeaconServer(OptionSet options) { if (beaconServer != null) throw new IllegalStateException("There is already an instance of " + this.getClass().getName()); beaconServer = this; this.options = options; this.minecraftProperties = new MinecraftProperties((File) this.options.valueOf("server-config")); this.networkHandler = new NetworkHandler(this); if (new File("server-icon.png").exists()) { try {/*from www .j av a 2 s .c om*/ ByteArrayOutputStream os = new ByteArrayOutputStream(); OutputStream b64 = new Base64OutputStream(os); BufferedImage icon = ImageIO.read(new File("server-icon.png")); if (icon.getWidth() != 64 || icon.getHeight() != 64) { ErrorStream.handle("server-icon cannot be loaded", "server-icon.png must be 64x64"); } else { ImageIO.write(icon, "png", b64); this.favicon = "data:image/png;base64, " + os.toString("UTF-8"); } os.close(); } catch (IOException ex) { ErrorStream.handle(ex); } } this.worldsManager = new WorldsManager(this); this.worldsManager.loadAllworlds(); //Test Worlds System.out.println(this.worldsManager.getWorld("world").getSpawnLocation()); InetAddress inetAddress = null; if (this.getIP().length() > 0) try { inetAddress = InetAddress.getByName(this.getIP()); } catch (UnknownHostException e) { //None } try { this.networkHandler.bind(inetAddress, this.getPort()); } catch (Exception ex) { InfoStream.handle("***** Failed to bind to port ****"); InfoStream.handle(ex.getMessage()); InfoStream.handle("Perhaps a server is already running on that port?"); ErrorStream.handle("Failed to bind to port", ex.getMessage()); System.out.println(); System.exit(1); return; } InfoStream.handle("Ready for connections. Listen to " + (this.getIP().length() > 0 ? this.getIP() : "*") + ":" + this.getPort()); }
From source file:org.bedework.calfacade.BwResourceContent.java
/** * @return base64 encoded value//from www . j a v a2s.com * @throws CalFacadeException */ public String getEncodedContent() throws CalFacadeException { Base64OutputStream b64out = null; try { Blob b = getValue(); if (b == null) { return null; } int len = -1; int chunkSize = 1024; byte buffer[] = new byte[chunkSize]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); b64out = new Base64OutputStream(baos); InputStream str = b.getBinaryStream(); while ((len = str.read(buffer)) != -1) { b64out.write(buffer, 0, len); } return new String(baos.toByteArray()); } catch (Throwable t) { throw new CalFacadeException(t); } finally { try { b64out.close(); } catch (Throwable t) { } } }
From source file:org.cesecore.certificates.certificate.CertificateDataSerializationTest.java
/** This test prints the serialized form of a CertificateData object, and was used to generated the data above. */ @Test//from w ww. ja v a2 s .com public void testSerializeCurrent() throws Exception { log.trace(">testSerializeCurrent"); final KeyPair kp = KeyTools.genKeys("1024", "RSA"); final Certificate cert = CertTools.genSelfCert("CN=certuser", 10 * 365, null, kp.getPrivate(), kp.getPublic(), "SHA256withRSA", false); final CertificateData certData = new CertificateData(cert, kp.getPublic(), "certuser", "1234567812345678", CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityInformation.NO_ENDENTITYPROFILE, null, new Date().getTime(), false, true); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final Base64OutputStream b64os = new Base64OutputStream(baos); final ObjectOutputStream oos = new ObjectOutputStream(b64os); oos.writeObject(certData); oos.close(); b64os.close(); log.info("Base 64 of serialized CertData is: " + baos.toString("US-ASCII")); log.trace("<testSerializeCurrent"); }