List of usage examples for org.apache.commons.codec.binary Base64InputStream Base64InputStream
public Base64InputStream(InputStream in, boolean doEncode)
From source file:de.drop_converter.plugins.binary_convert.Base642Data.java
@Override public boolean importData(TransferSupport support) throws ConverterException { try {/*from w ww .j av a 2s . c o m*/ if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { List<File> files = (List<File>) support.getTransferable() .getTransferData(DataFlavor.javaFileListFlavor); for (File file : files) { FileInputStream fis = null; Base64InputStream base64IS = null; OutputStream out = null; try { fis = new FileInputStream(file); base64IS = new Base64InputStream(fis, false); out = getOutputStream(file, ".bin"); IOUtils.copy(base64IS, out); } catch (Exception e) { throw new ConverterException(e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(base64IS); IOUtils.closeQuietly(fis); } } return true; } else if (support.isDataFlavorSupported(DataFlavor.stringFlavor)) { String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor); OutputStream out = null; try { byte[] encode = new Base64().decode(data.getBytes()); out = getOutputStream(null, ".bin"); out.write(encode); } catch (Exception e) { throw new ConverterException(e); } finally { IOUtils.closeQuietly(out); } } } catch (Exception e) { throw new ConverterException(e); } return false; }
From source file:de.drop_converter.plugins.binary_convert.Data2Base64.java
@Override public boolean importData(TransferSupport support) throws ConverterException { try {//from w w w. ja v a2 s. c o m if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { List<File> files = (List<File>) support.getTransferable() .getTransferData(DataFlavor.javaFileListFlavor); for (File file : files) { FileInputStream fis = null; Base64InputStream base64IS = null; OutputStream out = null; try { fis = new FileInputStream(file); base64IS = new Base64InputStream(fis, true); out = getOutputStream(file, ".base64"); IOUtils.copy(base64IS, out); } catch (Exception e) { throw new ConverterException(e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(base64IS); IOUtils.closeQuietly(fis); } } return true; } else if (support.isDataFlavorSupported(DataFlavor.stringFlavor)) { String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor); OutputStream out = null; try { byte[] encode = new Base64().encode(data.getBytes()); out = getOutputStream(null, ".base64"); out.write(encode); } catch (Exception e) { throw new ConverterException(e); } finally { IOUtils.closeQuietly(out); } } } catch (Exception e) { throw new ConverterException(e); } return false; }
From source file:com.demandware.vulnapp.challenge.impl.MD5Challenge.java
/** * attempt to copy the contents of the war file to a base64 encoded text file *//*from w w w . j ava 2 s . co m*/ private void generateB64FileForWar() { String troot = DivaApp.getInstance().getInformation(Dictionary.TOMCAT_ROOT); if (troot != null && !"".equals(troot)) { File root = new File(troot); root.mkdirs(); String warName = DivaApp.getInstance().getInformation(Dictionary.WAR_NAME); File war = Helpers.findFile(root, warName); if (war == null) { war = Helpers.findFile(root, "DIVA.war"); } if (war != null) { System.out.println("Copying War from " + war.getAbsolutePath()); try (InputStream is = new BufferedInputStream( new Base64InputStream(new FileInputStream(war), true)); BufferedWriter bw = new BufferedWriter(new FileWriter(this.b64WarLocation))) { IOUtils.copy(is, bw); this.b64WarMade = true; } catch (IOException e) { e.printStackTrace(); } } } }
From source file:net.ontopia.topicmaps.core.OccurrenceTest.java
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); assertTrue("Occurrence datatype is incorrect", Objects.equals(DataTypes.TYPE_BINARY, occurrence.getDataType())); // read and decode occurrence content Reader ro = occurrence.getReader(); assertTrue("Reader value is null", ro != null); InputStream in = new Base64InputStream(new ReaderInputStream(ro, "utf-8"), false); try {/*from w ww .j a v a 2 s . c om*/ OutputStream out = new FileOutputStream("/tmp/blob.gif"); try { IOUtils.copy(in, out); } finally { out.close(); } } finally { in.close(); } }
From source file:com.pearson.pdn.learningstudio.core.AbstractService.java
/** * Performs HTTP operations using the selected authentication method * /*from w w w .ja va 2s. co m*/ * @param extraHeaders Extra headers to include in the request * @param method The HTTP Method to user * @param relativeUrl The URL after .com (/me) * @param body The body of the message * @return Output in the preferred data format * @throws IOException */ protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl, String body) throws IOException { if (body == null) { body = ""; } // append .xml extension when XML data format enabled. if (dataFormat == DataFormat.XML) { logger.debug("Using XML extension on route"); String queryString = ""; int queryStringIndex = relativeUrl.indexOf('?'); if (queryStringIndex != -1) { queryString = relativeUrl.substring(queryStringIndex); relativeUrl = relativeUrl.substring(0, queryStringIndex); } String compareUrl = relativeUrl.toLowerCase(); if (!compareUrl.endsWith(".xml")) { relativeUrl += ".xml"; } if (queryStringIndex != -1) { relativeUrl += queryString; } } final String fullUrl = API_DOMAIN + relativeUrl; if (logger.isDebugEnabled()) { logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body); } URL url = new URL(fullUrl); Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body); if (oauthHeaders == null) { throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods"); } if (extraHeaders != null) { for (String key : extraHeaders.keySet()) { if (!oauthHeaders.containsKey(key)) { oauthHeaders.put(key, extraHeaders.get(key)); } else { throw new RuntimeException("Extra headers can not include OAuth headers"); } } } HttpsURLConnection request = (HttpsURLConnection) url.openConnection(); try { request.setRequestMethod(method.toString()); Set<String> oauthHeaderKeys = oauthHeaders.keySet(); for (String oauthHeaderKey : oauthHeaderKeys) { request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey)); } request.addRequestProperty("User-Agent", getServiceIdentifier()); if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) { if (dataFormat == DataFormat.XML) { request.setRequestProperty("Content-Type", "application/xml"); } else { request.setRequestProperty("Content-Type", "application/json"); } request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length)); request.setDoOutput(true); DataOutputStream out = new DataOutputStream(request.getOutputStream()); try { out.writeBytes(body); out.flush(); } finally { out.close(); } } Response response = new Response(); response.setMethod(method.toString()); response.setUrl(url.toString()); response.setStatusCode(request.getResponseCode()); response.setStatusMessage(request.getResponseMessage()); response.setHeaders(request.getHeaderFields()); InputStream inputStream = null; if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) { inputStream = request.getInputStream(); } else { inputStream = request.getErrorStream(); } boolean isBinary = false; if (inputStream != null) { StringBuilder responseBody = new StringBuilder(); String contentType = request.getContentType(); if (contentType != null) { if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml") && !contentType.startsWith("application/json")) { // assume binary isBinary = true; inputStream = new Base64InputStream(inputStream, true); // base64 encode } } BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); try { String line = null; while ((line = bufferedReader.readLine()) != null) { responseBody.append(line); } } finally { bufferedReader.close(); } response.setContentType(contentType); if (isBinary) { String content = responseBody.toString(); if (content.length() == 0) { response.setBinaryContent(new byte[0]); } else { response.setBinaryContent(Base64.decodeBase64(responseBody.toString())); } } else { response.setContent(responseBody.toString()); } } if (logger.isDebugEnabled()) { if (isBinary) { logger.debug("RESPONSE - binary response omitted"); } else { logger.debug("RESPONSE - " + response.toString()); } } return response; } finally { request.disconnect(); } }
From source file:com.demandware.vulnapp.challenge.impl.SQLIChallenge.java
/** * Given a statement, pull up to MAX_RESULTS from the results of the query * @param ps prepared and executed statement (this method will not close this) * @return String containing a formatted output string * @throws SQLException/* ww w. ja v a 2s . com*/ */ private String generateOutputForChallengeQuery(PreparedStatement ps) throws SQLException { StringBuilder sb = new StringBuilder(); ResultSet rs = ps.getResultSet(); int i = 0; while (i < MAX_RESULTS && rs.next()) { try { sb.append("<tr>"); sb.append("<td>"); String name = rs.getString(1); sb.append(name); sb.append("</td>"); sb.append("<td>"); String blurb = rs.getString(2); sb.append(blurb); sb.append("</td>"); String picData = ""; try { Base64InputStream pic = new Base64InputStream(rs.getBinaryStream(3), true); picData = IOUtils.toString(pic); } catch (Exception e) { picData = e.getMessage(); } sb.append("<td>"); sb.append("<img src=\"data:image/jpg;base64,").append(picData).append("\"/>"); sb.append("</td>"); sb.append("</tr>"); } catch (Exception e) { e.printStackTrace(); } } return sb.toString(); }
From source file:gov.osti.services.Metadata.java
/** * Convert a File InputStream to a Base64 string. * * @param in the InputStream containing the file content * @return the Base64 string of the file * @throws IOException on IO errors//w w w . j a v a2s . com */ private static String convertBase64(InputStream in) throws IOException { Base64InputStream b64in = new Base64InputStream(in, true); return IOUtils.toString(b64in, "UTF-8"); }
From source file:nl.nn.adapterframework.senders.SambaSender.java
@Override public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException { ParameterValueList pvl = null;/*from w w w .j a va 2 s . c o m*/ try { if (prc != null && paramList != null) { pvl = prc.getValues(paramList); } } catch (ParameterException e) { throw new SenderException( getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e); } SmbFile file; try { file = new SmbFile(smbContext, message); } catch (IOException e) { throw new SenderException(getLogPrefix() + "unable to get SMB file", e); } try { if (getAction().equalsIgnoreCase("download")) { SmbFileInputStream is = new SmbFileInputStream(file); InputStream base64 = new Base64InputStream(is, true); return Misc.streamToString(base64); } else if (getAction().equalsIgnoreCase("list")) { return listFilesInDirectory(file); } else if (getAction().equalsIgnoreCase("upload")) { Object paramValue = pvl.getParameterValue("file").getValue(); byte[] fileBytes = null; if (paramValue instanceof InputStream) fileBytes = Misc.streamToBytes((InputStream) paramValue); else if (paramValue instanceof byte[]) fileBytes = (byte[]) paramValue; else if (paramValue instanceof String) fileBytes = ((String) paramValue).getBytes(Misc.DEFAULT_INPUT_STREAM_ENCODING); else throw new SenderException("expected InputStream, ByteArray or String but got [" + paramValue.getClass().getName() + "] instead"); SmbFileOutputStream out = new SmbFileOutputStream(file); out.write(fileBytes); out.close(); return getFileAsXmlBuilder(new SmbFile(smbContext, message)).toXML(); } else if (getAction().equalsIgnoreCase("delete")) { if (!file.exists()) throw new SenderException("file not found"); if (file.isFile()) file.delete(); else throw new SenderException("trying to remove a directory instead of a file"); } else if (getAction().equalsIgnoreCase("mkdir")) { if (isForced()) file.mkdirs(); else file.mkdir(); } else if (getAction().equalsIgnoreCase("rmdir")) { if (!file.exists()) throw new SenderException("folder not found"); if (file.isDirectory()) file.delete(); else throw new SenderException("trying to remove a file instead of a directory"); } else if (getAction().equalsIgnoreCase("rename")) { String destination = pvl.getParameterValue("destination").asStringValue(null); if (destination == null) throw new SenderException("unknown destination[+destination+]"); SmbFile dest = new SmbFile(smbContext, destination); if (isForced() && dest.exists()) dest.delete(); file.renameTo(dest); } } catch (Exception e) { //Different types of SMB exceptions can be thrown, no exception means success.. Got to catch them all! throw new SenderException( getLogPrefix() + "unable to process action for SmbFile [" + file.getCanonicalPath() + "]", e); } return "<result>ok</result>"; }
From source file:nl.nn.adapterframework.util.JdbcUtil.java
public static String getBlobAsString(Blob blob, String column, String charset, boolean xmlEncode, boolean blobIsCompressed, boolean blobSmartGet, boolean encodeBlobBase64) throws IOException, JdbcException, SQLException, JMSException { if (encodeBlobBase64) { InputStream blobStream = JdbcUtil.getBlobInputStream(blob, column, blobIsCompressed); return Misc.streamToString(new Base64InputStream(blobStream, true), null, false); }/*from w ww . j av a 2s .c o m*/ if (blobSmartGet) { if (blob == null) { log.debug("no blob found in column [" + column + "]"); return null; } int bl = (int) blob.length(); InputStream is = blob.getBinaryStream(); byte[] buf = new byte[bl]; int bl1 = is.read(buf); Inflater decompressor = new Inflater(); decompressor.setInput(buf); ByteArrayOutputStream bos = new ByteArrayOutputStream(buf.length); byte[] bufDecomp = new byte[1024]; boolean decompresOK = true; while (!decompressor.finished()) { try { int count = decompressor.inflate(bufDecomp); if (count == 0) { break; } bos.write(bufDecomp, 0, count); } catch (DataFormatException e) { log.debug("message in column [" + column + "] is not compressed"); decompresOK = false; break; } } bos.close(); if (decompresOK) buf = bos.toByteArray(); Object result = null; ObjectInputStream ois = null; boolean objectOK = true; try { ByteArrayInputStream bis = new ByteArrayInputStream(buf); ois = new ObjectInputStream(bis); result = ois.readObject(); } catch (Exception e) { log.debug("message in column [" + column + "] is probably not a serialized object: " + e.getClass().getName()); objectOK = false; } if (ois != null) ois.close(); String rawMessage; if (objectOK) { if (result instanceof IMessageWrapper) { rawMessage = ((IMessageWrapper) result).getText(); } else if (result instanceof TextMessage) { rawMessage = ((TextMessage) result).getText(); } else { rawMessage = (String) result; } } else { rawMessage = new String(buf, charset); } String message = XmlUtils.encodeCdataString(rawMessage); return message; } return Misc.readerToString(getBlobReader(blob, column, charset, blobIsCompressed), null, xmlEncode); }
From source file:org.apache.xml.security.stax.impl.transformer.TransformBase64Decode.java
@Override public void transform(InputStream inputStream) throws XMLStreamException { if (getOutputStream() != null) { super.transform(inputStream); } else {//from ww w.ja va 2 s .c o m super.transform(new Base64InputStream(inputStream, false)); } }