org.jboss.resteasy.util.Base64类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(17.5k)|赞(0)|评价(0)|浏览(124)

本文整理了Java中org.jboss.resteasy.util.Base64类的一些代码示例,展示了Base64类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Base64类的具体详情如下:
包路径:org.jboss.resteasy.util.Base64
类名称:Base64

Base64介绍

[英]Encodes and decodes to and from Base64 notation.

Homepage: http://iharder.net/base64.

Example:

String encoded = Base64.encode( myByteArray );
byte[] myByteArray = Base64.decode( encoded );

The options parameter, which appears in a few places, is used to pass several pieces of information to the encoder. In the "higher level" methods such as encodeBytes( bytes, options ) the options parameter can be used to indicate such things as first gzipping the bytes before encoding them, not inserting linefeeds, and encoding using the URL-safe and Ordered dialects.

Note, according to RFC3548, Section 2.1, implementations should not add line feeds unless explicitly told to do so. I've got Base64 set to this behavior now, although earlier versions broke lines by default.

The constants defined in Base64 can be OR-ed together to combine options, so you might make a call like this:

String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );

to compress the data before encoding it and then making the output have newline characters.

Also...
String encoded = Base64.encodeBytes( crazyString.getBytes() );

Change Log:

  • v2.3.7 - Fixed subtle bug when base 64 input stream contained the value 01111111, which is an invalid base 64 character but should not throw an ArrayIndexOutOfBoundsException either. Led to discovery of mishandling (or potential for better handling) of other bad input characters. You should now get an IOException if you try decoding something that has bad characters in it.

  • v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded string ended in the last column; the buffer was not properly shrunk and contained an extra (null) byte that made it into the string.

  • v2.3.5 - Fixed bug in #encodeFromFile where estimated buffer size was wrong for files of size 31, 34, and 37 bytes.

  • v2.3.4 - Fixed bug when working with gzipped streams whereby flushing the Base64.OutputStream closed the Base64 encoding (by padding with equals signs) too soon. Also added an option to suppress the automatic decoding of gzipped streams. Also added experimental support for specifying a class loader when using the #decodeToObject(java.lang.String,int,java.lang.ClassLoader)method.

  • v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java footprint with its CharEncoders and so forth. Fixed some javadocs that were inconsistent. Removed imports and specified things like java.io.IOException explicitly inline.

  • v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the final encoded data will be so that the code doesn't have to create two output arrays: an oversized initial one and then a final, exact-sized one. Big win when using the #encodeBytesToBytes(byte[]) family of methods (and not using the gzip options which uses a different mechanism with streams and stuff).

  • v2.3.1 - Added #encodeBytesToBytes(byte[],int,int,int) and some similar helper methods to be more efficient with memory by not returning a String but just a byte array.

  • v2.3 - This is not a drop-in replacement! This is two years of comments and bug fixes queued up and finally executed. Thanks to everyone who sent me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else. Much bad coding was cleaned up including throwing exceptions where necessary instead of returning null values or something similar. Here are some changes that may affect you:

  • Does not break lines, by default. This is to keep in compliance with RFC3548.

    • Throws exceptions instead of returning null values. Because some operations (especially those that may permit the GZIP option) use IO streams, there is a possiblity of an java.io.IOException being thrown. After some discussion and thought, I've changed the behavior of the methods to throw java.io.IOExceptions rather than return null if ever there's an error. I think this is more appropriate, though it will require some changes to your code. Sorry, it should have been done this way to begin with.
    • Removed all references to System.out, System.err, and the like. Shame on me. All I can say is sorry they were ever there.
    • Throws NullPointerExceptions and IllegalArgumentExceptions as needed such as when passed arrays are null or offsets are invalid.
    • Cleaned up as much javadoc as I could to avoid any javadoc warnings. This was especially annoying before for people who were thorough in their own projects and then had gobs of javadoc warnings on this file.
  • v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug when using very small files (~< 40 bytes).

  1. v2.2 - Added some helper methods for encoding/decoding directly from one file to the next. Also added a main() method to support command line encoding/decoding from one file to the next. Also added these Base64 dialects:

  2. The default is RFC3548 format.

    1. Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates URL and file name friendly format as described in Section 4 of RFC3548. http://www.faqs.org/rfcs/rfc3548.html
    2. Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates URL and file name friendly format that preserves lexical ordering as described in http://www.faqs.org/qa/rfcc-1940.html
      Special thanks to Jim Kellerman at http://www.powerset.com/ for contributing the new Base64 dialects.
  3. v2.1 - Cleaned up javadoc comments and unused variables and methods. Added some convenience methods for reading and writing to and from files.

  4. v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems with other encodings (like EBCDIC).

  5. v2.0.1 - Fixed an error when decoding a single byte, that is, when the encoded data was a single byte.

  6. v2.0 - I got rid of methods that used booleans to set options. Now everything is more consolidated and cleaner. The code now detects when data that's being decoded is gzip-compressed and will decompress it automatically. Generally things are cleaner. You'll probably have to change some method calls that you were making to support the new options format (ints that you "OR" together).

  7. v1.5.1 - Fixed bug when decompressing and decoding to a byte[] using decode( String s, boolean gzipCompressed ). Added the ability to "suspend" encoding in the Output Stream so you can turn on and off the encoding if you need to embed base64 data in an otherwise "normal" stream (like an XML file).

  8. v1.5 - Output stream pases on flush() command but doesn't do anything itself. This helps when using GZIP streams. Added the ability to GZip-compress objects before encoding them.

  9. v1.4 - Added helper methods to read/write files.

  10. v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.

  11. v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream where last buffer being read, if not completely full, was not returned.

  12. v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.

  13. v1.3.3 - Fixed I/O streams which were totally messed up.

