org.apache.commons.codec.binary.Base64OutputStream Java Examples

The following examples show how to use org.apache.commons.codec.binary.Base64OutputStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EncodingUtility.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Description("Encodes string to base64.<br/>"+
        "<b>content</b> - string to encode.<br/>" +
        "<b>compress</b> - perform compression of the result string (y / Y / n / N).<br/>" +
        "Example:<br/>" +
        "#EncodeBase64(\"Test content\", \"n\") returns \"VGVzdCBjb250ZW50\"<br/>"+
        "Example:<br/>" +
        "#EncodeBase64(\"Test content\", \"y\") returns \"eJwLSS0uUUjOzytJzSsBAB2pBLw=\"<br/>")
@UtilityMethod
public String EncodeBase64(String content, Object compress) throws Exception{
    Boolean doCompress = BooleanUtils.toBoolean((String)compress);
    byte[] result;
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
         try (OutputStream b64 = new Base64OutputStream(os, true, -1, new byte[0]);
                InputStream ba = new ByteArrayInputStream(content.getBytes());
                InputStream is = doCompress ? new DeflaterInputStream(ba) : ba) {
            IOUtils.copy(is, b64);
        }
        os.flush();
        result = os.toByteArray();
    }
    return new String(result);
}
 
Example #2
Source File: HttpUtil.java    From hop with Apache License 2.0 5 votes vote down vote up
public static String encodeBase64ZippedString( String in ) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 );
  try ( Base64OutputStream base64OutputStream = new Base64OutputStream( baos );
        GZIPOutputStream gzos = new GZIPOutputStream( base64OutputStream ) ) {
    gzos.write( in.getBytes( StandardCharsets.UTF_8 ) );
  }
  return baos.toString();
}
 
Example #3
Source File: CommonActions.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
/**
 * Encode base64 text. Returns BASE64 string.
 *
 * @param actionContext
 *            - an implementation of {@link IActionContext}
 * @param inputData
 *            - hash map of script parameters - must contain value of column
 *            "FileName" and "Content" <br />
 * @throws Exception
 *             - throws an exception
 */
@Description("Encode file to base64.<br/>"+
        "<b>FileAlias</b> - file to encode.<br/>" +
        "<b>Compress</b> - do compress result string (y / Y / n / N).<br/>")
@CommonColumns(@CommonColumn(value = Column.Reference, required = true))
@CustomColumns({ @CustomColumn(value = "FileAlias", required = true), @CustomColumn(value = "Compress", required = false)})
@ActionMethod
public String LoadBase64Content(IActionContext actionContext, HashMap<?, ?> inputData) throws Exception {

    String fileAlias = unwrapFilters(inputData.get("FileAlias"));
    Boolean compress = BooleanUtils.toBoolean((String)unwrapFilters(inputData.get("Compress")));
    IDataManager dataManager = actionContext.getDataManager();
    SailfishURI target = SailfishURI.parse(fileAlias);

    if (dataManager.exists(target)) {

        byte[] result;

        try(ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            try (OutputStream b64 =  new Base64OutputStream(os, true, -1, new byte[0]);
                    InputStream dm = dataManager.getDataInputStream(target);
                    InputStream is = compress ? new DeflaterInputStream(dm) : dm) {
                IOUtils.copy(is, b64);
            }
            os.flush();
            result = os.toByteArray();
        }

        return new String(result);
    } else {
        throw new EPSCommonException(format("Specified %s file alias does not exists", fileAlias));
    }
}
 
Example #4
Source File: Copy.java    From java with Apache License 2.0 5 votes vote down vote up
public void copyFileToPod(
    String namespace, String pod, String container, Path srcPath, Path destPath)
    throws ApiException, IOException {

  // Run decoding and extracting processes
  String parentPath = destPath.getParent() != null ? destPath.getParent().toString() : ".";
  final Process proc =
      this.exec(
          namespace,
          pod,
          new String[] {"sh", "-c", "base64 -d | tar -xmf - -C " + parentPath},
          container,
          true,
          false);

  // Send encoded archive output stream
  File srcFile = new File(srcPath.toUri());
  try (ArchiveOutputStream archiveOutputStream =
          new TarArchiveOutputStream(
              new Base64OutputStream(proc.getOutputStream(), true, 0, null));
      FileInputStream input = new FileInputStream(srcFile)) {
    ArchiveEntry tarEntry = new TarArchiveEntry(srcFile, destPath.getFileName().toString());

    archiveOutputStream.putArchiveEntry(tarEntry);
    ByteStreams.copy(input, archiveOutputStream);
    archiveOutputStream.closeArchiveEntry();
  } finally {
    proc.destroy();
  }

  return;
}
 
