代码抽取聚合
1、将foudations包下mogo-utils模块下的network部分,抽取到core包下的mogo-core-network模块 2、将foudations包下mogo-commons模块下的部分network类,抽取到core包下的mogo-core-network模块 3、将AbsMogoApplication类中网络配置代码,抽取到NetConfigUtils类中
This commit is contained in:
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
/**
|
||||
* Defines common decoding methods for byte array decoders.
|
||||
*
|
||||
* @version $Id: BinaryDecoder.java 1379145 2012-08-30 21:02:52Z tn $
|
||||
*/
|
||||
public interface BinaryDecoder extends Decoder {
|
||||
|
||||
/**
|
||||
* Decodes a byte array and returns the results as a byte array.
|
||||
*
|
||||
* @param source
|
||||
* A byte array which has been encoded with the appropriate encoder
|
||||
* @return a byte array that contains decoded content
|
||||
* @throws DecoderException
|
||||
* A decoder exception is thrown if a Decoder encounters a failure condition during the decode process.
|
||||
*/
|
||||
byte[] decode( byte[] source ) throws DecoderException;
|
||||
}
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
/**
|
||||
* Defines common encoding methods for byte array encoders.
|
||||
*
|
||||
* @version $Id: BinaryEncoder.java 1379145 2012-08-30 21:02:52Z tn $
|
||||
*/
|
||||
public interface BinaryEncoder extends Encoder {
|
||||
|
||||
/**
|
||||
* Encodes a byte array and return the encoded data as a byte array.
|
||||
*
|
||||
* @param source
|
||||
* Data to be encoded
|
||||
* @return A byte array containing the encoded data
|
||||
* @throws EncoderException
|
||||
* thrown if the Encoder encounters a failure condition during the encoding process.
|
||||
*/
|
||||
byte[] encode( byte[] source ) throws EncoderException;
|
||||
}
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
/**
|
||||
* Character encoding names required of every implementation of the Java platform.
|
||||
*
|
||||
* From the Java documentation <a
|
||||
* href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>:
|
||||
* <p>
|
||||
* <cite>Every implementation of the Java platform is required to support the following character encodings. Consult the
|
||||
* release documentation for your implementation to see if any other encodings are supported. Consult the release
|
||||
* documentation for your implementation to see if any other encodings are supported.</cite>
|
||||
* </p>
|
||||
*
|
||||
* <ul>
|
||||
* <li><code>US-ASCII</code><br>
|
||||
* Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set.</li>
|
||||
* <li><code>ISO-8859-1</code><br>
|
||||
* ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.</li>
|
||||
* <li><code>UTF-8</code><br>
|
||||
* Eight-bit Unicode Transformation Format.</li>
|
||||
* <li><code>UTF-16BE</code><br>
|
||||
* Sixteen-bit Unicode Transformation Format, big-endian byte order.</li>
|
||||
* <li><code>UTF-16LE</code><br>
|
||||
* Sixteen-bit Unicode Transformation Format, little-endian byte order.</li>
|
||||
* <li><code>UTF-16</code><br>
|
||||
* Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either order
|
||||
* accepted on input, big-endian used on output.)</li>
|
||||
* </ul>
|
||||
*
|
||||
* This perhaps would best belong in the [lang] project. Even if a similar interface is defined in [lang], it is not
|
||||
* foreseen that [codec] would be made to depend on [lang].
|
||||
*
|
||||
* <p>
|
||||
* This class is immutable and thread-safe.
|
||||
* </p>
|
||||
*
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @since 1.4
|
||||
* @version $Id: CharEncoding.java 1563226 2014-01-31 19:38:06Z ggregory $
|
||||
*/
|
||||
public class CharEncoding {
|
||||
/**
|
||||
* CharEncodingISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
*/
|
||||
public static final String ISO_8859_1 = "ISO-8859-1";
|
||||
|
||||
/**
|
||||
* Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set.
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
*/
|
||||
public static final String US_ASCII = "US-ASCII";
|
||||
|
||||
/**
|
||||
* Sixteen-bit Unicode Transformation Format, The byte order specified by a mandatory initial byte-order mark
|
||||
* (either order accepted on input, big-endian used on output)
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
*/
|
||||
public static final String UTF_16 = "UTF-16";
|
||||
|
||||
/**
|
||||
* Sixteen-bit Unicode Transformation Format, big-endian byte order.
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
*/
|
||||
public static final String UTF_16BE = "UTF-16BE";
|
||||
|
||||
/**
|
||||
* Sixteen-bit Unicode Transformation Format, little-endian byte order.
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
*/
|
||||
public static final String UTF_16LE = "UTF-16LE";
|
||||
|
||||
/**
|
||||
* Eight-bit Unicode Transformation Format.
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
*/
|
||||
public static final String UTF_8 = "UTF-8";
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Operations on {@link CharSequence} that are <code>null</code> safe.
|
||||
* </p>
|
||||
* <p>
|
||||
* Copied from Apache Commons Lang r1586295 on April 10, 2014 (day of 3.3.2 release).
|
||||
* </p>
|
||||
*
|
||||
* @see CharSequence
|
||||
* @since 1.10
|
||||
*/
|
||||
public class CharSequenceUtils {
|
||||
|
||||
/**
|
||||
* Green implementation of regionMatches.
|
||||
*
|
||||
* @param cs
|
||||
* the <code>CharSequence</code> to be processed
|
||||
* @param ignoreCase
|
||||
* whether or not to be case insensitive
|
||||
* @param thisStart
|
||||
* the index to start on the <code>cs</code> CharSequence
|
||||
* @param substring
|
||||
* the <code>CharSequence</code> to be looked for
|
||||
* @param start
|
||||
* the index to start on the <code>substring</code> CharSequence
|
||||
* @param length
|
||||
* character length of the region
|
||||
* @return whether the region matched
|
||||
*/
|
||||
static boolean regionMatches( final CharSequence cs, final boolean ignoreCase, final int thisStart,
|
||||
final CharSequence substring, final int start, final int length) {
|
||||
if (cs instanceof String && substring instanceof String ) {
|
||||
return (( String ) cs).regionMatches(ignoreCase, thisStart, ( String ) substring, start, length);
|
||||
}
|
||||
int index1 = thisStart;
|
||||
int index2 = start;
|
||||
int tmpLen = length;
|
||||
|
||||
while (tmpLen-- > 0) {
|
||||
char c1 = cs.charAt(index1++);
|
||||
char c2 = substring.charAt(index2++);
|
||||
|
||||
if (c1 == c2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!ignoreCase) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The same check as in String.regionMatches():
|
||||
if ( Character.toUpperCase(c1) != Character.toUpperCase(c2) &&
|
||||
Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/**
|
||||
* Charsets required of every implementation of the Java platform.
|
||||
*
|
||||
* From the Java documentation <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard
|
||||
* charsets</a>:
|
||||
* <p>
|
||||
* <cite>Every implementation of the Java platform is required to support the following character encodings. Consult the
|
||||
* release documentation for your implementation to see if any other encodings are supported. Consult the release
|
||||
* documentation for your implementation to see if any other encodings are supported. </cite>
|
||||
* </p>
|
||||
*
|
||||
* <ul>
|
||||
* <li><code>US-ASCII</code><br>
|
||||
* Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set.</li>
|
||||
* <li><code>ISO-8859-1</code><br>
|
||||
* ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.</li>
|
||||
* <li><code>UTF-8</code><br>
|
||||
* Eight-bit Unicode Transformation Format.</li>
|
||||
* <li><code>UTF-16BE</code><br>
|
||||
* Sixteen-bit Unicode Transformation Format, big-endian byte order.</li>
|
||||
* <li><code>UTF-16LE</code><br>
|
||||
* Sixteen-bit Unicode Transformation Format, little-endian byte order.</li>
|
||||
* <li><code>UTF-16</code><br>
|
||||
* Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either order
|
||||
* accepted on input, big-endian used on output.)</li>
|
||||
* </ul>
|
||||
*
|
||||
* This perhaps would best belong in the Commons Lang project. Even if a similar class is defined in Commons Lang, it is
|
||||
* not foreseen that Commons Codec would be made to depend on Commons Lang.
|
||||
*
|
||||
* <p>
|
||||
* This class is immutable and thread-safe.
|
||||
* </p>
|
||||
*
|
||||
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @since 1.7
|
||||
* @version $Id: CharEncoding.java 1173287 2011-09-20 18:16:19Z ggregory $
|
||||
*/
|
||||
public class Charsets {
|
||||
|
||||
//
|
||||
// This class should only contain Charset instances for required encodings. This guarantees that it will load
|
||||
// correctly and without delay on all Java platforms.
|
||||
//
|
||||
|
||||
/**
|
||||
* Returns the given Charset or the default Charset if the given Charset is null.
|
||||
*
|
||||
* @param charset
|
||||
* A charset or null.
|
||||
* @return the given Charset or the default Charset if the given Charset is null
|
||||
*/
|
||||
public static Charset toCharset( final Charset charset) {
|
||||
return charset == null ? Charset.defaultCharset() : charset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a Charset for the named charset. If the name is null, return the default Charset.
|
||||
*
|
||||
* @param charset
|
||||
* The name of the requested charset, may be null.
|
||||
* @return a Charset for the named charset
|
||||
* @throws java.nio.charset.UnsupportedCharsetException
|
||||
* If the named charset is unavailable
|
||||
*/
|
||||
public static Charset toCharset( final String charset) {
|
||||
return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
|
||||
}
|
||||
|
||||
/**
|
||||
* CharEncodingISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
|
||||
*/
|
||||
@Deprecated
|
||||
public static final Charset ISO_8859_1 = Charset.forName(CharEncoding.ISO_8859_1);
|
||||
|
||||
/**
|
||||
* Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set.
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
|
||||
*/
|
||||
@Deprecated
|
||||
public static final Charset US_ASCII = Charset.forName(CharEncoding.US_ASCII);
|
||||
|
||||
/**
|
||||
* Sixteen-bit Unicode Transformation Format, The byte order specified by a mandatory initial byte-order mark
|
||||
* (either order accepted on input, big-endian used on output)
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
|
||||
*/
|
||||
@Deprecated
|
||||
public static final Charset UTF_16 = Charset.forName(CharEncoding.UTF_16);
|
||||
|
||||
/**
|
||||
* Sixteen-bit Unicode Transformation Format, big-endian byte order.
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
|
||||
*/
|
||||
@Deprecated
|
||||
public static final Charset UTF_16BE = Charset.forName(CharEncoding.UTF_16BE);
|
||||
|
||||
/**
|
||||
* Sixteen-bit Unicode Transformation Format, little-endian byte order.
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
|
||||
*/
|
||||
@Deprecated
|
||||
public static final Charset UTF_16LE = Charset.forName(CharEncoding.UTF_16LE);
|
||||
|
||||
/**
|
||||
* Eight-bit Unicode Transformation Format.
|
||||
* <p>
|
||||
* Every implementation of the Java platform is required to support this character encoding.
|
||||
*
|
||||
* @see <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
|
||||
*/
|
||||
@Deprecated
|
||||
public static final Charset UTF_8 = Charset.forName(CharEncoding.UTF_8);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
/**
|
||||
* Provides the highest level of abstraction for Decoders.
|
||||
* <p>
|
||||
* This is the sister interface of {@link Encoder}. All Decoders implement this common generic interface.
|
||||
* Allows a user to pass a generic Object to any Decoder implementation in the codec package.
|
||||
* <p>
|
||||
* One of the two interfaces at the center of the codec package.
|
||||
*
|
||||
* @version $Id: Decoder.java 1379145 2012-08-30 21:02:52Z tn $
|
||||
*/
|
||||
public interface Decoder {
|
||||
|
||||
/**
|
||||
* Decodes an "encoded" Object and returns a "decoded" Object. Note that the implementation of this interface will
|
||||
* try to cast the Object parameter to the specific type expected by a particular Decoder implementation. If a
|
||||
* {@link ClassCastException} occurs this decode method will throw a DecoderException.
|
||||
*
|
||||
* @param source
|
||||
* the object to decode
|
||||
* @return a 'decoded" object
|
||||
* @throws DecoderException
|
||||
* a decoder exception can be thrown for any number of reasons. Some good candidates are that the
|
||||
* parameter passed to this method is null, a param cannot be cast to the appropriate type for a
|
||||
* specific encoder.
|
||||
*/
|
||||
Object decode( Object source ) throws DecoderException;
|
||||
}
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
/**
|
||||
* Thrown when there is a failure condition during the decoding process. This exception is thrown when a {@link Decoder}
|
||||
* encounters a decoding specific exception such as invalid data, or characters outside of the expected range.
|
||||
*
|
||||
* @version $Id: DecoderException.java 1619948 2014-08-22 22:53:55Z ggregory $
|
||||
*/
|
||||
public class DecoderException extends Exception {
|
||||
|
||||
/**
|
||||
* Declares the Serial Version Uid.
|
||||
*
|
||||
* @see <a href="http://c2.com/cgi/wiki?AlwaysDeclareSerialVersionUid">Always Declare Serial Version Uid</a>
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Constructs a new exception with <code>null</code> as its detail message. The cause is not initialized, and may
|
||||
* subsequently be initialized by a call to {@link #initCause}.
|
||||
*
|
||||
* @since 1.4
|
||||
*/
|
||||
public DecoderException() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently
|
||||
* be initialized by a call to {@link #initCause}.
|
||||
*
|
||||
* @param message
|
||||
* The detail message which is saved for later retrieval by the {@link #getMessage()} method.
|
||||
*/
|
||||
public DecoderException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the specified detail message and cause.
|
||||
* <p>
|
||||
* Note that the detail message associated with <code>cause</code> is not automatically incorporated into this
|
||||
* exception's detail message.
|
||||
*
|
||||
* @param message
|
||||
* The detail message which is saved for later retrieval by the {@link #getMessage()} method.
|
||||
* @param cause
|
||||
* The cause which is saved for later retrieval by the {@link #getCause()} method. A <code>null</code>
|
||||
* value is permitted, and indicates that the cause is nonexistent or unknown.
|
||||
* @since 1.4
|
||||
*/
|
||||
public DecoderException( final String message, final Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the specified cause and a detail message of <code>(cause==null ?
|
||||
* null : cause.toString())</code> (which typically contains the class and detail message of <code>cause</code>).
|
||||
* This constructor is useful for exceptions that are little more than wrappers for other throwables.
|
||||
*
|
||||
* @param cause
|
||||
* The cause which is saved for later retrieval by the {@link #getCause()} method. A <code>null</code>
|
||||
* value is permitted, and indicates that the cause is nonexistent or unknown.
|
||||
* @since 1.4
|
||||
*/
|
||||
public DecoderException(final Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
@@ -1,817 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
/**
|
||||
* Operations to simplify common {@link MessageDigest} tasks.
|
||||
* This class is immutable and thread-safe.
|
||||
*
|
||||
* @version $Id: DigestUtils.java 1634433 2014-10-27 01:10:47Z ggregory $
|
||||
*/
|
||||
public class DigestUtils {
|
||||
|
||||
private static final int STREAM_BUFFER_LENGTH = 1024;
|
||||
|
||||
/**
|
||||
* Read through an InputStream and returns the digest for the data
|
||||
*
|
||||
* @param digest
|
||||
* The MessageDigest to use (e.g. MD5)
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return the digest
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
*/
|
||||
private static byte[] digest( final MessageDigest digest, final InputStream data) throws IOException {
|
||||
return updateDigest(digest, data).digest();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a <code>MessageDigest</code> for the given <code>algorithm</code>.
|
||||
*
|
||||
* @param algorithm
|
||||
* the name of the algorithm requested. See <a
|
||||
* href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#AppA"
|
||||
* >Appendix A in the Java Cryptography Architecture Reference Guide</a> for information about standard
|
||||
* algorithm names.
|
||||
* @return A digest instance.
|
||||
* @see MessageDigest#getInstance(String)
|
||||
* @throws IllegalArgumentException
|
||||
* when a {@link NoSuchAlgorithmException} is caught.
|
||||
*/
|
||||
public static MessageDigest getDigest( final String algorithm) {
|
||||
try {
|
||||
return MessageDigest.getInstance(algorithm);
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an MD2 MessageDigest.
|
||||
*
|
||||
* @return An MD2 digest instance.
|
||||
* @throws IllegalArgumentException
|
||||
* when a {@link NoSuchAlgorithmException} is caught, which should never happen because MD2 is a
|
||||
* built-in algorithm
|
||||
* @see MessageDigestAlgorithms#MD2
|
||||
* @since 1.7
|
||||
*/
|
||||
public static MessageDigest getMd2Digest() {
|
||||
return getDigest(MessageDigestAlgorithms.MD2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an MD5 MessageDigest.
|
||||
*
|
||||
* @return An MD5 digest instance.
|
||||
* @throws IllegalArgumentException
|
||||
* when a {@link NoSuchAlgorithmException} is caught, which should never happen because MD5 is a
|
||||
* built-in algorithm
|
||||
* @see MessageDigestAlgorithms#MD5
|
||||
*/
|
||||
public static MessageDigest getMd5Digest() {
|
||||
return getDigest(MessageDigestAlgorithms.MD5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an SHA-1 digest.
|
||||
*
|
||||
* @return An SHA-1 digest instance.
|
||||
* @throws IllegalArgumentException
|
||||
* when a {@link NoSuchAlgorithmException} is caught, which should never happen because SHA-1 is a
|
||||
* built-in algorithm
|
||||
* @see MessageDigestAlgorithms#SHA_1
|
||||
* @since 1.7
|
||||
*/
|
||||
public static MessageDigest getSha1Digest() {
|
||||
return getDigest(MessageDigestAlgorithms.SHA_1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an SHA-256 digest.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @return An SHA-256 digest instance.
|
||||
* @throws IllegalArgumentException
|
||||
* when a {@link NoSuchAlgorithmException} is caught, which should never happen because SHA-256 is a
|
||||
* built-in algorithm
|
||||
* @see MessageDigestAlgorithms#SHA_256
|
||||
*/
|
||||
public static MessageDigest getSha256Digest() {
|
||||
return getDigest(MessageDigestAlgorithms.SHA_256);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an SHA-384 digest.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @return An SHA-384 digest instance.
|
||||
* @throws IllegalArgumentException
|
||||
* when a {@link NoSuchAlgorithmException} is caught, which should never happen because SHA-384 is a
|
||||
* built-in algorithm
|
||||
* @see MessageDigestAlgorithms#SHA_384
|
||||
*/
|
||||
public static MessageDigest getSha384Digest() {
|
||||
return getDigest(MessageDigestAlgorithms.SHA_384);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an SHA-512 digest.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @return An SHA-512 digest instance.
|
||||
* @throws IllegalArgumentException
|
||||
* when a {@link NoSuchAlgorithmException} is caught, which should never happen because SHA-512 is a
|
||||
* built-in algorithm
|
||||
* @see MessageDigestAlgorithms#SHA_512
|
||||
*/
|
||||
public static MessageDigest getSha512Digest() {
|
||||
return getDigest(MessageDigestAlgorithms.SHA_512);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an SHA-1 digest.
|
||||
*
|
||||
* @return An SHA-1 digest instance.
|
||||
* @throws IllegalArgumentException
|
||||
* when a {@link NoSuchAlgorithmException} is caught
|
||||
* @deprecated Use {@link #getSha1Digest()}
|
||||
*/
|
||||
@Deprecated
|
||||
public static MessageDigest getShaDigest() {
|
||||
return getSha1Digest();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD2 digest and returns the value as a 16 element <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return MD2 digest
|
||||
* @since 1.7
|
||||
*/
|
||||
public static byte[] md2(final byte[] data) {
|
||||
return getMd2Digest().digest(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD2 digest and returns the value as a 16 element <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return MD2 digest
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.7
|
||||
*/
|
||||
public static byte[] md2(final InputStream data) throws IOException {
|
||||
return digest(getMd2Digest(), data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD2 digest and returns the value as a 16 element <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest; converted to bytes using {@link StringUtils#getBytesUtf8(String)}
|
||||
* @return MD2 digest
|
||||
* @since 1.7
|
||||
*/
|
||||
public static byte[] md2(final String data) {
|
||||
return md2(StringUtils.getBytesUtf8(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD2 digest and returns the value as a 32 character hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return MD2 digest as a hex string
|
||||
* @since 1.7
|
||||
*/
|
||||
public static String md2Hex( final byte[] data) {
|
||||
return Hex.encodeHexString(md2(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD2 digest and returns the value as a 32 character hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return MD2 digest as a hex string
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.7
|
||||
*/
|
||||
public static String md2Hex( final InputStream data) throws IOException {
|
||||
return Hex.encodeHexString(md2(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD2 digest and returns the value as a 32 character hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return MD2 digest as a hex string
|
||||
* @since 1.7
|
||||
*/
|
||||
public static String md2Hex( final String data) {
|
||||
return Hex.encodeHexString(md2(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD5 digest and returns the value as a 16 element <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return MD5 digest
|
||||
*/
|
||||
public static byte[] md5(final byte[] data) {
|
||||
return getMd5Digest().digest(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD5 digest and returns the value as a 16 element <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return MD5 digest
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.4
|
||||
*/
|
||||
public static byte[] md5(final InputStream data) throws IOException {
|
||||
return digest(getMd5Digest(), data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD5 digest and returns the value as a 16 element <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest; converted to bytes using {@link StringUtils#getBytesUtf8(String)}
|
||||
* @return MD5 digest
|
||||
*/
|
||||
public static byte[] md5(final String data) {
|
||||
return md5(StringUtils.getBytesUtf8(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD5 digest and returns the value as a 32 character hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return MD5 digest as a hex string
|
||||
*/
|
||||
public static String md5Hex( final byte[] data) {
|
||||
return Hex.encodeHexString(md5(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD5 digest and returns the value as a 32 character hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return MD5 digest as a hex string
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String md5Hex( final InputStream data) throws IOException {
|
||||
return Hex.encodeHexString(md5(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the MD5 digest and returns the value as a 32 character hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return MD5 digest as a hex string
|
||||
*/
|
||||
public static String md5Hex( final String data) {
|
||||
return Hex.encodeHexString(md5(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest
|
||||
* @deprecated Use {@link #sha1(byte[])}
|
||||
*/
|
||||
@Deprecated
|
||||
public static byte[] sha(final byte[] data) {
|
||||
return sha1(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.4
|
||||
* @deprecated Use {@link #sha1(InputStream)}
|
||||
*/
|
||||
@Deprecated
|
||||
public static byte[] sha(final InputStream data) throws IOException {
|
||||
return sha1(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest
|
||||
* @deprecated Use {@link #sha1(String)}
|
||||
*/
|
||||
@Deprecated
|
||||
public static byte[] sha(final String data) {
|
||||
return sha1(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest
|
||||
* @since 1.7
|
||||
*/
|
||||
public static byte[] sha1(final byte[] data) {
|
||||
return getSha1Digest().digest(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.7
|
||||
*/
|
||||
public static byte[] sha1(final InputStream data) throws IOException {
|
||||
return digest(getSha1Digest(), data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a <code>byte[]</code>.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest; converted to bytes using {@link StringUtils#getBytesUtf8(String)}
|
||||
* @return SHA-1 digest
|
||||
*/
|
||||
public static byte[] sha1(final String data) {
|
||||
return sha1(StringUtils.getBytesUtf8(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest as a hex string
|
||||
* @since 1.7
|
||||
*/
|
||||
public static String sha1Hex( final byte[] data) {
|
||||
return Hex.encodeHexString(sha1(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest as a hex string
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.7
|
||||
*/
|
||||
public static String sha1Hex( final InputStream data) throws IOException {
|
||||
return Hex.encodeHexString(sha1(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest as a hex string
|
||||
* @since 1.7
|
||||
*/
|
||||
public static String sha1Hex( final String data) {
|
||||
return Hex.encodeHexString(sha1(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 digest and returns the value as a <code>byte[]</code>.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-256 digest
|
||||
* @since 1.4
|
||||
*/
|
||||
public static byte[] sha256(final byte[] data) {
|
||||
return getSha256Digest().digest(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 digest and returns the value as a <code>byte[]</code>.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-256 digest
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.4
|
||||
*/
|
||||
public static byte[] sha256(final InputStream data) throws IOException {
|
||||
return digest(getSha256Digest(), data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 digest and returns the value as a <code>byte[]</code>.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest; converted to bytes using {@link StringUtils#getBytesUtf8(String)}
|
||||
* @return SHA-256 digest
|
||||
* @since 1.4
|
||||
*/
|
||||
public static byte[] sha256(final String data) {
|
||||
return sha256(StringUtils.getBytesUtf8(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 digest and returns the value as a hex string.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-256 digest as a hex string
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String sha256Hex( final byte[] data) {
|
||||
return Hex.encodeHexString(sha256(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 digest and returns the value as a hex string.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-256 digest as a hex string
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String sha256Hex( final InputStream data) throws IOException {
|
||||
return Hex.encodeHexString(sha256(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-256 digest and returns the value as a hex string.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-256 digest as a hex string
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String sha256Hex( final String data) {
|
||||
return Hex.encodeHexString(sha256(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-384 digest and returns the value as a <code>byte[]</code>.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-384 digest
|
||||
* @since 1.4
|
||||
*/
|
||||
public static byte[] sha384(final byte[] data) {
|
||||
return getSha384Digest().digest(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-384 digest and returns the value as a <code>byte[]</code>.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-384 digest
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.4
|
||||
*/
|
||||
public static byte[] sha384(final InputStream data) throws IOException {
|
||||
return digest(getSha384Digest(), data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-384 digest and returns the value as a <code>byte[]</code>.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest; converted to bytes using {@link StringUtils#getBytesUtf8(String)}
|
||||
* @return SHA-384 digest
|
||||
* @since 1.4
|
||||
*/
|
||||
public static byte[] sha384(final String data) {
|
||||
return sha384(StringUtils.getBytesUtf8(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-384 digest and returns the value as a hex string.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-384 digest as a hex string
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String sha384Hex( final byte[] data) {
|
||||
return Hex.encodeHexString(sha384(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-384 digest and returns the value as a hex string.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-384 digest as a hex string
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String sha384Hex( final InputStream data) throws IOException {
|
||||
return Hex.encodeHexString(sha384(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-384 digest and returns the value as a hex string.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-384 digest as a hex string
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String sha384Hex( final String data) {
|
||||
return Hex.encodeHexString(sha384(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-512 digest and returns the value as a <code>byte[]</code>.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-512 digest
|
||||
* @since 1.4
|
||||
*/
|
||||
public static byte[] sha512(final byte[] data) {
|
||||
return getSha512Digest().digest(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-512 digest and returns the value as a <code>byte[]</code>.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-512 digest
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.4
|
||||
*/
|
||||
public static byte[] sha512(final InputStream data) throws IOException {
|
||||
return digest(getSha512Digest(), data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-512 digest and returns the value as a <code>byte[]</code>.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest; converted to bytes using {@link StringUtils#getBytesUtf8(String)}
|
||||
* @return SHA-512 digest
|
||||
* @since 1.4
|
||||
*/
|
||||
public static byte[] sha512(final String data) {
|
||||
return sha512(StringUtils.getBytesUtf8(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-512 digest and returns the value as a hex string.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-512 digest as a hex string
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String sha512Hex( final byte[] data) {
|
||||
return Hex.encodeHexString(sha512(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-512 digest and returns the value as a hex string.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-512 digest as a hex string
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String sha512Hex( final InputStream data) throws IOException {
|
||||
return Hex.encodeHexString(sha512(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-512 digest and returns the value as a hex string.
|
||||
* <p>
|
||||
* Throws a <code>RuntimeException</code> on JRE versions prior to 1.4.0.
|
||||
* </p>
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-512 digest as a hex string
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String sha512Hex( final String data) {
|
||||
return Hex.encodeHexString(sha512(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest as a hex string
|
||||
* @deprecated Use {@link #sha1Hex(byte[])}
|
||||
*/
|
||||
@Deprecated
|
||||
public static String shaHex( final byte[] data) {
|
||||
return sha1Hex(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest as a hex string
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.4
|
||||
* @deprecated Use {@link #sha1Hex(InputStream)}
|
||||
*/
|
||||
@Deprecated
|
||||
public static String shaHex( final InputStream data) throws IOException {
|
||||
return sha1Hex(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the SHA-1 digest and returns the value as a hex string.
|
||||
*
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return SHA-1 digest as a hex string
|
||||
* @deprecated Use {@link #sha1Hex(String)}
|
||||
*/
|
||||
@Deprecated
|
||||
public static String shaHex( final String data) {
|
||||
return sha1Hex(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the given {@link MessageDigest}.
|
||||
*
|
||||
* @param messageDigest
|
||||
* the {@link MessageDigest} to update
|
||||
* @param valueToDigest
|
||||
* the value to update the {@link MessageDigest} with
|
||||
* @return the updated {@link MessageDigest}
|
||||
* @since 1.7
|
||||
*/
|
||||
public static MessageDigest updateDigest( final MessageDigest messageDigest, final byte[] valueToDigest) {
|
||||
messageDigest.update(valueToDigest);
|
||||
return messageDigest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads through an InputStream and updates the digest for the data
|
||||
*
|
||||
* @param digest
|
||||
* The MessageDigest to use (e.g. MD5)
|
||||
* @param data
|
||||
* Data to digest
|
||||
* @return the digest
|
||||
* @throws IOException
|
||||
* On error reading from the stream
|
||||
* @since 1.8
|
||||
*/
|
||||
public static MessageDigest updateDigest( final MessageDigest digest, final InputStream data) throws IOException {
|
||||
final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
|
||||
int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
|
||||
|
||||
while (read > -1) {
|
||||
digest.update(buffer, 0, read);
|
||||
read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
|
||||
}
|
||||
|
||||
return digest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the given {@link MessageDigest}.
|
||||
*
|
||||
* @param messageDigest
|
||||
* the {@link MessageDigest} to update
|
||||
* @param valueToDigest
|
||||
* the value to update the {@link MessageDigest} with;
|
||||
* converted to bytes using {@link StringUtils#getBytesUtf8(String)}
|
||||
* @return the updated {@link MessageDigest}
|
||||
* @since 1.7
|
||||
*/
|
||||
public static MessageDigest updateDigest( final MessageDigest messageDigest, final String valueToDigest) {
|
||||
messageDigest.update(StringUtils.getBytesUtf8(valueToDigest));
|
||||
return messageDigest;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
/**
|
||||
* Provides the highest level of abstraction for Encoders.
|
||||
* <p>
|
||||
* This is the sister interface of {@link Decoder}. Every implementation of Encoder provides this
|
||||
* common generic interface which allows a user to pass a generic Object to any Encoder implementation
|
||||
* in the codec package.
|
||||
*
|
||||
* @version $Id: Encoder.java 1379145 2012-08-30 21:02:52Z tn $
|
||||
*/
|
||||
public interface Encoder {
|
||||
|
||||
/**
|
||||
* Encodes an "Object" and returns the encoded content as an Object. The Objects here may just be
|
||||
* <code>byte[]</code> or <code>String</code>s depending on the implementation used.
|
||||
*
|
||||
* @param source
|
||||
* An object to encode
|
||||
* @return An "encoded" Object
|
||||
* @throws EncoderException
|
||||
* An encoder exception is thrown if the encoder experiences a failure condition during the encoding
|
||||
* process.
|
||||
*/
|
||||
Object encode( Object source ) throws EncoderException;
|
||||
}
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
/**
|
||||
* Thrown when there is a failure condition during the encoding process. This exception is thrown when an
|
||||
* {@link Encoder} encounters a encoding specific exception such as invalid data, inability to calculate a checksum,
|
||||
* characters outside of the expected range.
|
||||
*
|
||||
* @version $Id: EncoderException.java 1619948 2014-08-22 22:53:55Z ggregory $
|
||||
*/
|
||||
public class EncoderException extends Exception {
|
||||
|
||||
/**
|
||||
* Declares the Serial Version Uid.
|
||||
*
|
||||
* @see <a href="http://c2.com/cgi/wiki?AlwaysDeclareSerialVersionUid">Always Declare Serial Version Uid</a>
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Constructs a new exception with <code>null</code> as its detail message. The cause is not initialized, and may
|
||||
* subsequently be initialized by a call to {@link #initCause}.
|
||||
*
|
||||
* @since 1.4
|
||||
*/
|
||||
public EncoderException() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently
|
||||
* be initialized by a call to {@link #initCause}.
|
||||
*
|
||||
* @param message
|
||||
* a useful message relating to the encoder specific error.
|
||||
*/
|
||||
public EncoderException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the specified detail message and cause.
|
||||
*
|
||||
* <p>
|
||||
* Note that the detail message associated with <code>cause</code> is not automatically incorporated into this
|
||||
* exception's detail message.
|
||||
* </p>
|
||||
*
|
||||
* @param message
|
||||
* The detail message which is saved for later retrieval by the {@link #getMessage()} method.
|
||||
* @param cause
|
||||
* The cause which is saved for later retrieval by the {@link #getCause()} method. A <code>null</code>
|
||||
* value is permitted, and indicates that the cause is nonexistent or unknown.
|
||||
* @since 1.4
|
||||
*/
|
||||
public EncoderException( final String message, final Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the specified cause and a detail message of <code>(cause==null ?
|
||||
* null : cause.toString())</code> (which typically contains the class and detail message of <code>cause</code>).
|
||||
* This constructor is useful for exceptions that are little more than wrappers for other throwables.
|
||||
*
|
||||
* @param cause
|
||||
* The cause which is saved for later retrieval by the {@link #getCause()} method. A <code>null</code>
|
||||
* value is permitted, and indicates that the cause is nonexistent or unknown.
|
||||
* @since 1.4
|
||||
*/
|
||||
public EncoderException(final Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
@@ -1,328 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/**
|
||||
* Converts hexadecimal Strings. The charset used for certain operation can be set, the default is set in
|
||||
* {@link #DEFAULT_CHARSET_NAME}
|
||||
*
|
||||
* This class is thread-safe.
|
||||
*
|
||||
* @since 1.1
|
||||
* @version $Id: Hex.java 1619948 2014-08-22 22:53:55Z ggregory $
|
||||
*/
|
||||
public class Hex implements BinaryEncoder, BinaryDecoder {
|
||||
|
||||
/**
|
||||
* Default charset name is {@link Charsets#UTF_8}
|
||||
*
|
||||
* @since 1.7
|
||||
*/
|
||||
public static final Charset DEFAULT_CHARSET = Charsets.UTF_8;
|
||||
|
||||
/**
|
||||
* Default charset name is {@link CharEncoding#UTF_8}
|
||||
*
|
||||
* @since 1.4
|
||||
*/
|
||||
public static final String DEFAULT_CHARSET_NAME = CharEncoding.UTF_8;
|
||||
|
||||
/**
|
||||
* Used to build output as Hex
|
||||
*/
|
||||
private static final char[] DIGITS_LOWER =
|
||||
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
|
||||
|
||||
/**
|
||||
* Used to build output as Hex
|
||||
*/
|
||||
private static final char[] DIGITS_UPPER =
|
||||
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
|
||||
|
||||
/**
|
||||
* Converts an array of characters representing hexadecimal values into an array of bytes of those same values. The
|
||||
* returned array will be half the length of the passed array, as it takes two characters to represent any given
|
||||
* byte. An exception is thrown if the passed char array has an odd number of elements.
|
||||
*
|
||||
* @param data
|
||||
* An array of characters containing hexadecimal digits
|
||||
* @return A byte array containing binary data decoded from the supplied char array.
|
||||
* @throws DecoderException
|
||||
* Thrown if an odd number or illegal of characters is supplied
|
||||
*/
|
||||
public static byte[] decodeHex(final char[] data) throws DecoderException {
|
||||
|
||||
final int len = data.length;
|
||||
|
||||
if ((len & 0x01) != 0) {
|
||||
throw new DecoderException("Odd number of characters.");
|
||||
}
|
||||
|
||||
final byte[] out = new byte[len >> 1];
|
||||
|
||||
// two characters form the hex value.
|
||||
for (int i = 0, j = 0; j < len; i++) {
|
||||
int f = toDigit(data[j], j) << 4;
|
||||
j++;
|
||||
f = f | toDigit(data[j], j);
|
||||
j++;
|
||||
out[i] = (byte) (f & 0xFF);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
|
||||
* The returned array will be double the length of the passed array, as it takes two characters to represent any
|
||||
* given byte.
|
||||
*
|
||||
* @param data
|
||||
* a byte[] to convert to Hex characters
|
||||
* @return A char[] containing hexadecimal characters
|
||||
*/
|
||||
public static char[] encodeHex(final byte[] data) {
|
||||
return encodeHex(data, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
|
||||
* The returned array will be double the length of the passed array, as it takes two characters to represent any
|
||||
* given byte.
|
||||
*
|
||||
* @param data
|
||||
* a byte[] to convert to Hex characters
|
||||
* @param toLowerCase
|
||||
* <code>true</code> converts to lowercase, <code>false</code> to uppercase
|
||||
* @return A char[] containing hexadecimal characters
|
||||
* @since 1.4
|
||||
*/
|
||||
public static char[] encodeHex(final byte[] data, final boolean toLowerCase) {
|
||||
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
|
||||
* The returned array will be double the length of the passed array, as it takes two characters to represent any
|
||||
* given byte.
|
||||
*
|
||||
* @param data
|
||||
* a byte[] to convert to Hex characters
|
||||
* @param toDigits
|
||||
* the output alphabet
|
||||
* @return A char[] containing hexadecimal characters
|
||||
* @since 1.4
|
||||
*/
|
||||
protected static char[] encodeHex(final byte[] data, final char[] toDigits) {
|
||||
final int l = data.length;
|
||||
final char[] out = new char[l << 1];
|
||||
// two characters form the hex value.
|
||||
for (int i = 0, j = 0; i < l; i++) {
|
||||
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
|
||||
out[j++] = toDigits[0x0F & data[i]];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an array of bytes into a String representing the hexadecimal values of each byte in order. The returned
|
||||
* String will be double the length of the passed array, as it takes two characters to represent any given byte.
|
||||
*
|
||||
* @param data
|
||||
* a byte[] to convert to Hex characters
|
||||
* @return A String containing hexadecimal characters
|
||||
* @since 1.4
|
||||
*/
|
||||
public static String encodeHexString( final byte[] data) {
|
||||
return new String(encodeHex(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a hexadecimal character to an integer.
|
||||
*
|
||||
* @param ch
|
||||
* A character to convert to an integer digit
|
||||
* @param index
|
||||
* The index of the character in the source
|
||||
* @return An integer
|
||||
* @throws DecoderException
|
||||
* Thrown if ch is an illegal hex character
|
||||
*/
|
||||
protected static int toDigit(final char ch, final int index) throws DecoderException {
|
||||
final int digit = Character.digit(ch, 16);
|
||||
if (digit == -1) {
|
||||
throw new DecoderException("Illegal hexadecimal character " + ch + " at index " + index);
|
||||
}
|
||||
return digit;
|
||||
}
|
||||
|
||||
private final Charset charset;
|
||||
|
||||
/**
|
||||
* Creates a new codec with the default charset name {@link #DEFAULT_CHARSET}
|
||||
*/
|
||||
public Hex() {
|
||||
// use default encoding
|
||||
this.charset = DEFAULT_CHARSET;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new codec with the given Charset.
|
||||
*
|
||||
* @param charset
|
||||
* the charset.
|
||||
* @since 1.7
|
||||
*/
|
||||
public Hex(final Charset charset) {
|
||||
this.charset = charset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new codec with the given charset name.
|
||||
*
|
||||
* @param charsetName
|
||||
* the charset name.
|
||||
* @throws java.nio.charset.UnsupportedCharsetException
|
||||
* If the named charset is unavailable
|
||||
* @since 1.4
|
||||
* @since 1.7 throws UnsupportedCharsetException if the named charset is unavailable
|
||||
*/
|
||||
public Hex(final String charsetName) {
|
||||
this( Charset.forName(charsetName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an array of character bytes representing hexadecimal values into an array of bytes of those same values.
|
||||
* The returned array will be half the length of the passed array, as it takes two characters to represent any given
|
||||
* byte. An exception is thrown if the passed char array has an odd number of elements.
|
||||
*
|
||||
* @param array
|
||||
* An array of character bytes containing hexadecimal digits
|
||||
* @return A byte array containing binary data decoded from the supplied byte array (representing characters).
|
||||
* @throws DecoderException
|
||||
* Thrown if an odd number of characters is supplied to this function
|
||||
* @see #decodeHex(char[])
|
||||
*/
|
||||
@Override
|
||||
public byte[] decode(final byte[] array) throws DecoderException {
|
||||
return decodeHex(new String(array, getCharset()).toCharArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a String or an array of character bytes representing hexadecimal values into an array of bytes of those
|
||||
* same values. The returned array will be half the length of the passed String or array, as it takes two characters
|
||||
* to represent any given byte. An exception is thrown if the passed char array has an odd number of elements.
|
||||
*
|
||||
* @param object
|
||||
* A String or, an array of character bytes containing hexadecimal digits
|
||||
* @return A byte array containing binary data decoded from the supplied byte array (representing characters).
|
||||
* @throws DecoderException
|
||||
* Thrown if an odd number of characters is supplied to this function or the object is not a String or
|
||||
* char[]
|
||||
* @see #decodeHex(char[])
|
||||
*/
|
||||
@Override
|
||||
public Object decode( final Object object) throws DecoderException {
|
||||
try {
|
||||
final char[] charArray = object instanceof String ? (( String ) object).toCharArray() : (char[]) object;
|
||||
return decodeHex(charArray);
|
||||
} catch (final ClassCastException e) {
|
||||
throw new DecoderException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an array of bytes into an array of bytes for the characters representing the hexadecimal values of each
|
||||
* byte in order. The returned array will be double the length of the passed array, as it takes two characters to
|
||||
* represent any given byte.
|
||||
* <p>
|
||||
* The conversion from hexadecimal characters to the returned bytes is performed with the charset named by
|
||||
* {@link #getCharset()}.
|
||||
* </p>
|
||||
*
|
||||
* @param array
|
||||
* a byte[] to convert to Hex characters
|
||||
* @return A byte[] containing the bytes of the hexadecimal characters
|
||||
* @since 1.7 No longer throws IllegalStateException if the charsetName is invalid.
|
||||
* @see #encodeHex(byte[])
|
||||
*/
|
||||
@Override
|
||||
public byte[] encode(final byte[] array) {
|
||||
return encodeHexString(array).getBytes(this.getCharset());
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a String or an array of bytes into an array of characters representing the hexadecimal values of each
|
||||
* byte in order. The returned array will be double the length of the passed String or array, as it takes two
|
||||
* characters to represent any given byte.
|
||||
* <p>
|
||||
* The conversion from hexadecimal characters to bytes to be encoded to performed with the charset named by
|
||||
* {@link #getCharset()}.
|
||||
* </p>
|
||||
*
|
||||
* @param object
|
||||
* a String, or byte[] to convert to Hex characters
|
||||
* @return A char[] containing hexadecimal characters
|
||||
* @throws EncoderException
|
||||
* Thrown if the given object is not a String or byte[]
|
||||
* @see #encodeHex(byte[])
|
||||
*/
|
||||
@Override
|
||||
public Object encode( final Object object) throws EncoderException {
|
||||
try {
|
||||
final byte[] byteArray = object instanceof String ?
|
||||
(( String ) object).getBytes(this.getCharset()) : (byte[]) object;
|
||||
return encodeHex(byteArray);
|
||||
} catch (final ClassCastException e) {
|
||||
throw new EncoderException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the charset.
|
||||
*
|
||||
* @return the charset.
|
||||
* @since 1.7
|
||||
*/
|
||||
public Charset getCharset() {
|
||||
return this.charset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the charset name.
|
||||
*
|
||||
* @return the charset name.
|
||||
* @since 1.4
|
||||
*/
|
||||
public String getCharsetName() {
|
||||
return this.charset.name();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a string representation of the object, which includes the charset name.
|
||||
*
|
||||
* @return a string representation of the object.
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString() + "[charsetName=" + this.charset + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/**
|
||||
* Standard {@link MessageDigest} algorithm names from the <cite>Java Cryptography Architecture Standard Algorithm Name
|
||||
* Documentation</cite>.
|
||||
* <p>
|
||||
* This class is immutable and thread-safe.
|
||||
* </p>
|
||||
*
|
||||
* @see <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html">Java Cryptography
|
||||
* Architecture Standard Algorithm Name Documentation</a>
|
||||
* @since 1.7
|
||||
* @version $Id: MessageDigestAlgorithms.java 1585867 2014-04-09 00:12:36Z ggregory $
|
||||
*/
|
||||
public class MessageDigestAlgorithms {
|
||||
|
||||
private MessageDigestAlgorithms() {
|
||||
// cannot be instantiated.
|
||||
}
|
||||
|
||||
/**
|
||||
* The MD2 message digest algorithm defined in RFC 1319.
|
||||
*/
|
||||
public static final String MD2 = "MD2";
|
||||
|
||||
/**
|
||||
* The MD5 message digest algorithm defined in RFC 1321.
|
||||
*/
|
||||
public static final String MD5 = "MD5";
|
||||
|
||||
/**
|
||||
* The SHA-1 hash algorithm defined in the FIPS PUB 180-2.
|
||||
*/
|
||||
public static final String SHA_1 = "SHA-1";
|
||||
|
||||
/**
|
||||
* The SHA-256 hash algorithm defined in the FIPS PUB 180-2.
|
||||
*/
|
||||
public static final String SHA_256 = "SHA-256";
|
||||
|
||||
/**
|
||||
* The SHA-384 hash algorithm defined in the FIPS PUB 180-2.
|
||||
*/
|
||||
public static final String SHA_384 = "SHA-384";
|
||||
|
||||
/**
|
||||
* The SHA-512 hash algorithm defined in the FIPS PUB 180-2.
|
||||
*/
|
||||
public static final String SHA_512 = "SHA-512";
|
||||
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
/**
|
||||
* Defines common encoding methods for String encoders.
|
||||
*
|
||||
* @version $Id: StringEncoder.java 1379145 2012-08-30 21:02:52Z tn $
|
||||
*/
|
||||
public interface StringEncoder extends Encoder {
|
||||
|
||||
/**
|
||||
* Encodes a String and returns a String.
|
||||
*
|
||||
* @param source
|
||||
* the String to encode
|
||||
* @return the encoded String
|
||||
* @throws EncoderException
|
||||
* thrown if there is an error condition during the encoding process.
|
||||
*/
|
||||
String encode( String source ) throws EncoderException;
|
||||
}
|
||||
|
||||
@@ -1,384 +0,0 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.mogo.utils.digest;
|
||||
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/**
|
||||
* Converts String to and from bytes using the encodings required by the Java specification. These encodings are
|
||||
* specified in <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">
|
||||
* Standard charsets</a>.
|
||||
*
|
||||
* <p>This class is immutable and thread-safe.</p>
|
||||
*
|
||||
* @see CharEncoding
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @version $Id: StringUtils.java 1634456 2014-10-27 05:26:56Z ggregory $
|
||||
* @since 1.4
|
||||
*/
|
||||
public class StringUtils {
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Compares two CharSequences, returning <code>true</code> if they represent equal sequences of characters.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* <code>null</code>s are handled without exceptions. Two <code>null</code> references are considered to be equal.
|
||||
* The comparison is case sensitive.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.equals(null, null) = true
|
||||
* StringUtils.equals(null, "abc") = false
|
||||
* StringUtils.equals("abc", null) = false
|
||||
* StringUtils.equals("abc", "abc") = true
|
||||
* StringUtils.equals("abc", "ABC") = false
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* Copied from Apache Commons Lang r1583482 on April 10, 2014 (day of 3.3.2 release).
|
||||
* </p>
|
||||
*
|
||||
* @see Object#equals(Object)
|
||||
* @param cs1
|
||||
* the first CharSequence, may be <code>null</code>
|
||||
* @param cs2
|
||||
* the second CharSequence, may be <code>null</code>
|
||||
* @return <code>true</code> if the CharSequences are equal (case-sensitive), or both <code>null</code>
|
||||
* @since 1.10
|
||||
*/
|
||||
public static boolean equals( final CharSequence cs1, final CharSequence cs2) {
|
||||
if (cs1 == cs2) {
|
||||
return true;
|
||||
}
|
||||
if (cs1 == null || cs2 == null) {
|
||||
return false;
|
||||
}
|
||||
if (cs1 instanceof String && cs2 instanceof String ) {
|
||||
return cs1.equals(cs2);
|
||||
}
|
||||
return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls {@link String#getBytes(Charset)}
|
||||
*
|
||||
* @param string
|
||||
* The string to encode (if null, return null).
|
||||
* @param charset
|
||||
* The {@link Charset} to encode the <code>String</code>
|
||||
* @return the encoded bytes
|
||||
*/
|
||||
private static byte[] getBytes( final String string, final Charset charset) {
|
||||
if (string == null) {
|
||||
return null;
|
||||
}
|
||||
return string.getBytes(charset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the given string into a sequence of bytes using the ISO-8859-1 charset, storing the result into a new
|
||||
* byte array.
|
||||
*
|
||||
* @param string
|
||||
* the String to encode, may be <code>null</code>
|
||||
* @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#ISO_8859_1} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @see #getBytesUnchecked(String, String)
|
||||
*/
|
||||
public static byte[] getBytesIso8859_1(final String string) {
|
||||
return getBytes(string, Charsets.ISO_8859_1);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Encodes the given string into a sequence of bytes using the named charset, storing the result into a new byte
|
||||
* array.
|
||||
* <p>
|
||||
* This method catches {@link UnsupportedEncodingException} and rethrows it as {@link IllegalStateException}, which
|
||||
* should never happen for a required charset name. Use this method when the encoding is required to be in the JRE.
|
||||
* </p>
|
||||
*
|
||||
* @param string
|
||||
* the String to encode, may be <code>null</code>
|
||||
* @param charsetName
|
||||
* The name of a required {@link Charset}
|
||||
* @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
|
||||
* @throws IllegalStateException
|
||||
* Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a
|
||||
* required charset name.
|
||||
* @see CharEncoding
|
||||
* @see String#getBytes(String)
|
||||
*/
|
||||
public static byte[] getBytesUnchecked( final String string, final String charsetName) {
|
||||
if (string == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return string.getBytes(charsetName);
|
||||
} catch (final UnsupportedEncodingException e) {
|
||||
throw StringUtils.newIllegalStateException(charsetName, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the given string into a sequence of bytes using the US-ASCII charset, storing the result into a new byte
|
||||
* array.
|
||||
*
|
||||
* @param string
|
||||
* the String to encode, may be <code>null</code>
|
||||
* @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#US_ASCII} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @see #getBytesUnchecked(String, String)
|
||||
*/
|
||||
public static byte[] getBytesUsAscii(final String string) {
|
||||
return getBytes(string, Charsets.US_ASCII);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the given string into a sequence of bytes using the UTF-16 charset, storing the result into a new byte
|
||||
* array.
|
||||
*
|
||||
* @param string
|
||||
* the String to encode, may be <code>null</code>
|
||||
* @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#UTF_16} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @see #getBytesUnchecked(String, String)
|
||||
*/
|
||||
public static byte[] getBytesUtf16(final String string) {
|
||||
return getBytes(string, Charsets.UTF_16);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the given string into a sequence of bytes using the UTF-16BE charset, storing the result into a new byte
|
||||
* array.
|
||||
*
|
||||
* @param string
|
||||
* the String to encode, may be <code>null</code>
|
||||
* @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#UTF_16BE} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @see #getBytesUnchecked(String, String)
|
||||
*/
|
||||
public static byte[] getBytesUtf16Be(final String string) {
|
||||
return getBytes(string, Charsets.UTF_16BE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the given string into a sequence of bytes using the UTF-16LE charset, storing the result into a new byte
|
||||
* array.
|
||||
*
|
||||
* @param string
|
||||
* the String to encode, may be <code>null</code>
|
||||
* @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#UTF_16LE} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @see #getBytesUnchecked(String, String)
|
||||
*/
|
||||
public static byte[] getBytesUtf16Le(final String string) {
|
||||
return getBytes(string, Charsets.UTF_16LE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte
|
||||
* array.
|
||||
*
|
||||
* @param string
|
||||
* the String to encode, may be <code>null</code>
|
||||
* @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
|
||||
* @see #getBytesUnchecked(String, String)
|
||||
*/
|
||||
public static byte[] getBytesUtf8(final String string) {
|
||||
return getBytes(string, Charsets.UTF_8);
|
||||
}
|
||||
|
||||
private static IllegalStateException newIllegalStateException( final String charsetName,
|
||||
final UnsupportedEncodingException e) {
|
||||
return new IllegalStateException(charsetName + ": " + e);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new <code>String</code> by decoding the specified array of bytes using the given charset.
|
||||
*
|
||||
* @param bytes
|
||||
* The bytes to be decoded into characters
|
||||
* @param charset
|
||||
* The {@link Charset} to encode the <code>String</code>
|
||||
* @return A new <code>String</code> decoded from the specified array of bytes using the given charset,
|
||||
* or <code>null</code> if the input byte array was <code>null</code>.
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
*/
|
||||
private static String newString( final byte[] bytes, final Charset charset) {
|
||||
return bytes == null ? null : new String(bytes, charset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new <code>String</code> by decoding the specified array of bytes using the given charset.
|
||||
* <p>
|
||||
* This method catches {@link UnsupportedEncodingException} and re-throws it as {@link IllegalStateException}, which
|
||||
* should never happen for a required charset name. Use this method when the encoding is required to be in the JRE.
|
||||
* </p>
|
||||
*
|
||||
* @param bytes
|
||||
* The bytes to be decoded into characters, may be <code>null</code>
|
||||
* @param charsetName
|
||||
* The name of a required {@link Charset}
|
||||
* @return A new <code>String</code> decoded from the specified array of bytes using the given charset,
|
||||
* or <code>null</code> if the input byte array was <code>null</code>.
|
||||
* @throws IllegalStateException
|
||||
* Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen for a
|
||||
* required charset name.
|
||||
* @see CharEncoding
|
||||
* @see String#String(byte[], String)
|
||||
*/
|
||||
public static String newString( final byte[] bytes, final String charsetName) {
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new String(bytes, charsetName);
|
||||
} catch (final UnsupportedEncodingException e) {
|
||||
throw StringUtils.newIllegalStateException(charsetName, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new <code>String</code> by decoding the specified array of bytes using the ISO-8859-1 charset.
|
||||
*
|
||||
* @param bytes
|
||||
* The bytes to be decoded into characters, may be <code>null</code>
|
||||
* @return A new <code>String</code> decoded from the specified array of bytes using the ISO-8859-1 charset, or
|
||||
* <code>null</code> if the input byte array was <code>null</code>.
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#ISO_8859_1} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
*/
|
||||
public static String newStringIso8859_1( final byte[] bytes) {
|
||||
return new String(bytes, Charsets.ISO_8859_1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new <code>String</code> by decoding the specified array of bytes using the US-ASCII charset.
|
||||
*
|
||||
* @param bytes
|
||||
* The bytes to be decoded into characters
|
||||
* @return A new <code>String</code> decoded from the specified array of bytes using the US-ASCII charset,
|
||||
* or <code>null</code> if the input byte array was <code>null</code>.
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#US_ASCII} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
*/
|
||||
public static String newStringUsAscii( final byte[] bytes) {
|
||||
return new String(bytes, Charsets.US_ASCII);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-16 charset.
|
||||
*
|
||||
* @param bytes
|
||||
* The bytes to be decoded into characters
|
||||
* @return A new <code>String</code> decoded from the specified array of bytes using the UTF-16 charset
|
||||
* or <code>null</code> if the input byte array was <code>null</code>.
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#UTF_16} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
*/
|
||||
public static String newStringUtf16( final byte[] bytes) {
|
||||
return new String(bytes, Charsets.UTF_16);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-16BE charset.
|
||||
*
|
||||
* @param bytes
|
||||
* The bytes to be decoded into characters
|
||||
* @return A new <code>String</code> decoded from the specified array of bytes using the UTF-16BE charset,
|
||||
* or <code>null</code> if the input byte array was <code>null</code>.
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#UTF_16BE} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
*/
|
||||
public static String newStringUtf16Be( final byte[] bytes) {
|
||||
return new String(bytes, Charsets.UTF_16BE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-16LE charset.
|
||||
*
|
||||
* @param bytes
|
||||
* The bytes to be decoded into characters
|
||||
* @return A new <code>String</code> decoded from the specified array of bytes using the UTF-16LE charset,
|
||||
* or <code>null</code> if the input byte array was <code>null</code>.
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#UTF_16LE} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
*/
|
||||
public static String newStringUtf16Le( final byte[] bytes) {
|
||||
return new String(bytes, Charsets.UTF_16LE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-8 charset.
|
||||
*
|
||||
* @param bytes
|
||||
* The bytes to be decoded into characters
|
||||
* @return A new <code>String</code> decoded from the specified array of bytes using the UTF-8 charset,
|
||||
* or <code>null</code> if the input byte array was <code>null</code>.
|
||||
* @throws NullPointerException
|
||||
* Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since it is
|
||||
* required by the Java platform specification.
|
||||
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
|
||||
*/
|
||||
public static String newStringUtf8( final byte[] bytes) {
|
||||
return newString(bytes, Charsets.UTF_8);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.mogo.utils.httpdns;
|
||||
|
||||
public class HttpSimpleLocation {
|
||||
private String cityCode;
|
||||
private double lat;
|
||||
private double lon;
|
||||
|
||||
public HttpSimpleLocation(String cityCode, double lat, double lon) {
|
||||
this.cityCode = cityCode;
|
||||
this.lat = lat;
|
||||
this.lon = lon;
|
||||
}
|
||||
|
||||
public String getCityCode() {
|
||||
return cityCode;
|
||||
}
|
||||
|
||||
public void setCityCode(String cityCode) {
|
||||
this.cityCode = cityCode;
|
||||
}
|
||||
|
||||
public double getLat() {
|
||||
return lat;
|
||||
}
|
||||
|
||||
public void setLat(double lat) {
|
||||
this.lat = lat;
|
||||
}
|
||||
|
||||
public double getLon() {
|
||||
return lon;
|
||||
}
|
||||
|
||||
public void setLon(double lon) {
|
||||
this.lon = lon;
|
||||
}
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.mogo.utils.logger.Logger;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
|
||||
public abstract class BaseParams {
|
||||
|
||||
private static final String TAG = "BaseParams";
|
||||
|
||||
protected ConcurrentHashMap< String, Object > urlParams;
|
||||
|
||||
protected BaseParams() {
|
||||
this.init();
|
||||
}
|
||||
|
||||
public Object get( String key ) {
|
||||
return this.urlParams != null && key != null ? this.urlParams.get( key ) : "";
|
||||
}
|
||||
|
||||
protected BaseParams( Map< String, Object > source ) {
|
||||
this.init();
|
||||
Iterator iterator = source.entrySet().iterator();
|
||||
|
||||
while ( iterator.hasNext() ) {
|
||||
Map.Entry entry = ( Map.Entry ) iterator.next();
|
||||
this.put( ( String ) entry.getKey(), entry.getValue() );
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected BaseParams( String key, Object value ) {
|
||||
this.init();
|
||||
this.put( key, value );
|
||||
}
|
||||
|
||||
protected BaseParams( Object... keysAndValues ) {
|
||||
this.init();
|
||||
int len = keysAndValues.length;
|
||||
if ( len % 2 != 0 ) {
|
||||
throw new IllegalArgumentException( "Supplied arguments must be even" );
|
||||
} else {
|
||||
for ( int i = 0; i < len; i += 2 ) {
|
||||
String key = String.valueOf( keysAndValues[i] );
|
||||
Object value = keysAndValues[i + 1];
|
||||
this.put( key, value );
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private boolean checkValue( final Object value ) {
|
||||
if ( value instanceof CharSequence ) {
|
||||
return !TextUtils.isEmpty( ( CharSequence ) value );
|
||||
}
|
||||
|
||||
if ( value == null || value.getClass() == null ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final Class< ? > clazz = value.getClass();
|
||||
return clazz.isPrimitive() ||
|
||||
clazz.isAssignableFrom( Boolean.class ) ||
|
||||
clazz.isAssignableFrom( Character.class ) ||
|
||||
clazz.isAssignableFrom( Byte.class ) ||
|
||||
clazz.isAssignableFrom( Short.class ) ||
|
||||
clazz.isAssignableFrom( Integer.class ) ||
|
||||
clazz.isAssignableFrom( Long.class ) ||
|
||||
clazz.isAssignableFrom( Float.class ) ||
|
||||
clazz.isAssignableFrom( Double.class );
|
||||
}
|
||||
|
||||
private boolean checkKey( String key ) {
|
||||
return !TextUtils.isEmpty( key );
|
||||
}
|
||||
|
||||
public BaseParams put( String key, Object value ) {
|
||||
if ( checkKey( key ) && checkValue( value ) ) {
|
||||
urlParams.put( key, value );
|
||||
} else {
|
||||
Logger.e( TAG, "parameter key is illegal or parameter value is illegal" );
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Object remove( String key ) {
|
||||
return this.urlParams.remove( key );
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
Iterator< Map.Entry< String, Object > > iterator = this.urlParams.entrySet().iterator();
|
||||
while ( iterator.hasNext() ) {
|
||||
Map.Entry< String, Object > entry = iterator.next();
|
||||
if ( result.length() > 0 ) {
|
||||
result.append( "&" );
|
||||
}
|
||||
|
||||
result.append( entry.getKey() );
|
||||
result.append( "=" );
|
||||
result.append( entry.getValue() );
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
this.urlParams = new ConcurrentHashMap< String, Object >();
|
||||
}
|
||||
|
||||
public List< BasicNameValuePair > getParamsList() {
|
||||
LinkedList< BasicNameValuePair > pairs = new LinkedList< BasicNameValuePair >();
|
||||
Iterator< Map.Entry< String, Object > > iterator = this.urlParams.entrySet().iterator();
|
||||
|
||||
while ( iterator.hasNext() ) {
|
||||
Map.Entry< String, Object > entry = iterator.next();
|
||||
pairs.add( new BasicNameValuePair( entry.getKey(), entry.getValue() ) );
|
||||
}
|
||||
|
||||
return pairs;
|
||||
}
|
||||
|
||||
public Map< String, Object > getOriginMap() {
|
||||
return urlParams;
|
||||
}
|
||||
|
||||
public String getParamString() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
Iterator< BasicNameValuePair > iterator = getParamsList().iterator();
|
||||
|
||||
while ( iterator.hasNext() ) {
|
||||
BasicNameValuePair parameter = iterator.next();
|
||||
String key = parameter.getName();
|
||||
Object value = parameter.getValue();
|
||||
if ( result.length() > 0 ) {
|
||||
result.append( "&" );
|
||||
}
|
||||
|
||||
result.append( key );
|
||||
result.append( "=" );
|
||||
result.append( value );
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static class BasicNameValuePair {
|
||||
private String name;
|
||||
private Object value;
|
||||
|
||||
public BasicNameValuePair( String name, Object value ) {
|
||||
this.name = name;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName( String name ) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue( Object value ) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
|
||||
|
||||
public class CallerNotAliveException extends Exception {
|
||||
|
||||
public CallerNotAliveException( String message){
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
|
||||
@Retention( RetentionPolicy.SOURCE)
|
||||
@Target( ElementType.ANNOTATION_TYPE)
|
||||
public @interface CallerRestrictTo {
|
||||
Class<?>[] value();
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.Dialog;
|
||||
import android.app.Fragment;
|
||||
import android.content.ContextWrapper;
|
||||
import android.view.View;
|
||||
import android.widget.PopupWindow;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
|
||||
@Retention( RetentionPolicy.SOURCE )
|
||||
@Target( ElementType.PARAMETER )
|
||||
@CallerRestrictTo( {
|
||||
Activity.class,
|
||||
Fragment.class,
|
||||
androidx.fragment.app.Fragment.class,
|
||||
View.class,
|
||||
Dialog.class,
|
||||
PopupWindow.class,
|
||||
ContextWrapper.class,
|
||||
Object.class
|
||||
} )
|
||||
public @interface CallerType {
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
package com.mogo.utils.network
|
||||
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import com.mogo.eagle.core.data.BaseResponse
|
||||
import com.mogo.utils.network.exception.ApiException
|
||||
import com.mogo.utils.network.exception.CommonException.Companion.NETWORK_EXCEPTION
|
||||
import com.mogo.utils.network.exception.CommonException.Companion.NULL_EXCEPTION
|
||||
import com.mogo.utils.network.exception.CommonException.Companion.NULL_REQUEST_DATA_API_EXCEPTION
|
||||
import kotlinx.coroutines.*
|
||||
import java.net.SocketTimeoutException
|
||||
import java.net.UnknownHostException
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.TimeoutException
|
||||
|
||||
class Request<T> {
|
||||
private lateinit var loader: suspend () -> T
|
||||
|
||||
private var start: (() -> Unit)? = null
|
||||
|
||||
private var onSuccess: ((T) -> Unit)? = null
|
||||
|
||||
private var onError: ((java.lang.Exception) -> Unit)? = null
|
||||
|
||||
private var onComplete: (() -> Unit)? = null
|
||||
|
||||
private var addLifecycle: LifecycleOwner? = null
|
||||
|
||||
infix fun loader(loader: suspend () -> T) {
|
||||
this.loader = loader
|
||||
}
|
||||
|
||||
infix fun start(start: (() -> Unit)?) {
|
||||
this.start = start
|
||||
}
|
||||
|
||||
infix fun onSuccess(onSuccess: ((T) -> Unit)?) {
|
||||
this.onSuccess = onSuccess
|
||||
}
|
||||
|
||||
infix fun onError(onError: ((java.lang.Exception) -> Unit)?) {
|
||||
this.onError = onError
|
||||
}
|
||||
|
||||
infix fun onComplete(onComplete: (() -> Unit)?) {
|
||||
this.onComplete = onComplete
|
||||
}
|
||||
|
||||
infix fun addLifecycle(addLifecycle: LifecycleOwner?) {
|
||||
this.addLifecycle = addLifecycle
|
||||
}
|
||||
|
||||
fun request(requestKey: String? = null) {
|
||||
|
||||
//todo list 缓存result ,在停止时关闭
|
||||
GlobalScope.launch(context = Dispatchers.Main) {
|
||||
|
||||
start?.invoke()
|
||||
try {
|
||||
val deferred = GlobalScope.async(Dispatchers.IO, start = CoroutineStart.LAZY) {
|
||||
loader()
|
||||
}
|
||||
|
||||
requestKey?.let {
|
||||
deferredMap[requestKey] = deferred as Deferred<Any>
|
||||
}
|
||||
|
||||
val result = deferred.await()
|
||||
if (result != null && result is BaseResponse<*>) {
|
||||
if (result.code == 0 || result.code == 200) {
|
||||
onSuccess?.invoke(result)
|
||||
} else {
|
||||
throw ApiException(result.code, result.msg)
|
||||
}
|
||||
} else {
|
||||
throw NULL_REQUEST_DATA_API_EXCEPTION
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
//数据打点
|
||||
if (e == null) {
|
||||
onError?.invoke(NULL_EXCEPTION)
|
||||
}
|
||||
when (e) {
|
||||
is UnknownHostException -> onError?.invoke(NETWORK_EXCEPTION)
|
||||
is TimeoutException -> onError?.invoke(NETWORK_EXCEPTION)
|
||||
is SocketTimeoutException -> onError?.invoke(NETWORK_EXCEPTION)
|
||||
else -> onError?.invoke(java.lang.Exception(e.message))
|
||||
}
|
||||
} finally {
|
||||
requestKey?.let {
|
||||
if (deferredMap.contains(requestKey)) {
|
||||
deferredMap.remove(requestKey)
|
||||
}
|
||||
}
|
||||
onComplete?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
inline fun <T> request(requestKey: String? = "", buildRequest: Request<T>.() -> Unit) {
|
||||
Request<T>().apply(buildRequest).request(requestKey)
|
||||
}
|
||||
|
||||
private val deferredMap = ConcurrentHashMap<String, Deferred<Any>>()
|
||||
|
||||
fun cancel(requestKey: String) {
|
||||
if (deferredMap.contains(requestKey)) {
|
||||
deferredMap[requestKey]!!.cancel(CancellationException("manual cancel !"))
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun <T : Any> apiCall(call: suspend () -> BaseResponse<T>): BaseResponse<T> {
|
||||
return call.invoke()
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.List;
|
||||
|
||||
public
|
||||
/**
|
||||
* @author congtaowang
|
||||
* @since 2020/11/18
|
||||
*
|
||||
* 将HOST转换为HttpDNS的ip
|
||||
*/
|
||||
interface HttpDns {
|
||||
|
||||
List< InetAddress > lookup( String hostname ) throws UnknownHostException;
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpParams extends BaseParams {
|
||||
public HttpParams() {
|
||||
}
|
||||
|
||||
public HttpParams( Map< String, Object > source) {
|
||||
super(source);
|
||||
}
|
||||
|
||||
public HttpParams( Object... keysAndValues) {
|
||||
super(keysAndValues);
|
||||
}
|
||||
|
||||
public HttpParams( String key, Object value) {
|
||||
super(key, value);
|
||||
}
|
||||
|
||||
public List<BasicNameValuePair> getParamList() {
|
||||
List<BasicNameValuePair> list = getParamsList();
|
||||
Collections.sort(list, new KVPairComparator());
|
||||
return list;
|
||||
}
|
||||
|
||||
public String getSortedParamsString() {
|
||||
List<BasicNameValuePair> list = getParamList();
|
||||
StringBuilder sb = new StringBuilder(NetConfig.instance().getSignaturePrefix());
|
||||
for (BasicNameValuePair basicNameValuePair : list) {
|
||||
sb.append(basicNameValuePair.getName());
|
||||
sb.append(basicNameValuePair.getValue());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public Map< String, Object > getParamsMap() {
|
||||
List<BasicNameValuePair> list = getParamList();
|
||||
HashMap< String, Object > map = new HashMap< String, Object >();
|
||||
for (BasicNameValuePair basicNameValuePair : list) {
|
||||
map.put(basicNameValuePair.getName(), basicNameValuePair.getValue());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
public String getSortedUrlParamsString() {
|
||||
List<BasicNameValuePair> list = getParamList();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (BasicNameValuePair basicNameValuePair : list) {
|
||||
String key = basicNameValuePair.getName();
|
||||
Object value = basicNameValuePair.getValue();
|
||||
if (sb.length() > 0)
|
||||
sb.append("&");
|
||||
sb.append(key);
|
||||
sb.append("=");
|
||||
sb.append(value);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private class KVPairComparator implements Comparator<BasicNameValuePair> {
|
||||
public int compare(BasicNameValuePair pairA, BasicNameValuePair pairB) {
|
||||
return pairA.getName().compareTo(pairB.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.collection.ArraySet;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSession;
|
||||
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.internal.tls.OkHostnameVerifier;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This is a configuration class provided for clients.For better extension and customization,client can set customized parameters of network
|
||||
* based on their own application. However you should set these parameters before you get the global instance
|
||||
* of {@link okhttp3.OkHttpClient} by {@link OkHttpFactory} for the first time.<p/>
|
||||
* <p>
|
||||
* Some of the parameters have default values, so there is not a must to use this class.<p/>
|
||||
*/
|
||||
|
||||
public final class NetConfig {
|
||||
private long readTimeout = NetConstants.READ_TIMEOUT;
|
||||
private long writeTimeout = NetConstants.WRITE_TIMEOUT;
|
||||
private long connectTimeout = NetConstants.CONNECT_TIMEOUT;
|
||||
|
||||
private final Set< Interceptor > interceptors = new ArraySet<>();
|
||||
private final Set< Interceptor > networkInterceptors = new ArraySet<>();
|
||||
private final HostnameVerifier allowAllHostnameVerifier = new HostnameVerifier() {
|
||||
@Override
|
||||
public boolean verify( String hostname, SSLSession session ) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private String signaturePrefix = "com.foundation.network";
|
||||
private HostnameVerifier hostnameVerifier = OkHostnameVerifier.INSTANCE;
|
||||
private Map< String, Object > publicParams;
|
||||
private boolean isLoggable;
|
||||
private Context appContext;
|
||||
|
||||
private SSLContext sslContext;
|
||||
|
||||
private HttpDns httpDns;
|
||||
|
||||
private NetConfig() {
|
||||
}
|
||||
|
||||
private static final class SingletonHolder {
|
||||
private static final NetConfig INSTANCE = new NetConfig();
|
||||
}
|
||||
|
||||
public static NetConfig instance() {
|
||||
return SingletonHolder.INSTANCE;
|
||||
}
|
||||
|
||||
public synchronized long getReadTimeout() {
|
||||
return readTimeout;
|
||||
}
|
||||
|
||||
public synchronized NetConfig setReadTimeout( int readTimeout ) {
|
||||
this.readTimeout = readTimeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
public synchronized long getWriteTimeout() {
|
||||
return writeTimeout;
|
||||
}
|
||||
|
||||
public synchronized NetConfig setWriteTimeout( int writeTimeout ) {
|
||||
this.writeTimeout = writeTimeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
public synchronized long getConnectTimeout() {
|
||||
return connectTimeout;
|
||||
}
|
||||
|
||||
public synchronized NetConfig setConnectTimeout( int connectTimeout ) {
|
||||
this.connectTimeout = connectTimeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
public synchronized HostnameVerifier getHostnameVerifier() {
|
||||
return hostnameVerifier;
|
||||
}
|
||||
|
||||
public synchronized NetConfig setHostnameVerifier( HostnameVerifier hostnameVerifier ) {
|
||||
this.hostnameVerifier = hostnameVerifier;
|
||||
return this;
|
||||
}
|
||||
|
||||
public synchronized NetConfig setSignaturePrefix( String prefix ) {
|
||||
this.signaturePrefix = prefix;
|
||||
return this;
|
||||
}
|
||||
|
||||
public synchronized String getSignaturePrefix() {
|
||||
return signaturePrefix;
|
||||
}
|
||||
|
||||
public synchronized Set< Interceptor > getInterceptors() {
|
||||
return interceptors;
|
||||
}
|
||||
|
||||
public synchronized NetConfig addInterceptor( Interceptor interceptor ) {
|
||||
interceptors.add( interceptor );
|
||||
return this;
|
||||
}
|
||||
|
||||
public synchronized Set< Interceptor > getNetworkInterceptors() {
|
||||
return networkInterceptors;
|
||||
}
|
||||
|
||||
public synchronized NetConfig addNetworkInterceptor( Interceptor networkInterceptor ) {
|
||||
networkInterceptors.add( networkInterceptor );
|
||||
return this;
|
||||
}
|
||||
|
||||
public synchronized NetConfig setPublicParams( Map< String, Object > publicParams ) {
|
||||
this.publicParams = publicParams;
|
||||
return this;
|
||||
}
|
||||
|
||||
public synchronized Map< String, Object > getPublicParams() {
|
||||
return publicParams;
|
||||
}
|
||||
|
||||
public synchronized boolean isLoggable() {
|
||||
return isLoggable;
|
||||
}
|
||||
|
||||
public synchronized void setLoggable( boolean loggable ) {
|
||||
isLoggable = loggable;
|
||||
}
|
||||
|
||||
public synchronized NetConfig setAppContext( Context appContext ) {
|
||||
if ( appContext instanceof Application ) {
|
||||
this.appContext = appContext;
|
||||
} else {
|
||||
this.appContext = appContext.getApplicationContext();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public synchronized Context getAppContext() {
|
||||
return appContext;
|
||||
}
|
||||
|
||||
public synchronized SSLContext getSslContext() {
|
||||
return sslContext;
|
||||
}
|
||||
|
||||
public synchronized void setSslContext( SSLContext sslContext ) {
|
||||
this.sslContext = sslContext;
|
||||
}
|
||||
|
||||
public HttpDns getHttpDns() {
|
||||
return httpDns;
|
||||
}
|
||||
|
||||
public NetConfig setHttpDns( HttpDns httpDns ) {
|
||||
this.httpDns = httpDns;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
|
||||
public class NetConstants {
|
||||
/** 无数据 */
|
||||
public final static int NO_DATA = -800;
|
||||
/** 数据返回正常 */
|
||||
public final static int OK = 0;
|
||||
|
||||
public static final long READ_TIMEOUT = 20_000L;
|
||||
public static final long WRITE_TIMEOUT = 20_000L;
|
||||
public static final long CONNECT_TIMEOUT = 15_000L;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.mogo.utils.CheckUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.Response;
|
||||
|
||||
|
||||
final class NetworkMonitorInterceptor implements Interceptor {
|
||||
private static final String TAG = "NetworkMonitorInterceptor";
|
||||
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
final Context appContext = NetConfig.instance().getAppContext();
|
||||
if(appContext != null && !CheckUtils.isNetworkConnected(appContext)){
|
||||
throw new NetworkUnavailableException("Network is unavailable");
|
||||
}
|
||||
return chain.proceed(chain.request());
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import okhttp3.Interceptor;
|
||||
|
||||
/**
|
||||
* An exception occurs whenever network is not reachable, it's threw by {@link NetworkMonitorInterceptor}
|
||||
* during {@link NetworkMonitorInterceptor#intercept(Interceptor.Chain)} method.
|
||||
*
|
||||
*/
|
||||
|
||||
public class NetworkUnavailableException extends IOException {
|
||||
|
||||
public NetworkUnavailableException( String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import com.mogo.utils.logger.Logger;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import okhttp3.ConnectionPool;
|
||||
import okhttp3.Dns;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.OkHttpClient;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Before getting an global instance of {@link OkHttpClient}, you can use {@link NetConfig} to set some
|
||||
* parameters of network. Note that network configuration must be first set before you get an instance of {@link OkHttpClient},
|
||||
* for the first time, otherwise configuration is invalid<p/>
|
||||
*
|
||||
*/
|
||||
public final class OkHttpFactory {
|
||||
|
||||
private static volatile OkHttpClient sInstance;
|
||||
|
||||
private OkHttpFactory() {
|
||||
}
|
||||
|
||||
public static OkHttpClient getInstance() {
|
||||
if (sInstance == null) {
|
||||
synchronized (OkHttpClient.class) {
|
||||
if (sInstance == null) {
|
||||
final OkHttpClient.Builder builder = new OkHttpClient.Builder();
|
||||
builder.addInterceptor(new NetworkMonitorInterceptor());
|
||||
builder.addInterceptor(new RequestLogInterceptor());
|
||||
builder.addInterceptor(new ResponseLogInterceptor());
|
||||
builder.hostnameVerifier(NetConfig.instance().getHostnameVerifier());
|
||||
if ( NetConfig.instance().getSslContext() != null ) {
|
||||
builder.sslSocketFactory( NetConfig.instance().getSslContext().getSocketFactory());
|
||||
}
|
||||
builder.connectTimeout(NetConfig.instance().getConnectTimeout(), TimeUnit.MILLISECONDS);
|
||||
builder.readTimeout(NetConfig.instance().getReadTimeout(), TimeUnit.MILLISECONDS);
|
||||
builder.writeTimeout(NetConfig.instance().getWriteTimeout(), TimeUnit.MILLISECONDS);
|
||||
final Set<Interceptor> interceptors = NetConfig.instance().getInterceptors();
|
||||
for(Interceptor interceptor : interceptors){
|
||||
builder.addInterceptor(interceptor);
|
||||
}
|
||||
|
||||
final Set<Interceptor> networkInterceptors = NetConfig.instance().getNetworkInterceptors();
|
||||
for(Interceptor networkInterceptor : networkInterceptors){
|
||||
builder.addNetworkInterceptor(networkInterceptor);
|
||||
}
|
||||
|
||||
HttpDns httpDns = NetConfig.instance().getHttpDns();
|
||||
if ( httpDns != null ) {
|
||||
builder.dns( hostname -> {
|
||||
List< InetAddress > addresses = httpDns.lookup( hostname );
|
||||
if ( addresses != null && !addresses.isEmpty() ) {
|
||||
Logger.d("OkHttpFactory","look up hostname: "+hostname+" address: "+addresses.get(0).getHostAddress());
|
||||
return addresses;
|
||||
}
|
||||
Logger.d("OkHttpFactory","hostname: "+hostname+" no address");
|
||||
return Dns.SYSTEM.lookup( hostname );
|
||||
} );
|
||||
}
|
||||
|
||||
sInstance = builder.build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sInstance;
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import com.mogo.utils.logger.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.Protocol;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
import okio.Buffer;
|
||||
|
||||
|
||||
final class RequestLogInterceptor implements Interceptor {
|
||||
private static final String TAG = "RequestLogInterceptor";
|
||||
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
Request request = chain.request();
|
||||
RequestBody requestBody = request.body();
|
||||
boolean hasRequestBody = requestBody != null;
|
||||
|
||||
String protocol = Protocol.HTTP_1_1.toString();
|
||||
if(chain.connection() != null && chain.connection().protocol() != null){
|
||||
protocol = chain.connection().protocol().toString();
|
||||
}
|
||||
|
||||
StringBuilder logMsg = new StringBuilder();
|
||||
logMsg.append("--> ");
|
||||
logMsg.append(protocol).append(", ");
|
||||
logMsg.append(request.method()).append(", ");
|
||||
logMsg.append("Request Headers: ").append(request.headers()).append("\r\n");
|
||||
logMsg.append(request.url()).append("\r\n");
|
||||
if(hasRequestBody){
|
||||
logMsg.append("Content-Type: ").append(requestBody.contentType()).append(", ");
|
||||
logMsg.append("\r\nContent-Length: ").append(requestBody.contentLength());
|
||||
try {
|
||||
String body = null;
|
||||
Charset UTF8 = Charset.forName("UTF-8");
|
||||
Buffer buffer = new Buffer();
|
||||
requestBody.writeTo(buffer);
|
||||
Charset charset = UTF8;
|
||||
MediaType contentType = requestBody.contentType();
|
||||
if (contentType != null) {
|
||||
charset = contentType.charset(UTF8);
|
||||
}
|
||||
if (charset != null) {
|
||||
body = buffer.readString(charset);
|
||||
}
|
||||
logMsg.append("\r\nContent-body: ").append(body);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
logMsg.append("\r\n<-- end http request");
|
||||
|
||||
if(NetConfig.instance().isLoggable()){
|
||||
Logger.d(TAG, logMsg.toString());
|
||||
}
|
||||
|
||||
return chain.proceed(request);
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
import android.content.Context;
|
||||
import android.view.KeyEvent;
|
||||
|
||||
|
||||
import com.mogo.utils.network.utils.Util;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class RequestOptions {
|
||||
private static final String DEFAULT_LOADING_MESSAGE = "正在加载中...";
|
||||
|
||||
private Object caller;
|
||||
private Context context;
|
||||
private Map< String, Object > parameter;
|
||||
private CharSequence loadingMessage;
|
||||
private boolean loading = false;
|
||||
private boolean cancelable;
|
||||
private boolean cancelableOnTouchOutside;
|
||||
|
||||
/**
|
||||
* Private constructor with some default initialization.
|
||||
*/
|
||||
public RequestOptions(@CallerType Object caller) {
|
||||
this.caller = caller;
|
||||
this.context = Util.getContext( caller );
|
||||
this.parameter = Collections.emptyMap();
|
||||
this.loadingMessage = DEFAULT_LOADING_MESSAGE;
|
||||
this.loading = false;
|
||||
this.cancelable = true;
|
||||
this.cancelableOnTouchOutside = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method to create an instance of {@link RequestOptions}
|
||||
*
|
||||
* <p>
|
||||
* Request caller can be any type of object. HOWEVER, if you want to show loading message
|
||||
* when request is ongoing or if you want to monitor caller's lifecycle in process of requesting
|
||||
* in order to avoid unexpected async exceptions, please use one of {@link android.app.Activity},
|
||||
* {@link android.app.Fragment},{@link androidx.fragment.app.Fragment},{@link android.view.View},
|
||||
* {@link android.app.Dialog} and {@link android.widget.PopupWindow} as caller<p/>
|
||||
*
|
||||
* <p>
|
||||
* Caller can be other types if loading message is not intended to be shown.<p/>
|
||||
*
|
||||
* <p>
|
||||
* It's strongly suggested that caller should have an context for better control of caller's lifecycle.<p/>
|
||||
*/
|
||||
public static RequestOptions create( Object caller ) {
|
||||
return new RequestOptions( caller );
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutator for request parameters
|
||||
*/
|
||||
public RequestOptions parameter( Map< String, Object > parameter ) {
|
||||
this.parameter = parameter;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutator for indicating whether loading message should be displayed while request is ongoing
|
||||
*/
|
||||
public RequestOptions loading( boolean loading ) {
|
||||
this.loading = loading;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutator for loading message
|
||||
*/
|
||||
private RequestOptions loadingMessage( CharSequence loadingMessage ) {
|
||||
this.loading = true;
|
||||
this.loadingMessage = loadingMessage;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutator for indicating that loading dialog is cancelable with the {@link KeyEvent#KEYCODE_BACK BACK} key.
|
||||
* Default value is true.
|
||||
*/
|
||||
public RequestOptions cancelable( boolean cancelable ) {
|
||||
this.cancelable = cancelable;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutator for indicating that loading dialog is cancelable with touching outside of the dialog.
|
||||
* Default value is false.
|
||||
*/
|
||||
public RequestOptions cancelableOnTouchOutside( boolean cancelableOnTouchOutside ) {
|
||||
this.cancelableOnTouchOutside = cancelableOnTouchOutside;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Object getCaller() {
|
||||
return caller;
|
||||
}
|
||||
|
||||
public Context getContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
public Map< String, Object > getParameter() {
|
||||
return parameter;
|
||||
}
|
||||
|
||||
public CharSequence getLoadingMessage() {
|
||||
return loadingMessage;
|
||||
}
|
||||
|
||||
public boolean isLoading() {
|
||||
return loading;
|
||||
}
|
||||
|
||||
public boolean isCancelable() {
|
||||
return cancelable;
|
||||
}
|
||||
|
||||
public boolean isCancelableOnTouchOutside() {
|
||||
return cancelableOnTouchOutside;
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
|
||||
import com.mogo.utils.logger.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.Response;
|
||||
import okhttp3.ResponseBody;
|
||||
|
||||
|
||||
final class ResponseLogInterceptor implements Interceptor {
|
||||
private static final String TAG = "ResponseLogInterceptor";
|
||||
|
||||
@Override
|
||||
public Response intercept( Chain chain ) throws IOException {
|
||||
long startTime = System.nanoTime();
|
||||
Response response = chain.proceed( chain.request() );
|
||||
long endTime = TimeUnit.NANOSECONDS.toMillis( System.nanoTime() - startTime );
|
||||
|
||||
ResponseBody responseBody = response.body();
|
||||
String responseContent = null;
|
||||
String bodySize = null;
|
||||
MediaType contentType = null;
|
||||
boolean consumedResponse = false;
|
||||
|
||||
StringBuilder logMsg = new StringBuilder();
|
||||
|
||||
if ( responseBody != null ) {
|
||||
long contentLength = responseBody.contentLength();
|
||||
bodySize = contentLength != -1L ? contentLength + "-byte" : "unknown-length";
|
||||
contentType = responseBody.contentType();
|
||||
responseContent = responseBody.string();
|
||||
consumedResponse = true;
|
||||
}
|
||||
|
||||
logMsg.append( "--> " );
|
||||
logMsg.append( response.code() ).append( " " );
|
||||
logMsg.append( response.message() ).append( " " );
|
||||
logMsg.append( response.protocol() ).append( " " );
|
||||
logMsg.append( response.request().url() ).append( "\r\n" );
|
||||
logMsg.append( "Response Content: " ).append( responseContent ).append( "\r\n" );
|
||||
logMsg.append( "Content-Type: " ).append( contentType ).append( ", " );
|
||||
logMsg.append( "Content-Length: " ).append( bodySize ).append( ", " );
|
||||
logMsg.append( " (" ).append( endTime ).append( "ms)" );
|
||||
logMsg.append( " <-- end http response" );
|
||||
|
||||
if ( NetConfig.instance().isLoggable() ) {
|
||||
Logger.d( TAG, logMsg.toString() );
|
||||
}
|
||||
|
||||
return consumedResponse ?
|
||||
response.newBuilder().body( ResponseBody.create( contentType, responseContent ) ).build() :
|
||||
response;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
|
||||
import retrofit2.Retrofit;
|
||||
|
||||
public final class RetrofitFactory {
|
||||
|
||||
private RetrofitFactory() {
|
||||
}
|
||||
|
||||
public static synchronized Retrofit getInstance(String baseUrl) {
|
||||
return com.mogo.cloud.network.RetrofitFactory.INSTANCE.getInstance(baseUrl);
|
||||
}
|
||||
|
||||
public static synchronized Retrofit getInstanceNoCallAdapter(String baseUrl) {
|
||||
return com.mogo.cloud.network.RetrofitFactory.INSTANCE.getInstanceNoCallAdapter(baseUrl);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.mogo.utils.network;
|
||||
|
||||
public class ServerParam {
|
||||
public static final String SIGNATURE = "sig";
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.mogo.utils.network.exception
|
||||
|
||||
class ApiException : CommonException {
|
||||
|
||||
constructor(code: Int, msg: String) : super(code, msg)
|
||||
|
||||
fun getErrorMsg():String{
|
||||
return msg
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.mogo.utils.network.exception
|
||||
|
||||
open class CommonException :Exception{
|
||||
|
||||
companion object{
|
||||
val NETWORK_EXCEPTION = CommonException(1, "network is error")
|
||||
val NULL_EXCEPTION = CommonException(1, "exception is null")
|
||||
val NULL_REQUEST_DATA_API_EXCEPTION = CommonException(1, "request data is null")
|
||||
}
|
||||
|
||||
protected var code: Int = 0
|
||||
protected var msg: String = ""
|
||||
|
||||
constructor(code: Int, msg: String) : super(msg) {
|
||||
this.code = code
|
||||
this.msg = msg
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.mogo.utils.network.ui;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.fragment.app.FragmentActivity;
|
||||
import androidx.fragment.app.FragmentManager;
|
||||
import androidx.fragment.app.FragmentTransaction;
|
||||
|
||||
import com.mogo.utils.logger.Logger;
|
||||
|
||||
|
||||
public class ProgressDialog {
|
||||
|
||||
private static final String TAG = "ProgressDialog";
|
||||
|
||||
public static final String LOADING_DIALOG_TAG = "loading_dialog_tag";
|
||||
|
||||
private ProgressDialogFragment mProgressDialogFragment;
|
||||
private FragmentManager mFragmentManager;
|
||||
|
||||
public void showLoadingDialog( @NonNull Context context, CharSequence loadingMassage) {
|
||||
showLoadingDialog(context, loadingMassage, true);
|
||||
}
|
||||
|
||||
public void showLoadingDialog( @NonNull Context context, CharSequence loadingMassage, boolean cancelable) {
|
||||
showLoadingDialog(context, loadingMassage, cancelable, false);
|
||||
}
|
||||
|
||||
public void showLoadingDialog( Context context, CharSequence loadingMassage, boolean cancelable, boolean cancelableOnTouchOutSide) {
|
||||
if (context != null && context instanceof FragmentActivity )
|
||||
mFragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
|
||||
|
||||
if (mFragmentManager == null)
|
||||
return;
|
||||
|
||||
mProgressDialogFragment = new ProgressDialogFragment();
|
||||
mProgressDialogFragment.setContent(loadingMassage, cancelable, cancelableOnTouchOutSide);
|
||||
|
||||
try {
|
||||
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
|
||||
fragmentTransaction.add( mProgressDialogFragment, LOADING_DIALOG_TAG );
|
||||
fragmentTransaction.add(mProgressDialogFragment, LOADING_DIALOG_TAG);
|
||||
fragmentTransaction.commitAllowingStateLoss();
|
||||
} catch ( IllegalStateException e) {
|
||||
Logger.e(TAG, e, e.getMessage());
|
||||
mFragmentManager = null;
|
||||
mProgressDialogFragment = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void removeLoadingDialog() {
|
||||
if (mProgressDialogFragment != null) {
|
||||
try {
|
||||
mProgressDialogFragment.dismissAllowingStateLoss();
|
||||
} catch ( Exception e) {
|
||||
Logger.e(TAG, "dialog 取消异常");
|
||||
} finally {
|
||||
mProgressDialogFragment = null;
|
||||
mFragmentManager = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.mogo.utils.network.ui;
|
||||
|
||||
import android.app.Dialog;
|
||||
import android.app.ProgressDialog;
|
||||
import android.os.Bundle;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.fragment.app.DialogFragment;
|
||||
|
||||
|
||||
public class ProgressDialogFragment extends DialogFragment {
|
||||
|
||||
/**
|
||||
* Progress显示的文字
|
||||
*/
|
||||
private CharSequence mMessage;
|
||||
|
||||
private boolean mCancelableOnTouchOutSide;
|
||||
|
||||
/**
|
||||
* 设置dialog内容
|
||||
*
|
||||
* @param message 显示的文字
|
||||
* @param cancelable 是否可以被取消 例如back键取消
|
||||
*/
|
||||
public void setContent( CharSequence message, boolean cancelable, boolean cancelableOnTouchOutSide) {
|
||||
mMessage = message;
|
||||
mCancelableOnTouchOutSide = cancelableOnTouchOutSide;
|
||||
setCancelable(cancelable);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Dialog onCreateDialog( Bundle savedInstanceState) {
|
||||
ProgressDialog dialog = new ProgressDialog(getActivity());
|
||||
dialog.setMessage(mMessage);
|
||||
dialog.setCanceledOnTouchOutside(mCancelableOnTouchOutSide);
|
||||
return dialog;
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
package com.mogo.utils.network.utils;
|
||||
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class GsonUtil {
|
||||
|
||||
private static volatile Gson gson;
|
||||
|
||||
private GsonUtil() {}
|
||||
|
||||
public static Gson getGson() {
|
||||
if(gson == null){
|
||||
synchronized (GsonUtil.class) {
|
||||
if (gson == null) {
|
||||
GsonBuilder builder = new GsonBuilder();
|
||||
gson = builder.create();
|
||||
}
|
||||
}
|
||||
}
|
||||
return gson;
|
||||
}
|
||||
|
||||
public static String jsonFromObject( Object object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
return getGson().toJson(object);
|
||||
} catch ( Exception var2) {
|
||||
var2.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T objectFromJson( String json, Class<T> klass) {
|
||||
if (json == null) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
return getGson().fromJson(json, klass);
|
||||
} catch ( Exception var3) {
|
||||
var3.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static <T> List<T> arrayFromJson( String json, Class<T> clazz) {
|
||||
List<T> list = new ArrayList<T>();
|
||||
if ( TextUtils.isEmpty(json)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
org.json.JSONArray array = new org.json.JSONArray(json);
|
||||
for (int i = 0; i < array.length(); i++) {
|
||||
JSONObject object = array.getJSONObject(i);
|
||||
String js = object.toString();
|
||||
T t = GsonUtil.objectFromJson(js, clazz);
|
||||
list.add(t);
|
||||
}
|
||||
return list;
|
||||
} catch ( Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
package com.mogo.utils.network.utils;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.NetworkInfo;
|
||||
import android.net.wifi.WifiInfo;
|
||||
import android.net.wifi.WifiManager;
|
||||
import android.os.Build;
|
||||
import android.telephony.PhoneStateListener;
|
||||
import android.telephony.SignalStrength;
|
||||
import android.telephony.TelephonyManager;
|
||||
import android.util.Log;
|
||||
|
||||
import com.mogo.utils.CommonUtils;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* @author liujing
|
||||
* @description 网络状态监听
|
||||
* @since: 7/29/21
|
||||
*/
|
||||
public class NetworkStatusUtil {
|
||||
|
||||
private static PhoneStatListener phoneStatListener;
|
||||
private static int mSignalStrength;
|
||||
private static SignalStrength signal;
|
||||
private static NetWorkStatus netWorkStatus1 = new NetWorkStatus();
|
||||
|
||||
/**
|
||||
* 监听网络强度
|
||||
*/
|
||||
public static NetWorkStatus networkState(Context context) {
|
||||
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
|
||||
String netWorkStatus = CommonUtils.getNetworkType(context);
|
||||
netWorkStatus1.status = netWorkStatus;
|
||||
if (info != null && info.isAvailable()) {
|
||||
netWorkStatus1.status = netWorkStatus;
|
||||
switch (info.getType()) {
|
||||
case ConnectivityManager.TYPE_WIFI:
|
||||
//wifi
|
||||
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
|
||||
WifiInfo connectionInfo = manager.getConnectionInfo();
|
||||
mSignalStrength = connectionInfo.getRssi();
|
||||
if (mSignalStrength > -90) {
|
||||
Log.e("CheckActivity", "getNetWorkInfo: 信号强度强");
|
||||
} else {
|
||||
Log.e("CheckActivity", "getNetWorkInfo: 信号强度弱");
|
||||
}
|
||||
netWorkStatus1.mSignalStrength = mSignalStrength;
|
||||
return netWorkStatus1;
|
||||
case ConnectivityManager.TYPE_MOBILE:
|
||||
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
if (telephonyManager == null) {
|
||||
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
}
|
||||
if (phoneStatListener == null) {
|
||||
phoneStatListener = new PhoneStatListener();
|
||||
}
|
||||
telephonyManager.listen(phoneStatListener, PhoneStatListener.LISTEN_SIGNAL_STRENGTHS);
|
||||
//移动网络,可以通过TelephonyManager来获取具体细化的网络类型
|
||||
if (netWorkStatus != "UNKNOWN") {
|
||||
try {
|
||||
if (signal == null) {
|
||||
Log.e("CheckActivity", "getNetWorkInfo: signal为空");
|
||||
break;
|
||||
}
|
||||
Method method = signal.getClass().getMethod("getDbm");
|
||||
mSignalStrength = (int) method.invoke(signal);
|
||||
} catch (NoSuchMethodException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvocationTargetException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
} else {
|
||||
if (signal == null) {
|
||||
break;
|
||||
}
|
||||
mSignalStrength = signal.getGsmSignalStrength();
|
||||
}
|
||||
netWorkStatus1.mSignalStrength = mSignalStrength;
|
||||
return netWorkStatus1;
|
||||
}
|
||||
} else {
|
||||
return netWorkStatus1;
|
||||
}
|
||||
return netWorkStatus1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听非WiFi网络信号强度变化
|
||||
*/
|
||||
static class PhoneStatListener extends PhoneStateListener {
|
||||
@Override
|
||||
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
|
||||
//获取信号强度变化
|
||||
super.onSignalStrengthsChanged(signalStrength);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
mSignalStrength = signalStrength.getLevel();
|
||||
return;
|
||||
}
|
||||
mSignalStrength = signalStrength.getGsmSignalStrength();
|
||||
}
|
||||
}
|
||||
|
||||
static public class NetWorkStatus implements Serializable {
|
||||
String status;
|
||||
int mSignalStrength;
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public int getSignalStrength() {
|
||||
return mSignalStrength;
|
||||
}
|
||||
|
||||
public void setSignalStrength(int signalStrength) {
|
||||
mSignalStrength = signalStrength;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
package com.mogo.utils.network.utils;
|
||||
|
||||
|
||||
import com.mogo.utils.digest.DigestUtils;
|
||||
import com.mogo.utils.network.HttpParams;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
|
||||
public class SignUtil {
|
||||
|
||||
private static class StrSortTreeMap extends TreeMap< String, Object > {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public StrSortTreeMap() {
|
||||
super(new Comparator< String >() {
|
||||
|
||||
public int compare( String str1, String str2) {
|
||||
return str1.compareTo(str2);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static String createSign( Map< String, Object > map, String key) {
|
||||
if (map == null || map.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
StrSortTreeMap treeMap = new StrSortTreeMap();
|
||||
for ( String k : map.keySet()) {
|
||||
treeMap.put(k, map.get(k));
|
||||
}
|
||||
return createSign(treeMap, key);
|
||||
}
|
||||
|
||||
private static String createSign( StrSortTreeMap map, String key) {
|
||||
try{
|
||||
StringBuilder queryString = new StringBuilder();
|
||||
for ( Map.Entry< String, Object > entry : map.entrySet()) {
|
||||
queryString.append(entry.getKey())
|
||||
.append("=")
|
||||
.append(entry.getValue())
|
||||
.append("&");
|
||||
}
|
||||
queryString.append("key=").append(DigestUtils.shaHex(key));
|
||||
return DigestUtils.shaHex(queryString.toString()).toUpperCase();
|
||||
}catch ( Exception e){
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static String encode( String string) {
|
||||
try {
|
||||
return URLEncoder.encode(string, "UTF-8");
|
||||
} catch ( UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
public static String decode( String string) {
|
||||
try {
|
||||
return URLDecoder.decode(string, "UTF-8");
|
||||
} catch ( UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成请求参数的签名
|
||||
*
|
||||
* @param params HTTP请求中的所有POST或GET参数的Key-Value集合
|
||||
* @return 签名字符串,用于赋值给sig参数
|
||||
*/
|
||||
public static String generateSignature( HttpParams params) {
|
||||
String paramString = params.getSortedParamsString();
|
||||
try {
|
||||
return DigestUtils.shaHex(paramString);
|
||||
} catch ( Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static String generateSignature( Map< String, String > params) {
|
||||
HttpParams httpParams = new HttpParams(params);
|
||||
return generateSignature(httpParams);
|
||||
}
|
||||
|
||||
public static Map< String, Object > convertToMap( JSONObject jsonObject) {
|
||||
final TreeMap< String, Object > sortedMap = new TreeMap< String, Object >();
|
||||
|
||||
if (jsonObject != null) {
|
||||
Iterator< String > keys = jsonObject.keys();
|
||||
while (keys.hasNext()) {
|
||||
String key = keys.next();
|
||||
Object value = jsonObject.opt(key);
|
||||
sortedMap.put(key,value);
|
||||
}
|
||||
}
|
||||
|
||||
return sortedMap;
|
||||
}
|
||||
|
||||
public static String signString( String value) {
|
||||
try {
|
||||
return DigestUtils.shaHex(value);
|
||||
} catch ( Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package com.mogo.utils.network.utils;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.Dialog;
|
||||
import android.app.Fragment;
|
||||
import android.content.Context;
|
||||
import android.content.ContextWrapper;
|
||||
import android.os.Build;
|
||||
import android.os.Looper;
|
||||
import android.view.View;
|
||||
import android.widget.PopupWindow;
|
||||
|
||||
import com.mogo.utils.network.CallerNotAliveException;
|
||||
|
||||
public class Util {
|
||||
|
||||
public static boolean checkAlive( Object caller ) {
|
||||
if ( caller instanceof Activity ) {
|
||||
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 ? !( ( Activity ) caller ).isDestroyed() : !( ( Activity ) caller ).isFinishing();
|
||||
} else if ( caller instanceof Fragment ) {
|
||||
return ( ( Fragment ) caller ).isAdded();
|
||||
} else if ( caller instanceof androidx.fragment.app.Fragment ) {
|
||||
return ( ( androidx.fragment.app.Fragment ) caller ).isAdded();
|
||||
} else if ( caller instanceof View ) {
|
||||
return true;
|
||||
} else if ( caller instanceof Dialog ) {
|
||||
return ( ( Dialog ) caller ).getWindow() != null;
|
||||
} else if ( caller instanceof PopupWindow ) {
|
||||
return ( ( PopupWindow ) caller ).getContentView() != null;
|
||||
}
|
||||
return caller != null;
|
||||
}
|
||||
|
||||
public static void assertCallerAlive( Object caller ) throws CallerNotAliveException {
|
||||
if ( !checkAlive( caller ) ) {
|
||||
throw new CallerNotAliveException( "Caller is not alive any more" );
|
||||
}
|
||||
}
|
||||
|
||||
public static Context getContext( Object object ) {
|
||||
if ( object instanceof Activity ) {
|
||||
return ( Activity ) object;
|
||||
} else if ( object instanceof Fragment ) {
|
||||
return ( ( Fragment ) object ).getActivity();
|
||||
} else if ( object instanceof androidx.fragment.app.Fragment ) {
|
||||
return ( ( androidx.fragment.app.Fragment ) object ).getActivity();
|
||||
} else if ( object instanceof View ) {
|
||||
return ( ( View ) object ).getContext();
|
||||
} else if ( object instanceof Dialog ) {
|
||||
return ( ( Dialog ) object ).getContext();
|
||||
} else if ( object instanceof PopupWindow ) {
|
||||
if ( ( ( PopupWindow ) object ).getContentView() != null )
|
||||
return ( ( PopupWindow ) object ).getContentView().getContext();
|
||||
else return null;
|
||||
} else if ( object instanceof ContextWrapper ) {
|
||||
return ( ( ContextWrapper ) object ).getBaseContext();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws an {@link IllegalArgumentException} if called on a thread other than the main
|
||||
* thread.
|
||||
*/
|
||||
public static void assertMainThread() {
|
||||
if ( !isOnMainThread() ) {
|
||||
throw new IllegalArgumentException( "You must call this method on the main thread" );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws an {@link IllegalArgumentException} if called on the main thread.
|
||||
*/
|
||||
public static void assertBackgroundThread() {
|
||||
if ( !isOnBackgroundThread() ) {
|
||||
throw new IllegalArgumentException( "You must call this method on a background thread" );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if called on the main thread, {@code false} otherwise.
|
||||
*/
|
||||
public static boolean isOnMainThread() {
|
||||
return Looper.myLooper() == Looper.getMainLooper();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if called on a background thread, {@code false} otherwise.
|
||||
*/
|
||||
public static boolean isOnBackgroundThread() {
|
||||
return !isOnMainThread();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user