I am placing this code in the Public Domain. Do with it as you will. This software comes with no guarantees or warranties but with plenty of well-wishing instead! Please visit http://iharder.net/base64 periodically to check for updates or to contribute improvements.
[中]对Base64符号进行编码和解码。
主页:http://iharder.net/base64
例子:
String encoded = Base64.encode( myByteArray );
byte[] myByteArray = Base64.decode( encoded );
options参数出现在几个地方,用于将多条信息传递给编码器。在encodeBytes(bytes,options)等“更高级别”方法中,options参数可用于指示在编码字节之前先压缩字节,不插入换行符,以及使用URL安全和有序方言进行编码。
注意,根据RFC3548,第2.1节,除非明确要求添加换行符,否则实现不应该添加换行符。我现在已经将Base64设置为这种行为,尽管早期版本在默认情况下会中断。
Base64中定义的常量可以合并或合并在一起以组合选项,因此您可以进行如下调用:
String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );
在编码数据之前压缩数据,然后使输出具有换行符。
而且
String encoded = Base64.encodeBytes( crazyString.getBytes() );
更改日志:
*v2。3.7-修复了Base64输入流包含值01111111时的细微错误,该值是无效的Base64字符,但也不应引发ArrayIndexOutOfBoundsException。导致发现错误处理(或可能更好地处理)其他错误输入字符。如果您尝试解码包含坏字符的内容,现在应该会得到一个IOException。
*v2。3.6-修复了断行时的错误,编码字符串的最后一个字节在最后一列结束;缓冲区未正确收缩,并包含一个额外的(空)字节,使其进入字符串。
*v2。3.5-修复了#encodeFromFile中的错误,其中大小为31、34和37字节的文件的估计缓冲区大小错误。
*v2。3.4-修复了处理Gzip流时刷新Base64的错误。OutputStream过早地关闭了Base64编码(通过使用等号填充)。还添加了一个选项来抑制gzip流的自动解码。还添加了在使用#decodeToObject(java.lang.String,int,java.lang.ClassLoader)方法时指定类加载器的实验支持。
*v2。3.3-将默认字符编码更改为US-ASCII,从而减少了其字符编码器的内部Java占用空间,等等。修复了一些不一致的Javadoc。删除了导入和指定的东西,如java。木卫一。IOException显式内联。
*v2。3.2-减少内存占用!最后,对最终编码数据的大小进行了“猜测”,这样代码就不必创建两个输出数组:一个超大的初始数组和一个最终的、精确大小的数组。当使用#encodeBytesToBytes(byte[])方法家族(而不使用gzip选项,它使用不同的机制处理流和内容)时,这是一个巨大的胜利。
*v2。3.1-添加了#encodeBytesToBytes(byte[],int,int,int,int)和一些类似的助手方法,通过不返回字符串而只返回字节数组来提高内存效率。
*v2。3-这不是一个一次性的替代品!这是长达两年的评论和bug修复排队并最终执行。感谢所有给我发邮件的人,很抱歉我没能把你的补丁分发给其他人。许多糟糕的编码都被清除了,包括在必要时抛出异常,而不是返回空值或类似的东西。以下是一些可能会影响您的更改:
**默认情况下不断线。*这是为了遵守RFC3548
**抛出异常而不是返回空值。*因为一些操作(特别是那些允许GZIP选项的操作)使用IO流,所以有可能使用java。木卫一。正在抛出异常。经过一些讨论和思考,我已经改变了方法的行为来抛出java。木卫一。IOExceptions,而不是在出现错误时返回null。我认为这更合适,尽管它需要对代码进行一些更改。对不起,一开始就应该这样做。
**删除对系统的所有引用。退出,系统。呃,等等。*我真丢脸。我所能说的就是他们曾经在那里。
*根据需要抛出NullPointerException和IllegalArgumentException,例如当传递的数组为null或偏移量无效时。
*清理尽可能多的javadoc以避免任何javadoc警告。对于那些在自己的项目中做得很透彻,然后在这个文件上有大量javadoc警告的人来说,这尤其令人讨厌。
*v2。2.1-修复了使用URL_安全和有序编码的错误。修复了使用非常小的文件(~<40字节)时的错误。
1.v2。2-添加了一些辅助方法,用于直接从一个文件到下一个文件进行编码/解码。还添加了main()方法以支持从一个文件到下一个文件的命令行编码/解码。还添加了以下64种基本方言:
1.默认为RFC3548格式。
1.呼叫Base64。setFormat(Base64.Base64_FORMAT.URLSAFE_FORMAT)生成URL和文件名友好格式,如RFC3548第4节所述。http://www.faqs.org/rfcs/rfc3548.html
1.呼叫Base64。setFormat(Base64.Base64\u FORMAT.ORDERED\u FORMAT)生成URL和文件名友好格式,该格式保留词汇顺序,如中所述http://www.faqs.org/qa/rfcc-1940.html
特别感谢{http://www.powerset.com/的吉姆·凯勒曼为新的Base64方言所作的贡献。
1.v2。1-清理了javadoc注释和未使用的变量和方法。添加了一些方便的文件读写方法。
1.v2。0.2-现在在使用其他编码(如EBCDIC)的系统上代码失败的地方指定UTF-8编码。
1.v2。0.1-修复了解码单个字节时的错误,即编码数据为单个字节时的错误。
1.v2。0-我去掉了使用布尔设置选项的方法。现在一切都更加巩固和清洁。代码现在检测正在解码的数据何时被压缩并将自动解压缩。一般来说,情况比较干净。您可能需要更改一些方法调用,以支持新的选项格式(ints,您可以“或”一起使用)。
1.v1。5.1-修复了使用decode( String s, boolean gzipCompressed )解压并解码为字节[]时出现的错误。添加了在输出流中“挂起”编码的功能,因此,如果需要在其他“正常”流(如XML文件)中嵌入base64数据,则可以打开和关闭编码。
1.v1。5-输出流在flush()命令上运行,但本身不执行任何操作。这有助于使用GZIP流。添加了在编码对象之前压缩对象的能力。
1.v1。4-添加了用于读取/写入文件的帮助器方法。
1.v1。3.6-固定输出流。刷新(),以便重置“位置”。
1.v1。3.5-添加了用于打开和关闭换行符的标志。修复了输入流中最后一个被读取的缓冲区(若未完全填满)未返回的错误。
1.v1。3.4-修复了在错误时间抛出“未正确填充的流”错误。
1.v1。3.3-修复了完全混乱的I/O流。
我将此代码置于公共域中。你想怎么做就怎么做。这个软件没有任何保证或保证,但却有很多美好的愿望!请定期访问http://iharder.net/base64,检查更新或作出改进。

代码示例

代码示例来源:origin: weibocom/motan

public static Exception getCause(BuiltResponse resp) {
  if (resp == null || resp.getStatus() != Status.EXPECTATION_FAILED.getStatusCode())
    return null;
  String exceptionClass = resp.getHeaderString(EXCEPTION_HEADER);
  if (!StringUtils.isBlank(exceptionClass)) {
    String body = resp.readEntity(String.class);
    resp.close();
    try {
      ByteArrayInputStream bais = new ByteArrayInputStream(
          Base64.decode(body.getBytes(MotanConstants.DEFAULT_CHARACTER)));
      ObjectInputStream ois = new ObjectInputStream(bais);
      return (Exception) ois.readObject();
    } catch (Exception e) {
      LoggerUtil.error("deserialize " + exceptionClass + " error", e);
    }
  }
  return null;
}

代码示例来源:origin: resteasy/Resteasy

/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
*   GZIP: gzip-compresses object before encoding it.
*   DO_BREAK_LINES: break lines at 76 characters
*     <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param source  The data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @throws java.io.IOException  if there is an error
* @throws NullPointerException if source array is null
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @since 2.0
*/
public static String encodeBytes(byte[] source, int options) throws java.io.IOException
{
 return encodeBytes(source, 0, source.length, options);
}   // end encodeBytes

代码示例来源:origin: weibocom/motan

public static Response serializeError(Exception ex) {
  try {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(ex);
    oos.flush();
    String info = new String(Base64.encodeBytesToBytes(baos.toByteArray()), MotanConstants.DEFAULT_CHARACTER);
    return Response.status(Status.EXPECTATION_FAILED).header(EXCEPTION_HEADER, ex.getClass()).entity(info)
        .build();
  } catch (IOException e) {
    LoggerUtil.error("serialize " + ex.getClass() + " error", e);
    return Response.status(Status.INTERNAL_SERVER_ERROR).entity("serialization " + ex.getClass() + " error")
        .build();
  }
}

代码示例来源:origin: resteasy/Resteasy

byte[] DECODABET = getDecodabet(options);
      outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options);
      b4Posn = 0;