Example #5
Source File: Util.java    From act with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] compressXMLDocument(Document doc) throws
    IOException, TransformerConfigurationException, TransformerException {
  Transformer transformer = getTransformerFactory().newTransformer();
  // The OutputKeys.INDENT configuration key determines whether the output is indented.

  DOMSource w3DomSource = new DOMSource(doc);
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  Writer w = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(
      new Base64OutputStream(baos, true, 0, new byte[]{'\n'}))));
  StreamResult sResult = new StreamResult(w);
  transformer.transform(w3DomSource, sResult);
  w.close();
  return baos.toByteArray();
}
 
Example #6
Source File: CastToBase64BinaryOperation.java    From vxquery with Apache License 2.0 5 votes vote down vote up
@Override
public void convertString(UTF8StringPointable stringp, DataOutput dOut) throws SystemException, IOException {
    baaos.reset();
    Base64OutputStream b64os = new Base64OutputStream(baaos, false);
    b64os.write(stringp.getByteArray(), stringp.getCharStartOffset(), stringp.getUTF8Length());

    dOut.write(ValueTag.XS_BASE64_BINARY_TAG);
    dOut.write((byte) ((baaos.size() >>> 8) & 0xFF));
    dOut.write((byte) ((baaos.size() >>> 0) & 0xFF));
    dOut.write(baaos.getByteArray(), 0, baaos.size());

    b64os.close();
}
 
Example #7
Source File: CastToStringOperation.java    From vxquery with Apache License 2.0 5 votes vote down vote up
@Override
public void convertBase64Binary(XSBinaryPointable binaryp, DataOutput dOut) throws SystemException, IOException {
    // Read binary
    Base64OutputStream b64os = new Base64OutputStream(baaos, true);
    b64os.write(binaryp.getByteArray(), binaryp.getStartOffset() + 2, binaryp.getLength() - 2);

    // Write string
    startString();
    sb.appendUtf8Bytes(baaos.getByteArray(), 0, baaos.size());
    sendStringDataOutput(dOut);
}
 
Example #8
Source File: EncodingBenchmark.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Benchmark
public byte[] write1KRecordsBase64Only(EncodingBenchmarkState state) throws IOException {
  ByteArrayOutputStream sink = new ByteArrayOutputStream();
  OutputStream os = new Base64OutputStream(sink);
  os.write(state.OneKBytes);
  os.close();

  return sink.toByteArray();
}
 
Example #9
Source File: HttpUtil.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static String encodeBase64ZippedString( String in ) throws IOException {
  Charset charset = Charset.forName( Const.XML_ENCODING );
  ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 );
  try ( Base64OutputStream base64OutputStream = new Base64OutputStream( baos );
        GZIPOutputStream gzos = new GZIPOutputStream( base64OutputStream ) ) {
    gzos.write( in.getBytes( charset ) );
  }
  return baos.toString();
}
 
Example #10
Source File: EncodeUtil.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * Base64 encodes then zips a byte array into a compressed string
 *
 * @param src the source byte array
 * @return a compressed, base64 encoded string
 * @throws IOException
 */
public static String encodeBase64Zipped( byte[] src ) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 );
  try ( Base64OutputStream base64OutputStream = new Base64OutputStream( baos );
        GZIPOutputStream gzos = new GZIPOutputStream( base64OutputStream ) ) {
    gzos.write( src );
  }
  return baos.toString();
}
 
Example #11
Source File: EncodeContent.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void process(InputStream in, OutputStream out) throws IOException {
    try (Base64OutputStream bos = new Base64OutputStream(out)) {
        StreamUtils.copy(in, bos);
    }
}
 
Example #12
Source File: DeviceRegisterServiceImpl.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
/**
 * Generate an encoded base64 String with qrcode image
 *
 * @param credentials
 * @param width
 * @param height
 * @return String
 * @throws Exception
 */
