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

来源:互联网 发布:大型网络3d游戏 编辑:程序博客网 时间:2024/06/05 03:15

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

The following are top voted examples for showing how to use org.apache.commons.codec.binary.Base64InputStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples. 


Apache commons codec 的 base64 应用,将文件、字符串、byte转换为 base64.

Example 1
Project: burrow-java   File: Encoder.java View source codeVote up6 votes
public static int[] unpack(String S) {    try {        ByteArrayInputStream base = new ByteArrayInputStream(S.getBytes());        ObjectInputStream ois = new ObjectInputStream(new Base64InputStream(base));        int[] result = (int[]) ois.readObject();        ois.close();        return result;    } catch (ClassCastException cce) {        System.err.println("Error: Malformed job");        System.exit(1);    } catch (IOException ioe) {        //Shouldn't be possible from an in memory source    } catch (ClassNotFoundException cnfe) {        //Impossible, pretty sure int[] exists everywhere    }    throw new Error("Should not be reached.");} 
Example 2
Project: WPS   File: IOUtils.java View source codeVote up6 votes
public static File writeBase64ToFile(InputStream input, String extension)throws IOException {       File file = File.createTempFile(               "file" + UUID.randomUUID(),               "." + extension,               new File(System.getProperty("java.io.tmpdir")));       OutputStream outputStream = null;       try {           outputStream = new FileOutputStream(file);           copyLarge(new Base64InputStream(input), outputStream);       } finally {           closeQuietly(outputStream);       }return file;} 
Example 3
Project: opensearchserver   File: StreamLimiterBase64.java View source codeVote up6 votes
@Overrideprotected void loadOutputCache() throws LimitException, IOException {InputStream is = null;Base64InputStream b64is = null;try {is = new LargeStringInputString(base64text, 131072);b64is = new Base64InputStream(is);loadOutputCache(b64is);} finally {IOUtils.close(b64is, is);}} 
Example 4
Project: spice   File: RsaAesPlexusEncryptor.java View source codeVote up6 votes
protected PublicKey readPublicKey( InputStream keyInput )    throws IOException, GeneralSecurityException{    InputStream input = new Base64InputStream( keyInput );    byte[] encKey = IOUtil.toByteArray( input );    IOUtil.close( input );    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec( encKey );    KeyFactory keyFactory = KeyFactory.getInstance( "RSA" );    PublicKey pubKey = keyFactory.generatePublic( pubKeySpec );    return pubKey;} 
Example 5
Project: pades_signing_2.1.5   File: Base64Helper.java View source codeVote up6 votes
public static byte[] decodeFromFile(String string) throws IOException {FileInputStream fis = new FileInputStream(string);Base64InputStream is = new Base64InputStream(fis);ByteArrayOutputStream baos = new ByteArrayOutputStream();Streams.pipeAll(is, baos);return baos.toByteArray();} 
Example 6
Project: confluence2wordpress   File: CodecUtils.java View source codeVote up6 votes
public static String decodeAndExpand(String encoded) throws IOException {GZIPInputStream gzis = new GZIPInputStream(new Base64InputStream(new ByteArrayInputStream(encoded.getBytes(UTF_8))));try {return IOUtils.toString(gzis, UTF_8);} finally {gzis.close();}} 
Example 7
Project: plato   File: ProjectExportAction.java View source codeVote up6 votes
/** * Dumps binary data to provided file. It results in an XML file with a * single element: data. *  * @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();    }        } 
Example 8
Project: solarnetwork-common   File: JavaBeanXmlSerializerTest.java View source codeVote up6 votes
@Testpublic void testParseSimpleEncoded() throws IOException {JavaBeanXmlSerializer helper = new JavaBeanXmlSerializer();InputStream in = new GZIPInputStream(new Base64InputStream(getClass().getResourceAsStream("test1.b64")));Map<String, Object> result = helper.parseXml(in);assertNotNull(result);assertEquals(4, result.size());assertEquals("23466f06", result.get("confirmationKey"));assertEquals("2011-09-16T05:07:32.579Z", result.get("expiration"));assertEquals("123123", result.get("nodeId"));assertEquals("foo@localhost", result.get("username"));} 
Example 9
Project: iaf   File: JdbcUtil.java View source codeVote up6 votes
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 10
Project: evrythng-java-sdk   File: EvrythngServiceBase.java View source codeVote up6 votes
protected String encodeBase64(final InputStream image, final String mime) throws IOException {Base64InputStream b64is = null;StringWriter sw = null;try {b64is = new Base64InputStream(image, true);sw = new StringWriter();IOUtils.copy(b64is, sw);return mime + "," + sw.toString();} finally {IOUtils.closeQuietly(b64is);IOUtils.closeQuietly(sw);}} 
Example 11
Project: OG-Platform   File: Compressor.java View source codeVote up6 votes
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);  }  oStream.flush();} 
Example 12
Project: OpenEMRConnect   File: Daemon.java View source codeVote up6 votes
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;    try {        FileInputStream message = new FileInputStream(filename);        Base64InputStream message64 = new Base64InputStream(message, true, -1, null);        requestEntity = new InputStreamRequestEntity(message64, "application/octet-stream");    } catch (FileNotFoundException e) {        Mediator.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;        Mediator.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Request timed out.  Not retrying.", e);    } catch (HttpException e) {        returnStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;        Mediator.getLogger(Daemon.class.getName()).log(Level.SEVERE, "HTTP exception.  Not retrying.", e);    } catch (ConnectException e) {        returnStatus = HttpStatus.SC_SERVICE_UNAVAILABLE;        Mediator.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Service unavailable.  Not retrying.", e);    } catch (UnknownHostException e) {        returnStatus = HttpStatus.SC_NOT_FOUND;        Mediator.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Not found.  Not retrying.", e);    } catch (IOException e) {        returnStatus = HttpStatus.SC_GATEWAY_TIMEOUT;        Mediator.getLogger(Daemon.class.getName()).log(Level.SEVERE, "IO exception.  Not retrying.", e);    } finally {        httpPost.releaseConnection();    }    return returnStatus == HttpStatus.SC_OK;} 
Example 13
Project: exist   File: Base64BinaryValueTypeTest.java View source codeVote up6 votes
@Testpublic void verify_validBase64_passes_large_string() throws XPathException, IOException {    File home = ConfigurationHelper.getExistHome();    File binaryFile = new File(home, "webapp/logo.jpg");    InputStream is = null;    ByteArrayOutputStream baos = null;    String base64data = null;    try {        is = new Base64InputStream(new FileInputStream(binaryFile), true, -1, null);        baos  = new ByteArrayOutputStream();        byte buf[] = new byte[1024];        int read = -1;        while((read = is.read(buf)) > -1) {            baos.write(buf, 0, read);        }        base64data = new String(baos.toByteArray());    } finally {        if(is != null) { is.close(); }        if(baos != null) { baos.close(); }    }    assertNotNull(base64data);    TestableBase64BinaryValueType base64Type = new TestableBase64BinaryValueType();    base64Type.verifyString(base64data);} 
Example 14
Project: adf-selenium   File: FileOutputType.java View source codeVote up6 votes
@Overridepublic 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 15
Project: cloudeventbus   File: CertificateUtils.java View source codeVote up6 votes
private static void loadCertificates(Path path, Collection<Certificate> certificates) throws IOException {try (final InputStream fileIn = Files.newInputStream(path);final InputStream in = new Base64InputStream(fileIn)) {CertificateStoreLoader.load(in, certificates);}} 
Example 16
Project: pdfcombinercco   File: Application.java View source codeVote up6 votes
/** * Decodes a base64 encoded file to binary. * @param base64FileName * @param newFileName * @throws Exception */public static void decodeBase64File(String base64FileName, String newFileName) throws Exception {int BUFFER_SIZE = 4096;byte[] buffer = new byte[BUFFER_SIZE];Logger.info("   open input stream");InputStream input = new Base64InputStream(new FileInputStream(base64FileName));Logger.info("   open output stream");OutputStream output = new FileOutputStream(newFileName);int n = input.read(buffer, 0, BUFFER_SIZE);while (n >= 0) {Logger.info("   reading");output.write(buffer, 0, n);n = input.read(buffer, 0, BUFFER_SIZE);}Logger.info("   closing streams");input.close();output.close();} 
Example 17
Project: miso-lims   File: IntegrationUtils.java View source codeVote up6 votes
public static byte[] decompress(byte[] contentBytes) throws IOException {  ByteArrayOutputStream out = new ByteArrayOutputStream();  GZIPInputStream bis = new GZIPInputStream(new Base64InputStream(new ByteArrayInputStream(contentBytes)));  byte[] buffer = new byte[1024*4];  int n = 0;  while (-1 != (n = bis.read(buffer))) {    out.write(buffer, 0, n);  }  return out.toByteArray();} 
Example 18
Project: palava-media   File: Create.java View source codeVote up6 votes
@RequiresPermissions(MediaPermissions.ASSET_CREATE)@Transactional@Overridepublic void execute(IpcCall call, Map<String, Object> result) throws IpcCommandExecutionException {    final IpcArguments arguments = call.getArguments();    final AssetBase asset = provider.get();    final String name = arguments.getString(AssetConstants.NAME);    final byte[] binary = arguments.getString(AssetConstants.BINARY).getBytes(Charset.forName("UTF-8"));    final String title = arguments.getString(AssetConstants.TITLE, null);    final String description = arguments.getString(AssetConstants.DESCRIPTION, null);    final Map<Object, Object> metaData = arguments.getMap(AssetConstants.META_DATA, null);    final Date expiresAt = arguments.getDate(AssetConstants.EXPIRES_AT, null);    asset.setName(name);        final InputStream stream = new Base64InputStream(new ByteArrayInputStream(binary));    asset.setStream(stream);        asset.setTitle(title);    asset.setDescription(description);    if (metaData == null) {        LOG.debug("No meta data received");    } else {        LOG.debug("Adding new metaData {} to {}", metaData, asset);        for (Entry<Object, Object> entry : metaData.entrySet()) {            final String key = Preconditions.checkNotNull(                entry.getKey(), "Key with value {} is null", entry.getValue()            ).toString();            final String value = entry.getValue() == null ? null : entry.getValue().toString();            asset.getMetaData().put(key, value);        }    }    asset.setExpiresAt(expiresAt);    try {        service.create(asset);    } finally {        try {            stream.close();        } catch (IOException e) {            throw new IpcCommandExecutionException(e);        }    }        result.put(AssetConstants.ASSET, asset);} 
Example 19
Project: solarnetwork-node   File: DefaultSetupService.java View source codeVote up5 votes
@Overridepublic NetworkAssociationDetails decodeVerificationCode(String verificationCode)throws InvalidVerificationCodeException {log.debug("Decoding verification code {}", verificationCode);NetworkAssociationDetails details = new NetworkAssociationDetails();try {JavaBeanXmlSerializer helper = new JavaBeanXmlSerializer();InputStream in = new GZIPInputStream(new Base64InputStream(new ByteArrayInputStream(verificationCode.getBytes())));Map<String, Object> result = helper.parseXml(in);// Get the host serverString hostName = (String) result.get(VERIFICATION_CODE_HOST_NAME);if ( hostName == null ) {// Use the defaultlog.debug("Property {} not found in verfication code", VERIFICATION_CODE_HOST_NAME);throw new InvalidVerificationCodeException("Missing host");}details.setHost(hostName);// Get the host portString hostPort = (String) result.get(VERIFICATION_CODE_HOST_PORT);if ( hostPort == null ) {log.debug("Property {} not found in verfication code", VERIFICATION_CODE_HOST_PORT);throw new InvalidVerificationCodeException("Missing port");}try {details.setPort(Integer.valueOf(hostPort));} catch ( NumberFormatException e ) {throw new InvalidVerificationCodeException("Invalid host port value: " + hostPort, e);}// Get the confirmation KeyString confirmationKey = (String) result.get(VERIFICATION_CODE_CONFIRMATION_KEY);if ( confirmationKey == null ) {throw new InvalidVerificationCodeException("Missing confirmation code");}details.setConfirmationKey(confirmationKey);// Get the identity keyString identityKey = (String) result.get(VERIFICATION_CODE_IDENTITY_KEY);if ( identityKey == null ) {throw new InvalidVerificationCodeException("Missing identity key");}details.setIdentityKey(identityKey);// Get the user nameString userName = (String) result.get(VERIFICATION_CODE_USER_NAME_KEY);if ( userName == null ) {throw new InvalidVerificationCodeException("Missing username");}details.setUsername(userName);// Get the expirationString expiration = (String) result.get(VERIFICATION_CODE_EXPIRATION_KEY);if ( expiration == null ) {throw new InvalidVerificationCodeException(VERIFICATION_CODE_EXPIRATION_KEY+ " not found in verification code: " + verificationCode);}try {DateTimeFormatter fmt = ISODateTimeFormat.dateTime();DateTime expirationDate = fmt.parseDateTime(expiration);details.setExpiration(expirationDate.toDate());} catch ( IllegalArgumentException e ) {throw new InvalidVerificationCodeException("Invalid expiration date value", e);}// Get the TLS settingString forceSSL = (String) result.get(VERIFICATION_CODE_FORCE_TLS);details.setForceTLS(forceSSL == null ? false : Boolean.valueOf(forceSSL));return details;} catch ( InvalidVerificationCodeException e ) {throw e;} catch ( Exception e ) {// Runtime/IO errors can come from webFormGetForBeanthrow new InvalidVerificationCodeException("Error while trying to decode verfication code: "+ verificationCode, e);}} 
Example 20
Project: oxalis   File: MdnMimeMessageInspector.java View source codeVote up5 votes
public Map<String, String> getMdnFields() {    Map<String, String> ret = new HashMap<String, String>();    try {        BodyPart bp = getMessageDispositionNotificationPart();        boolean contentIsBase64Encoded = false;        //        // look for base64 transfer encoded MDN's (when Content-Transfer-Encoding is present)        //        // Content-Type: message/disposition-notification        // Content-Transfer-Encoding: base64        //        // "Content-Transfer-Encoding not used in HTTP transport Because HTTP, unlike SMTP,        // does not have an early history involving 7-bit restriction.        // There is no need to use the Content Transfer Encodings of MIME."        //        String[] contentTransferEncodings = bp.getHeader("Content-Transfer-Encoding");        if (contentTransferEncodings != null && contentTransferEncodings.length > 0) {            if (contentTransferEncodings.length > 1) log.warn("MDN has multiple Content-Transfer-Encoding, we only try the first one");            String encoding = contentTransferEncodings[0];            if (encoding == null) encoding = "";            encoding = encoding.trim();            log.info("MDN specifies Content-Transfer-Encoding : '" + encoding + "'");            if ("base64".equalsIgnoreCase(encoding)) {                contentIsBase64Encoded = true;            }        }        Object content = bp.getContent();        if (content instanceof InputStream) {            InputStream contentInputStream = (InputStream) content;            if (contentIsBase64Encoded) {                log.debug("MDN seems to be base64 encoded, wrapping content stream in Base64 decoding stream");                contentInputStream = new Base64InputStream(contentInputStream); // wrap in base64 decoding stream            }            BufferedReader r = new BufferedReader(new InputStreamReader(contentInputStream));            while (r.ready()) {                String line = r.readLine();                int firstColon = line.indexOf(":"); // "Disposition: ......"                if (firstColon > 0) {                    String key = line.substring(0, firstColon).trim(); // up to :                    String value = line.substring(firstColon + 1).trim(); // skip :                    ret.put(key, value);                }            }        } else {            throw new Exception("Unsupported MDN content, expected InputStream found @ " + content.toString());        }    } catch (Exception e) {        throw new IllegalStateException("Unable to retrieve the values from the MDN : " + e.getMessage(), e);    }    return ret;}

原文来自:http://www.programcreek.com/java-api-examples/index.php?api=org.apache.commons.codec.binary.Base64InputStream
0 0
原创粉丝点击