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

The following examples show how to use org.apache.commons.codec.binary.Base64InputStream. 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: CommonActions.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
/**
 * Saves BASE64 content into file
 *
 * @param actionContext
 *            - an implementation of {@link IActionContext}
 * @param inputData
 *            - hash map of script parameters - must contain value of column
 *            "FileAlias" and "Content" <br />
 * @throws Exception
 *             - throws an exception
 */
@CustomColumns({
    @CustomColumn(value = "FileAlias", required = true),
    @CustomColumn(value = "Content", required = true),
    @CustomColumn(value = "Compress", required = false)
    })
@ActionMethod
public void SaveBase64Content(IActionContext actionContext, HashMap<?, ?> inputData) throws Exception {

    String content = unwrapFilters(inputData.get("Content"));

    try (InputStream bais = new ByteArrayInputStream(content.getBytes());
            InputStream b64 = new Base64InputStream(bais, false)) {
        saveContent(actionContext, inputData, b64);
    }
}
 
Example #2
Source File: EncodingUtility.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Description("Decodes base64 to string.<br/>"+
        "<b>base64Content</b> - base64 string to decode.<br/>" +
        "<b>compress</b> - perform compression of the result string (y / Y / n / N).<br/>" +
        "Example:<br/>" +
        "#DecodeBase64(\"VGVzdCBjb250ZW50\", \"n\") returns \"Test content\"<br/>"+
        "Example:<br/>" +
        "#DecodeBase64(\"eJwLSS0uUUjOzytJzSsBAB2pBLw=\", \"y\") returns \"Test content\"<br/>")
@UtilityMethod
public String DecodeBase64(String base64Content, Object compress) throws Exception{
    Boolean doCompress = BooleanUtils.toBoolean((String)compress);
    byte[] result;
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        try (InputStream ba = new ByteArrayInputStream(base64Content.getBytes());
                InputStream b64 = new Base64InputStream(ba, false);
                InputStream is = doCompress ? new InflaterInputStream(b64) : b64) {
            IOUtils.copy(is, os);
        }
        os.flush();
        result = os.toByteArray();
    }
    return new String(result);
}
 
Example #3
Source File: OccurrenceTest.java    From ontopia with Apache License 2.0 6 votes vote down vote up
public void _testBinaryReader() throws Exception {
  // read file and store in occurrence
  String file = TestFileUtils.getTestInputFile("various", "blob.gif");
  Reader ri = new InputStreamReader(new Base64InputStream(new FileInputStream(file), true), "utf-8");
  occurrence.setReader(ri, file.length(), DataTypes.TYPE_BINARY);

  Assert.assertTrue("Occurrence datatype is incorrect", Objects.equals(DataTypes.TYPE_BINARY, occurrence.getDataType()));
               
  // read and decode occurrence content
  Reader ro = occurrence.getReader();
  Assert.assertTrue("Reader value is null", ro != null);
  InputStream in = new Base64InputStream(new ReaderInputStream(ro, "utf-8"), false);
  try {
    OutputStream out = new FileOutputStream("/tmp/blob.gif");
    try {
      IOUtils.copy(in, out);
    } finally {
      out.close();
    }
  } finally {
    in.close();
  }
}
 