代码示例来源:origin: resteasy/Resteasy

/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <code>null</code> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException   if encodedObject is null
* @throws java.io.IOException    if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
*                                class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject(String encodedObject)
   throws java.io.IOException, java.lang.ClassNotFoundException
{
 return decodeToObject(encodedObject, NO_OPTIONS, null);
}

代码示例来源:origin: resteasy/Resteasy

byte[] decoded = Base64.decodeFromFile(infile);
java.io.OutputStream out = null;
try

代码示例来源:origin: org.jboss.resteasy/resteasy-jaxrs-20

byte[] DECODABET = getDecodabet(options);
      outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options);
      b4Posn = 0;

代码示例来源:origin: org.jboss.resteasy/resteasy-core

/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <code>null</code> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException   if encodedObject is null
* @throws java.io.IOException    if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
*                                class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject(String encodedObject)
   throws java.io.IOException, java.lang.ClassNotFoundException
{
 return decodeToObject(encodedObject, NO_OPTIONS, null);
}

代码示例来源:origin: org.jboss.resteasy/resteasy-core

byte[] decoded = Base64.decodeFromFile(infile);
java.io.OutputStream out = null;
try

代码示例来源:origin: resteasy/Resteasy

public static String encode(byte[] bytes)
{
 String s = Base64.encodeBytes(bytes);
 s = s.split("=")[0]; // Remove any trailing '='s
 s = s.replace('+', '-'); // 62nd char of encoding
 s = s.replace('/', '_'); // 63rd char of encoding
 return s;
}