@Override
public ServiceResponse<String> generateQrCodeAccess(DeviceSecurityCredentials credentials, int width, int height, Locale locale) {
    try {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Base64OutputStream encoded = new Base64OutputStream(baos);
        StringBuilder content = new StringBuilder();
        content.append("{\"user\":\"").append(credentials.getDevice().getUsername());
        content.append("\",\"pass\":\"").append(credentials.getPassword());
        
        DeviceDataURLs deviceDataURLs = new DeviceDataURLs(credentials.getDevice(), locale);
       	content.append("\",\"host\":\"").append(deviceDataURLs.getHttpHostName());
        content.append("\",\"ctx\":\"").append(deviceDataURLs.getContext());
        content.append("\",\"host-mqtt\":\"").append(deviceDataURLs.getMqttHostName());
        
        content.append("\",\"http\":\"").append(deviceDataURLs.getHttpPort());
        content.append("\",\"https\":\"").append(deviceDataURLs.getHttpsPort());
        content.append("\",\"mqtt\":\"").append(deviceDataURLs.getMqttPort());
        content.append("\",\"mqtt-tls\":\"").append(deviceDataURLs.getMqttTlsPort());
        content.append("\",\"pub\":\"pub/").append(credentials.getDevice().getUsername());
        content.append("\",\"sub\":\"sub/").append(credentials.getDevice().getUsername()).append("\"}");

        Map<EncodeHintType, Serializable> map = new HashMap<>();
        for (AbstractMap.SimpleEntry<EncodeHintType, ? extends Serializable> item : Arrays.<AbstractMap.SimpleEntry<EncodeHintType, ? extends Serializable>>asList(
                new AbstractMap.SimpleEntry<>(EncodeHintType.MARGIN, 0),
                new AbstractMap.SimpleEntry<>(EncodeHintType.CHARACTER_SET, "UTF-8")
        )) {
            if (map.put(item.getKey(), item.getValue()) != null) {
                throw new IllegalStateException("Duplicate key");
            }
        }
        BitMatrix bitMatrix = new QRCodeWriter().encode(
                content.toString(),
                BarcodeFormat.QR_CODE, width, height,
                Collections.unmodifiableMap(map));
        MatrixToImageWriter.writeToStream(bitMatrix, "png", encoded);
        String result = "data:image/png;base64," + new String(baos.toByteArray(), 0, baos.size(), "UTF-8");
        return ServiceResponseBuilder.<String>ok().withResult(result).build();
    } catch (Exception e) {
        return ServiceResponseBuilder.<String>error()
                .withMessage(Messages.DEVICE_QRCODE_ERROR.getCode())
                .build();
    }
}
 
Example #13
Source File: PodUpload.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private static boolean uploadDirectory(OkHttpClient client, PodOperationContext context,
  OperationSupport operationSupport, Path pathToUpload)
  throws IOException, InterruptedException {

  final String command = String.format(
    "mkdir -p %1$s && base64 -d - | tar -C %1$s -xzf -", context.getDir());
  final PodUploadWebSocketListener podUploadWebSocketListener = initWebSocket(
    buildCommandUrl(command, context, operationSupport), client);
  try (
    final PipedOutputStream pos = new PipedOutputStream();
    final PipedInputStream pis = new PipedInputStream(pos);
    final Base64OutputStream b64Out = new Base64OutputStream(pos, true, 0, new byte[]{'\r', '\n'});
    final GZIPOutputStream gzip = new GZIPOutputStream(b64Out)

  ) {
    final CountDownLatch done = new CountDownLatch(1);
    final AtomicReference<IOException> readFileException = new AtomicReference<>(null);
    podUploadWebSocketListener.waitUntilReady(DEFAULT_CONNECTION_TIMEOUT_SECONDS);
    final Runnable readFiles = () -> {
      try (final TarArchiveOutputStream tar = new TarArchiveOutputStream(gzip)) {
        for (File file : pathToUpload.toFile().listFiles()) {
          addFileToTar(null, file, tar);
        }
        tar.flush();
      } catch (IOException ex) {
        readFileException.set(ex);
      } finally {
        done.countDown();
      }
    };
    final ExecutorService es = Executors.newSingleThreadExecutor();
    es.submit(readFiles);
    copy(pis, podUploadWebSocketListener::send);
    podUploadWebSocketListener.waitUntilComplete(DEFAULT_COMPLETE_REQUEST_TIMEOUT_SECONDS);
    final boolean doneGracefully = done.await(100, TimeUnit.SECONDS);
    es.shutdown();
    if (readFileException.get() != null) {
      throw readFileException.get();
    }
    return doneGracefully;
  }
}
 
Example #14
Source File: CompressAndEncodeTool.java    From tesb-studio-se with Apache License 2.0 4 votes vote down vote up
private static OutputStream compressAndEncodeStream(OutputStream os) {
    return new DeflaterOutputStream(new Base64OutputStream(os));
}
 
Example #15
Source File: Base64Codec.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
private OutputStream encodeOutputStreamWithApache(OutputStream origStream) {
  return new Base64OutputStream(origStream, true, 0, null);
}
 
Example #16
Source File: EncodeContent.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void process(InputStream in, OutputStream out) throws IOException {
    try (Base64OutputStream bos = new Base64OutputStream(out)) {
        StreamUtils.copy(in, bos);
    }
}