Example #4
Source File: UploadIFrame.java    From ontopia with Apache License 2.0 6 votes vote down vote up
@Override
public void onSubmit() {
  FileUpload upload = uploadField.getFileUpload();         
  if (upload != null) {
    try {
      Reader input = new InputStreamReader(new Base64InputStream(upload.getInputStream(), true), "utf-8");
      FieldInstance fieldInstance = fieldValueModel.getFieldInstanceModel().getFieldInstance();
      StringWriter swriter = new StringWriter();
      IOUtils.copy(input, swriter);
      String value = swriter.toString();
      fieldInstance.addValue(value, getLifeCycleListener());
      fieldValueModel.setExistingValue(value);
      uploaded = true;
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
 
Example #5
Source File: PodUpload.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static boolean uploadFile(OkHttpClient client, PodOperationContext context,
  OperationSupport operationSupport, Path pathToUpload)
  throws IOException, InterruptedException {

  final String file = context.getFile();
  final String directory = file.substring(0, file.lastIndexOf('/'));
  final String command = String.format(
    "mkdir -p %s && base64 -d - > %s", directory, file);
  final PodUploadWebSocketListener podUploadWebSocketListener = initWebSocket(
    buildCommandUrl(command, context, operationSupport), client);
  try (
    final FileInputStream fis = new FileInputStream(pathToUpload.toFile());
    final Base64InputStream b64In = new Base64InputStream(fis, true, 0, new byte[]{'\r', '\n'})
  ) {
    podUploadWebSocketListener.waitUntilReady(DEFAULT_CONNECTION_TIMEOUT_SECONDS);
    copy(b64In, podUploadWebSocketListener::send);
    podUploadWebSocketListener.waitUntilComplete(DEFAULT_COMPLETE_REQUEST_TIMEOUT_SECONDS);
    return true;
  }
}
 
Example #6
Source File: EnvironmentVariableResource.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream open() throws IOException {
   String value = System.getenv(variable);
   if(value == null) {
      throw new ResourceNotFoundException("No environment variable named '" + variable + "' is set");
   }
   return new Base64InputStream(new ByteArrayInputStream(value.getBytes()));
}
 
Example #7
Source File: Copy.java    From java with Apache License 2.0 5 votes vote down vote up
public InputStream copyFileFromPod(String namespace, String pod, String container, String srcPath)
    throws ApiException, IOException {
  Process proc =
      this.exec(
          namespace,
          pod,
          new String[] {"sh", "-c", "cat " + srcPath + " | base64"},
          container,
          false,
          false);
  return new Base64InputStream(proc.getInputStream());
}
 
Example #8
Source File: MailSenderBase.java    From iaf with Apache License 2.0 5 votes vote down vote up
private MailAttachmentStream streamToMailAttachment(InputStream stream, boolean isBase64, String mimeType) {
	MailAttachmentStream attachment = new MailAttachmentStream();
	if(StringUtils.isEmpty(mimeType)) {
		mimeType = "application/octet-stream";
	}
	if (isBase64) {
		attachment.setContent(new Base64InputStream(stream));
	} else {
		attachment.setContent(stream);
	}
	attachment.setMimeType(mimeType);

	return attachment;
}
 
Example #9
Source File: Util.java    From act with GNU General Public License v3.0 5 votes vote down vote up
public static Document decompressXMLDocument(byte[] bytes) throws
    IOException, ParserConfigurationException, SAXException,
    TransformerConfigurationException, TransformerException {
  // With help from http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
  ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
  InputStream s = new GZIPInputStream(new Base64InputStream(bais));
  DocumentBuilder documentBuilder = mkDocBuilderFactory().newDocumentBuilder();
  Document doc = documentBuilder.parse(s);
  s.close();
  return doc;
}
 
Example #10
Source File: FileOutputType.java    From adf-selenium with Apache License 2.0 5 votes vote down vote up
@Override
public File convertFromBase64Png(String base64Png) {
    try {
        IOUtils.copy(new Base64InputStream(IOUtils.toInputStream(base64Png)), new FileOutputStream(file));
    } catch (IOException e) {
        throw new WebDriverException(e);
    }
    return file;
}
 
Example #11
Source File: DataURIEncodingInputStream.java    From extract with MIT License 5 votes vote down vote up
public DataURIEncodingInputStream(final InputStream in, final MediaType type) {

		// Only text documents should be URL-encoded. It doesn't matter if the encoding is supported or not because
		// the URL-io works on raw bytes. Everything else must be base-64-encoded.
		if (type.getType().equals("text")) {
			this.prepend = ("data:" + type + ",").getBytes(StandardCharsets.US_ASCII);
			this.encoder = new URLEncodingInputStream(in);
		} else {
			this.prepend = ("data:" + type + ";base64,").getBytes(StandardCharsets.US_ASCII);
			this.encoder = new Base64InputStream(in, true, -1, null);
		}
	}
 
Example #12
Source File: JdbcUtil.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static void streamBlob(Blob blob, String column, String charset, boolean blobIsCompressed, String blobBase64Direction, Object target, boolean close) throws JdbcException, SQLException, IOException {
	if (target==null) {
		throw new JdbcException("cannot stream Blob to null object");
	}
	OutputStream outputStream=StreamUtil.getOutputStream(target);
	if (outputStream!=null) {
		InputStream inputStream = JdbcUtil.getBlobInputStream(blob, column, blobIsCompressed);
		if ("decode".equalsIgnoreCase(blobBase64Direction)){
			Base64InputStream base64DecodedStream = new Base64InputStream (inputStream);
			StreamUtil.copyStream(base64DecodedStream, outputStream, 50000);
		}
		else if ("encode".equalsIgnoreCase(blobBase64Direction)){
			Base64InputStream base64EncodedStream = new Base64InputStream (inputStream, true);
			StreamUtil.copyStream(base64EncodedStream, outputStream, 50000);
		}
		else {	
			StreamUtil.copyStream(inputStream, outputStream, 50000);
		}
		
		if (close) {
			outputStream.close();
		}
		return;
	}
	Writer writer = StreamUtil.getWriter(target);
	if (writer !=null) {
		Reader reader = JdbcUtil.getBlobReader(blob, column, charset, blobIsCompressed);
		StreamUtil.copyReaderToWriter(reader, writer, 50000, false, false);
		if (close) {
			writer.close();
		}
		return;
	}
	throw new IOException("cannot stream Blob to ["+target.getClass().getName()+"]");
}
 
Example #13
Source File: OccurrenceWebResource.java    From ontopia with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream getInputStream() throws ResourceStreamNotFoundException {
  try {
    return new Base64InputStream(new ReaderInputStream(reader, "utf-8"), false);
  } catch (UnsupportedEncodingException e) {
    throw new OntopiaRuntimeException(e);
  }
}
 
Example #14
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 (Base64InputStream bis = new Base64InputStream(new ValidatingBase64InputStream(in))) {
        StreamUtils.copy(bis, out);
    }
}
 
Example #15
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 (Base64InputStream bis = new Base64InputStream(new ValidatingBase64InputStream(in))) {
        StreamUtils.copy(bis, out);
    }
}
 
Example #16
Source File: Base64Codec.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
private InputStream decodeInputStreamWithApache(InputStream origStream) {
  return new Base64InputStream(origStream);
}
 
Example #17
Source File: Copy.java    From java with Apache License 2.0 4 votes vote down vote up
public void copyDirectoryFromPod(
    String namespace, String pod, String container, String srcPath, Path destination)
    throws ApiException, IOException, CopyNotSupportedException {
  // Test that 'tar' is present in the container?
  if (!isTarPresentInContainer(namespace, pod, container)) {
    throw new CopyNotSupportedException("Tar is not present in the target container");
  }
  final Process proc =
      this.exec(
          namespace,
          pod,
          new String[] {"sh", "-c", "tar cz - " + srcPath + " | base64"},
          container,
          false,
          false);
  try (InputStream is = new Base64InputStream(new BufferedInputStream(proc.getInputStream()));
      ArchiveInputStream archive = new TarArchiveInputStream(new GzipCompressorInputStream(is))) {
    for (ArchiveEntry entry = archive.getNextEntry();
        entry != null;
        entry = archive.getNextEntry()) {
      if (!archive.canReadEntryData(entry)) {
        log.error("Can't read: " + entry);
        continue;
      }
      File f = new File(destination.toFile(), entry.getName());
      if (entry.isDirectory()) {
        if (!f.isDirectory() && !f.mkdirs()) {
          throw new IOException("create directory failed: " + f);
        }
      } else {
        File parent = f.getParentFile();
        if (!parent.isDirectory() && !parent.mkdirs()) {
          throw new IOException("create directory failed: " + parent);
        }
        try (OutputStream fs = new FileOutputStream(f)) {
          ByteStreams.copy(archive, fs);
          fs.flush();
        }
      }
    }
  }
  try {
    int status = proc.waitFor();
    if (status != 0) {
      throw new IOException("Copy command failed with status " + status);
    }
  } catch (InterruptedException ex) {
    throw new IOException(ex);
  }
}
 
Example #18
Source File: PDDocs.java    From openprodoc with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Assign the file IN BASE 64 to be uploaded when called insert or update.
 * @param B64InputStream  Binary content in Base64 of the document to import
 * @throws PDException In any error
 */
private void setStreamB64(InputStream B64InputStream)
{
FileStream=new Base64InputStream(B64InputStream,false);
}