代码示例来源:origin: resteasy/Resteasy

/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @throws java.io.IOException If there is a problem
* @since 1.4
*/
public static byte[] decode(String s) throws java.io.IOException
{
 return decode(s, NO_OPTIONS);
}

代码示例来源:origin: resteasy/Resteasy

/**
* Similar to {@link #encodeBytes(byte[])} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
* @param source The data to convert
* @return The Base64-encoded data as a byte[] (of ASCII characters)
* @throws NullPointerException if source array is null
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes(byte[] source)
{
 byte[] encoded = null;
 try
 {
   encoded = encodeBytesToBytes(source, 0, source.length, Base64.NO_OPTIONS);
 }
 catch (java.io.IOException ex)
 {
   assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
 }
 return encoded;
}

代码示例来源:origin: org.jboss.resteasy/resteasy-core

byte[] DECODABET = getDecodabet(options);
      outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options);
      b4Posn = 0;

代码示例来源:origin: org.jboss.resteasy/resteasy-jaxrs-20

/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException   if encodedObject is null
* @throws java.io.IOException    if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
*                                class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject(String encodedObject)
    throws java.io.IOException, java.lang.ClassNotFoundException
{
 return decodeToObject(encodedObject, NO_OPTIONS, null);
}

代码示例来源:origin: org.jboss.resteasy/resteasy-jaxrs-20

byte[] decoded = Base64.decodeFromFile(infile);
java.io.OutputStream out = null;
try

代码示例来源:origin: resteasy/Resteasy

public static String createHeader(String username, String password)
{
 StringBuffer buf = new StringBuffer(username);
 buf.append(':').append(password);
 return "Basic " + Base64.encodeBytes(buf.toString().getBytes(StandardCharsets.UTF_8));
}

代码示例来源:origin: resteasy/Resteasy

/**
  * Low-level access to decoding ASCII characters in
  * the form of a byte array. <strong>Ignores GUNZIP option, if
  * it's set.</strong> This is not generally a recommended method,
  * although it is used internally as part of the decoding process.
  * Special case: if len = 0, an empty array is returned. Still,
  * if you need more speed and reduced memory footprint (and aren't
  * gzipping), consider this method.
  *
  * @param source The Base64 encoded data
  * @return decoded data
  * @throws IOException If bogus characters exist in source data
  * @since 2.3.1
  */
  public static byte[] decode(byte[] source)
     throws java.io.IOException
  {
   byte[] decoded = null;
//        try {
   decoded = decode(source, 0, source.length, Base64.NO_OPTIONS);
//        } catch( java.io.IOException ex ) {
//            assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
//        }
   return decoded;
  }

代码示例来源:origin: resteasy/Resteasy

byte[] encoded = encodeBytesToBytes(source, off, len, options);

代码示例来源:origin: resteasy/Resteasy

/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @return The data in Base64-encoded form
* @throws NullPointerException if source array is null
* @since 1.4
*/
public static String encodeBytes(byte[] source)
{
 // Since we're not going to have the GZIP encoding turned on,
 // we're not going to have an java.io.IOException thrown, so
 // we should not force the user to have to catch it.
 String encoded = null;
 try
 {
   encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
 }
 catch (java.io.IOException ex)
 {
   assert false : ex.getMessage();
 }   // end catch
 assert encoded != null;
 return encoded;
}   // end encodeBytes

代码示例来源:origin: resteasy/Resteasy

protected void extractAttributes()
{
 String heads = attributes.get(HEADERS);
 if (heads != null)
 {
   headers = Arrays.asList(heads.split(":"));
 }
 String sig = attributes.get(SIGNATURE);
 try
 {
   if (sig != null) signature = Base64.decode(sig);
 }
 catch (IOException e)
 {
   throw new RuntimeException(e);
 }
}

相关文章