List of usage examples for org.apache.commons.codec.binary Base64InputStream Base64InputStream
public Base64InputStream(InputStream in, boolean doEncode, int lineLength, byte[] lineSeparator)
From source file:com.opengamma.web.analytics.json.Compressor.java
static void decompressStream(InputStream inputStream, OutputStream outputStream) throws IOException { @SuppressWarnings("resource") InputStream iStream = new GZIPInputStream( new Base64InputStream(new BufferedInputStream(inputStream), false, -1, null)); OutputStream oStream = new BufferedOutputStream(outputStream); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = iStream.read(buffer)) != -1) { oStream.write(buffer, 0, bytesRead); }/*from w ww. ja v a2s . co m*/ oStream.flush(); }
From source file:com.dinochiesa.edgecallouts.Base64.java
public ExecutionResult execute(final MessageContext msgCtxt, final ExecutionContext execContext) { try {/*from w w w .j a v a 2s . com*/ Base64Action action = getAction(msgCtxt); InputStream content = msgCtxt.getMessage().getContentAsStream(); int lineLength = getLineLength(msgCtxt, -1); InputStream is = new Base64InputStream(content, (action == Base64Action.Encode), lineLength, linebreak); byte[] bytes = IOUtils.toByteArray(is); boolean isBase64 = org.apache.commons.codec.binary.Base64.isBase64(bytes); if (isBase64) { msgCtxt.setVariable(varName("action"), action.name().toLowerCase()); boolean wantStringDefault = (action == Base64Action.Encode); boolean wantString = getStringOutput(msgCtxt, wantStringDefault); if (wantString) { msgCtxt.setVariable(varName("wantString"), wantString); String encoded = StringUtils.newStringUtf8(bytes); msgCtxt.setVariable(varName("result"), encoded); } else { String mimeType = getMimeType(msgCtxt); if (mimeType != null) { msgCtxt.setVariable(varName("mimeType"), mimeType); } msgCtxt.setVariable(varName("result"), bytes); } return ExecutionResult.SUCCESS; } else { msgCtxt.setVariable(varName("error"), "not Base64"); return ExecutionResult.ABORT; } } catch (Exception e) { System.out.println(ExceptionUtils.getStackTrace(e)); String error = e.toString(); msgCtxt.setVariable(varName("exception"), error); int ch = error.lastIndexOf(':'); if (ch >= 0) { msgCtxt.setVariable(varName("error"), error.substring(ch + 2).trim()); } else { msgCtxt.setVariable(varName("error"), error); } msgCtxt.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(e)); return ExecutionResult.ABORT; } }
From source file:ke.go.moh.oec.adt.Daemon.java
private static boolean sendMessage(String url, String filename) { int returnStatus = HttpStatus.SC_CREATED; HttpClient httpclient = new HttpClient(); HttpConnectionManager connectionManager = httpclient.getHttpConnectionManager(); connectionManager.getParams().setSoTimeout(120000); PostMethod httpPost = new PostMethod(url); RequestEntity requestEntity;//from ww w.j a v a2 s . c o m try { FileInputStream message = new FileInputStream(filename); Base64InputStream message64 = new Base64InputStream(message, true, -1, null); requestEntity = new InputStreamRequestEntity(message64, "application/octet-stream"); } catch (FileNotFoundException e) { Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "File not found.", e); return false; } httpPost.setRequestEntity(requestEntity); try { httpclient.executeMethod(httpPost); returnStatus = httpPost.getStatusCode(); } catch (SocketTimeoutException e) { returnStatus = HttpStatus.SC_REQUEST_TIMEOUT; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Request timed out. Not retrying.", e); } catch (HttpException e) { returnStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "HTTP exception. Not retrying.", e); } catch (ConnectException e) { returnStatus = HttpStatus.SC_SERVICE_UNAVAILABLE; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Service unavailable. Not retrying.", e); } catch (UnknownHostException e) { returnStatus = HttpStatus.SC_NOT_FOUND; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Not found. Not retrying.", e); } catch (IOException e) { returnStatus = HttpStatus.SC_GATEWAY_TIMEOUT; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "IO exception. Not retrying.", e); } finally { httpPost.releaseConnection(); } return returnStatus == HttpStatus.SC_OK; }
From source file:com.groupdocs.sdk.common.ApiInvoker.java
public static String readAsDataURL(InputStream is, String contentType) throws IOException { String base64file = IOUtils.toString(new Base64InputStream(is, true, 0, null)); return "data:" + contentType + ";base64," + base64file; }
From source file:eu.scape_project.planning.xml.ProjectExportAction.java
/** * Dumps binary data to provided file. It results in an XML file with a * single element: data./*from w w w .j a v a 2 s.com*/ * * @param id * @param data * @param f * @param encoder * @throws IOException */ private static void writeBinaryData(int id, InputStream data, File f) throws IOException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(f)); writer.writeStartDocument(PlanXMLConstants.ENCODING, "1.0"); writer.writeStartElement("data"); writer.writeAttribute("id", "" + id); Base64InputStream base64EncodingIn = new Base64InputStream(data, true, PlanXMLConstants.BASE64_LINE_LENGTH, PlanXMLConstants.BASE64_LINE_BREAK); OutputStream out = new WriterOutputStream(new XMLStreamContentWriter(writer), PlanXMLConstants.ENCODING); // read the binary data and encode it on the fly IOUtils.copy(base64EncodingIn, out); out.flush(); // all data is written - end writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.doculibre.constellio.feedprotocol.FeedProcessor.java
private ContentParse asContentParse(String url, List<FeedContent> feedContents, ConnectorInstance connectorInstance) { ConnectorInstanceServices connectorInstanceServices = ConstellioSpringUtils.getConnectorInstanceServices(); ContentParse contentParse = new ContentParse(); List<RecordMeta> metas = new ArrayList<RecordMeta>(); contentParse.setMetas(metas);/*from ww w . ja v a2 s . c om*/ List<String> md5s = new ArrayList<String>(); StringBuffer contentBuffer = new StringBuffer(); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e1) { throw new RuntimeException(e1); } for (FeedContent feedContent : feedContents) { InputStream input = null; try { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(-1); ParseContext parseContext = new ParseContext(); if (feedContent.getEncoding() == FeedContent.ENCODING.BASE64BINARY) { input = new BufferedInputStream(new Base64InputStream( new FileInputStream(feedContent.getValue()), false, 80, new byte[] { (byte) '\n' })); } else { input = new BufferedInputStream(new FileInputStream(feedContent.getValue())); } // MD5 on the fly DigestInputStream dis = new DigestInputStream(input, md); if (connectorInstance.getConnectorType().getName().equals("mailbox-connector")) { // FIXME : a supprimer et ajouter un Detector qui detecte // correctement les fichiers eml // CompositeParser parser = new AutoDetectParser(); // Map<String, Parser> parsers = parser.getParsers(); // parsers.put("text/plain", new // EmlParser());//message/rfc822 // parser.setParsers(parsers); // Autre pb avec detection des fichiers eml Parser parser = new EmlParser(); parser.parse(dis, handler, metadata, parseContext); } else { // IOUtils.copy(input, new FileOutputStream(new // File("C:/tmp/test.pdf"))); PARSER.parse(dis, handler, metadata, parseContext); } md5s.add(Base64.encodeBase64String(md.digest())); for (String name : metadata.names()) { for (String content : metadata.getValues(name)) { if (!"null".equals(content)) { RecordMeta meta = new RecordMeta(); ConnectorInstanceMeta connectorInstanceMeta = connectorInstance.getOrCreateMeta(name); if (connectorInstanceMeta.getId() == null) { connectorInstanceServices.makePersistent(connectorInstance); } meta.setConnectorInstanceMeta(connectorInstanceMeta); meta.setContent(content); metas.add(meta); } } } String contentString = handler.toString(); // remove the duplication of white space, Bin contentBuffer.append(contentString.replaceAll("(\\s){2,}", "$1")); } catch (Throwable e) { LOG.warning("Could not parse document " + StringUtils.defaultString(url) + " for connector : " + connectorInstance.getName() + " Message: " + e.getMessage()); } finally { IOUtils.closeQuietly(input); if (feedContent != null) { FileUtils.deleteQuietly(feedContent.getValue()); } } } contentParse.setContent(contentBuffer.toString()); contentParse.setMd5(md5s); return contentParse; }
From source file:com.evrythng.java.wrapper.core.EvrythngServiceBase.java
protected String encodeBase64(final InputStream image, final String mime) throws IOException { Base64InputStream b64is = null; StringWriter sw = null;/*from w w w . jav a2 s . co m*/ try { // Base64 encoding WITHOUT line separators b64is = new Base64InputStream(image, BASE64_ENCODE, BASE64_ENCODE_NO_LINE_LENGTH, BASE64_ENCODE_NO_LINE_SEPARATOR); sw = new StringWriter(); IOUtils.copy(b64is, sw); return mime + "," + sw.toString(); } finally { IOUtils.closeQuietly(b64is); IOUtils.closeQuietly(sw); } }
From source file:nl.nn.adapterframework.pipes.Base64Pipe.java
public PipeRunResult doPipe(Object invoer, IPipeLineSession session) throws PipeRunException { Object result = null;/*from w w w . j a va2s . co m*/ if (invoer != null) { if ("encode".equalsIgnoreCase(getDirection())) { InputStream binaryInputStream; if (convert2String) { if (StringUtils.isEmpty(getCharset())) { binaryInputStream = new ByteArrayInputStream(invoer.toString().getBytes()); } else { try { binaryInputStream = new ByteArrayInputStream(invoer.toString().getBytes(getCharset())); } catch (UnsupportedEncodingException e) { throw new PipeRunException(this, "cannot encode message using charset [" + getCharset() + "]", e); } } } else if (invoer instanceof InputStream) { binaryInputStream = (InputStream) invoer; } else { binaryInputStream = new ByteArrayInputStream((byte[]) invoer); } try { result = Misc.streamToString( new Base64InputStream(binaryInputStream, true, getLineLength(), lineSeparatorArray), null, false); } catch (IOException e) { throw new PipeRunException(this, "cannot encode message from inputstream", e); } } else { String in; if (invoer instanceof InputStream) { try { in = Misc.streamToString((InputStream) invoer, null, false); } catch (IOException e) { throw new PipeRunException(this, "cannot read inputstream", e); } } else { in = invoer.toString(); } try { byte[] data = Base64.decodeBase64(in); if (convert2String) { if (StringUtils.isEmpty(getCharset())) { result = new String(data); } else { result = new String(data, getCharset()); } } else { result = data; } } catch (IOException e) { throw new PipeRunException(this, getLogPrefix(session) + "cannot decode base64, charset [" + getCharset() + "]", e); } } } else { log.debug(getLogPrefix(session) + "has null input, returning null"); } return new PipeRunResult(getForward(), result); }
From source file:org.apache.camel.dataformat.base64.Base64DataFormat.java
@Override public Object unmarshal(Exchange exchange, InputStream input) throws Exception { return new Base64InputStream(input, false, lineLength, lineSeparator); }
From source file:org.apache.shindig.gadgets.servlet.ServletUtil.java
/** * Converts the given {@code HttpResponse} into JSON form, with at least * one field, dataUri, containing a Data URI that can be inlined into an HTML page. * Any metadata on the given {@code HttpResponse} is also added as fields. * /*from w w w . ja va 2s.co m*/ * @param response Input HttpResponse to convert to JSON. * @return JSON-containing HttpResponse. * @throws IOException If there are problems reading from {@code response}. */ public static HttpResponse convertToJsonResponse(HttpResponse response) throws IOException { // Pull out charset, if present. If not, this operation simply returns contentType. String contentType = response.getHeader("Content-Type"); if (contentType == null) { contentType = ""; } else if (contentType.contains(";")) { contentType = StringUtils.split(contentType, ';')[0].trim(); } // First and most importantly, emit dataUri. // Do so in streaming fashion, to avoid needless buffering. ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("{\n "); pw.write(DATA_URI_KEY); pw.write(":'data:"); pw.write(contentType); pw.write(";base64;charset="); pw.write(response.getEncoding()); pw.write(","); pw.flush(); // Stream out the base64-encoded data. // Ctor args indicate to encode w/o line breaks. Base64InputStream b64input = new Base64InputStream(response.getResponse(), true, 0, null); byte[] buf = new byte[1024]; int read = -1; try { while ((read = b64input.read(buf, 0, 1024)) > 0) { os.write(buf, 0, read); } } finally { IOUtils.closeQuietly(b64input); } // Complete the JSON object. pw.write("',\n "); boolean first = true; for (Map.Entry<String, String> metaEntry : response.getMetadata().entrySet()) { if (DATA_URI_KEY.equals(metaEntry.getKey())) continue; if (!first) { pw.write(",\n "); } first = false; pw.write("'"); pw.write(StringEscapeUtils.escapeJavaScript(metaEntry.getKey()).replace("'", "\'")); pw.write("':'"); pw.write(StringEscapeUtils.escapeJavaScript(metaEntry.getValue()).replace("'", "\'")); pw.write("'"); } pw.write("\n}"); pw.flush(); return new HttpResponseBuilder().setHeader("Content-Type", "application/json") .setResponseNoCopy(os.toByteArray()).create(); }