下面列出了org.apache.http.client.entity.GzipDecompressingEntity#java.nio.charset.UnsupportedCharsetException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates a alphanumeric projection with a given length of the given object using its {@link Object#hashCode()}.
*/
public static String createAlphanumericHash(final String str, final int length) {
try {
final MessageDigest md = MessageDigest.getInstance("SHA-256");
final byte[] digest = md.digest(str.getBytes(CHARSET_UTF8));
// To human
final StringBuilder sb = new StringBuilder();
for (final byte b : digest) {
if (b < 16) sb.append("0");
sb.append(Integer.toHexString(b & 0xff));
}
// repeat if to small
while (sb.length() < length) {
sb.append(sb.toString());
}
// truncation and return
return sb.delete(length, sb.length()).toString();
} catch (NoSuchAlgorithmException | UnsupportedCharsetException e) {
// Hashalgo. and charset is mandatory for all kinds of JDK, so this should happend. But even when, we generate a random string.
return createRandomAlphanumeric(length);
}
}
@Override
public int writeHeader() throws IOException {
if (header == null && sHeader != null) {
try {
header = CloverBuffer.wrap(sHeader.getBytes(encoder.charset().name()));
} catch (UnsupportedEncodingException e) {
throw new UnsupportedCharsetException(encoder.charset().name());
}
}
if (header != null) {
dataBuffer.put(header);
header.rewind();
return header.remaining();
} else
return 0;
}
@Test(expected=FileDecoderException.class)
public void testCharsetConverterCharsetCharsetInvalid() throws IOException, UnsupportedCharsetException, ConnectionException, RequestException, AccessException, NoSuchObjectException, ConfigException, ResourceException, URISyntaxException, FileDecoderException, FileEncoderException {
File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/euc-jp.txt");
CharsetConverter convert = new CharsetConverter(PerforceCharsets.getP4Charset("shiftjis"), CharsetDefs.UTF8);
InputStream inStream = new FileInputStream(testResourceFile);
byte[] bytes = new byte[2048];
int read = inStream.read(bytes);
inStream.close();
byte[] trueIn = new byte[read];
System.arraycopy(bytes, 0, trueIn, 0, read);
ByteBuffer bufIn = ByteBuffer.wrap(bytes, 0, read);
convert.convert(bufIn);
}
private void handleFileActivity(@NotNull FileActivity activity)
throws IOException, IllegalCharsetNameException, UnsupportedCharsetException {
if (activity.isRecovery()) {
handleFileRecovery(activity);
return;
}
switch (activity.getType()) {
case CREATED:
handleFileCreation(activity);
break;
case REMOVED:
handleFileDeletion(activity);
break;
case MOVED:
handleFileMove(activity);
break;
default:
throw new UnsupportedOperationException(
"FileActivity type "
+ activity.getType()
+ " not supported. Dropped activity: "
+ activity);
}
}
@Override
protected Charset detectCharsetImpl(byte[] buffer) throws Exception
{
CharsetDetector detector = new CharsetDetector();
detector.setText(buffer);
CharsetMatch match = detector.detect();
if(match != null && match.getConfidence() > threshold)
{
try
{
return Charset.forName(match.getName());
}
catch(UnsupportedCharsetException e)
{
logger.info("Charset detected as " + match.getName() + " but the JVM does not support this, detection skipped");
}
}
return null;
}
public void setOutput(OutputStream os, String encoding) throws IOException,
IllegalArgumentException, IllegalStateException {
if (os == null)
throw new IllegalArgumentException();
if (true) {
try {
mCharset = Charset.forName(encoding).newEncoder();
} catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
throw (UnsupportedEncodingException) (new UnsupportedEncodingException(
encoding).initCause(e));
}
mOutputStream = os;
} else {
setOutput(
encoding == null
? new OutputStreamWriter(os)
: new OutputStreamWriter(os, encoding));
}
}
@Override
protected void saveFromKitToStream(StyledDocument doc, EditorKit kit, OutputStream stream) throws IOException, BadLocationException {
Parameters.notNull("doc", doc);
Parameters.notNull("kit", kit);
String foundEncoding = (String) doc.getProperty(DOCUMENT_SAVE_ENCODING);
String encoding = foundEncoding != null ? foundEncoding : defaulEncoding;
Charset charset = Charset.forName("UTF-8"); //NOI18N
try {
charset = Charset.forName(encoding);
} catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
LOGGER.log(Level.INFO, "Illegal charset found: {0}, defaulted to UTF-8 as warned by dialog", encoding);
}
writeByteOrderMark(charset, stream);
super.saveFromKitToStream(doc, kit, stream);
}
public JavaCTBConverter(OSFCodeSetRegistry.Entry codeset,
int alignmentForEncoding) {
try {
ctb = cache.getCharToByteConverter(codeset.getName());
if (ctb == null) {
Charset tmpCharset = Charset.forName(codeset.getName());
ctb = tmpCharset.newEncoder();
cache.setConverter(codeset.getName(), ctb);
}
} catch(IllegalCharsetNameException icne) {
// This can only happen if one of our Entries has
// an invalid name.
throw wrapper.invalidCtbConverterName(icne,codeset.getName());
} catch(UnsupportedCharsetException ucne) {
// This can only happen if one of our Entries has
// an unsupported name.
throw wrapper.invalidCtbConverterName(ucne,codeset.getName());
}
this.codeset = codeset;
alignment = alignmentForEncoding;
}
/**
* Get the encoding for a character column.
*/
public static Encoding charEncoding(String charsetName) {
synchronized (charEncodingMap) {
Encoding encoding = charEncodingMap.get(charsetName);
if (encoding == null) {
try {
Charset charset = Charset.forName(charsetName);
if (charset.name().equals("UTF-8"))
encoding = UTF8Encoder.INSTANCE;
else if (charset.newEncoder().maxBytesPerChar() == 1.0)
encoding = SBCSEncoder.INSTANCE;
}
catch (IllegalCharsetNameException |
UnsupportedCharsetException |
UnsupportedOperationException ex) {
encoding = SBCSEncoder.INSTANCE;
}
if (encoding == null)
encoding = new SlowMBCSEncoder(charsetName);
charEncodingMap.put(charsetName, encoding);
}
return encoding;
}
}
@ParameterizedTest
@MethodSource("fileSystemConfigProvider")
public void invalidFileEncoding(ReaderFsTestConfig fsConfig) {
Map<String, Object> readerConfig = getReaderConfig();
readerConfig.put(TextFileReader.FILE_READER_TEXT_FIELD_NAME_VALUE, FIELD_NAME_VALUE);
readerConfig.put(TextFileReader.FILE_READER_TEXT_ENCODING, "invalid_charset");
readerConfig.put(TextFileReader.FILE_READER_TEXT_COMPRESSION_TYPE, COMPRESSION_TYPE_DEFAULT);
assertThrows(ConnectException.class, () -> getReader(fsConfig.getFs(), fsConfig.getDataFile(), readerConfig));
assertThrows(UnsupportedCharsetException.class, () -> {
try {
getReader(fsConfig.getFs(), fsConfig.getDataFile(), readerConfig);
} catch (Exception e) {
throw e.getCause();
}
});
}
public JavaCTBConverter(OSFCodeSetRegistry.Entry codeset,
int alignmentForEncoding) {
try {
ctb = cache.getCharToByteConverter(codeset.getName());
if (ctb == null) {
Charset tmpCharset = Charset.forName(codeset.getName());
ctb = tmpCharset.newEncoder();
cache.setConverter(codeset.getName(), ctb);
}
} catch(IllegalCharsetNameException icne) {
// This can only happen if one of our Entries has
// an invalid name.
throw wrapper.invalidCtbConverterName(icne,codeset.getName());
} catch(UnsupportedCharsetException ucne) {
// This can only happen if one of our Entries has
// an unsupported name.
throw wrapper.invalidCtbConverterName(ucne,codeset.getName());
}
this.codeset = codeset;
alignment = alignmentForEncoding;
}
protected static String decodeRFC2231value(String value) {
int q1 = value.indexOf('\'');
if (q1 == -1) {
// missing charset
return value;
}
String mimeCharset = value.substring(0, q1);
int q2 = value.indexOf('\'', q1 + 1);
if (q2 == -1) {
// missing language
return value;
}
byte[] bytes = fromHex(value.substring(q2 + 1));
try {
return new String(bytes, Charset.forName(mimeCharset));
} catch (UnsupportedCharsetException e) {
// incorrect encoding
return value;
}
}
public DataParserFactory getParserFactory(Stage.Context context) {
DataParserFactoryBuilder builder = new DataParserFactoryBuilder(context, DataFormat.XML.getParserFormat());
try {
builder.setCharset(Charset.forName(charset));
} catch (UnsupportedCharsetException ex) {
throw new RuntimeException("It should not happen: " + ex.toString(), ex);
}
builder.setRemoveCtrlChars(removeCtrlChars).setMaxDataLen(-1)
.setConfig(XmlDataParserFactory.RECORD_ELEMENT_KEY, xmlRecordElement)
.setConfig(XmlDataParserFactory.INCLUDE_FIELD_XPATH_ATTRIBUTES_KEY, includeFieldXpathAttributes)
.setConfig(XmlDataParserFactory.RECORD_ELEMENT_XPATH_NAMESPACES_KEY, xPathNamespaceContext)
.setConfig(XmlDataParserFactory.USE_FIELD_ATTRIBUTES, outputFieldAttributes);
return builder.build();
}
/**
* Returns the byte[] representation of subset of the given char[] using the given encoding.
*
* @param value
* chars
* @param offset
* offset
* @param length
* length
* @param encoding
* java encoding
* @return bytes
*/
public static byte[] getBytes(char[] value, int offset, int length, String encoding) {
Charset cs;
try {
if (encoding == null) {
cs = Charset.defaultCharset();
} else {
cs = Charset.forName(encoding);
}
} catch (UnsupportedCharsetException ex) {
throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("StringUtils.0", new Object[] { encoding }), ex);
}
ByteBuffer buf = cs.encode(CharBuffer.wrap(value, offset, length));
// can't simply .array() this to get the bytes especially with variable-length charsets the buffer is sometimes larger than the actual encoded data
int encodedLen = buf.limit();
byte[] asBytes = new byte[encodedLen];
buf.get(asBytes, 0, encodedLen);
return asBytes;
}
/**
* Extracts {@code Content-Type} value from {@link HttpEntity} exactly as
* specified by the {@code Content-Type} header of the entity. Returns {@code null}
* if not specified.
*
* @param entity HTTP entity
* @return content type
* @throws ParseException if the given text does not represent a valid
* {@code Content-Type} value.
* @throws UnsupportedCharsetException Thrown when the named charset is not available in
* this instance of the Java virtual machine
*/
public static ContentType get(
final HttpEntity entity) throws ParseException, UnsupportedCharsetException {
if (entity == null) {
return null;
}
final Header header = entity.getContentType();
if (header != null) {
final HeaderElement[] elements = header.getElements();
if (elements.length > 0) {
return create(elements[0], true);
}
}
return null;
}
@Override
public Contact doImport(String language, Document doc, String hcpId, List<String> protocolIds, List<String> formIds, String planOfActionId, Contact ctc, List<String> enckeys) throws IOException {
String text = decodeRawData(doc.decryptAttachment(enckeys));
if (text != null) {
Reader r = new StringReader(text);
List<LaboLine> lls = parseReportsAndLabs(language, protocolIds, r);
fillContactWithLines(ctc, lls, planOfActionId, hcpId, protocolIds, formIds);
return contactLogic.modifyContact(ctc);
} else {
throw new UnsupportedCharsetException("Charset could not be detected");
}
}
public void testnewWriterCharsetError() throws Exception {
this.fouts = new FileOutputStream(tmpFile);
WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
try {
Channels.newWriter(wbChannel, Charset.forName(BAD_CODE_SET)
.newEncoder(), -1);
fail();
} catch (UnsupportedCharsetException e) {
// correct
}
}
/**
* This methods tests if a charset is valid regarding the charset nio API.
* @param charset
* @return
*/
public static boolean isValidCharset(String charset) {
try {
Charset.forName(charset);
} catch (UnsupportedCharsetException e) {
return false;
}
return true;
}
private static Charset lookupCharset(String csn) {
if (Charset.isSupported(csn)) {
try {
return Charset.forName(csn);
} catch (UnsupportedCharsetException x) {
throw new Error(x);
}
}
return null;
}
/**
* Returns a charset object for the given charset name.
* @throws NullPointerException is csn is null
* @throws UnsupportedEncodingException if the charset is not supported
*/
private static Charset toCharset(String csn)
throws UnsupportedEncodingException
{
Objects.requireNonNull(csn, "charsetName");
try {
return Charset.forName(csn);
} catch (IllegalCharsetNameException|UnsupportedCharsetException unused) {
// UnsupportedEncodingException should be thrown
throw new UnsupportedEncodingException(csn);
}
}
protected void consumeResponseContent(Map<String, String> result) throws IOException {
if (StringUtils.isEmpty(destinationFile)) {
String document;
try {
document = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharacterSet);
} catch (UnsupportedCharsetException e) {
throw new IllegalArgumentException("Could not parse responseCharacterSet. " + e.getMessage(), e);
}
result.put(HttpClientService.RETURN_RESULT, document);
} else {
consumeToDestinationFile();
}
}
/**
* Split 'path' into path-elements and add each one to breadcrumbs list
* @param breadcrumbs
* @param path
* @param lastElementIsLink
*/
public static void addSubPath(List<Breadcrumb> breadcrumbs, String path, boolean lastElementIsLink) {
path = path.replace("//", "/");
String[] pathElements = path.split("/");
int currentSlashIndex = 0;
for (int i=0; i<pathElements.length; i++) {
String label = pathElements[i];
if (label.isEmpty()) {
continue;
}
if (!label.equals("*") && (lastElementIsLink || i < pathElements.length - 1)) {
try {
currentSlashIndex = path.indexOf('/', currentSlashIndex + 1);
String linkParam = (currentSlashIndex != -1) ? path.substring(0, currentSlashIndex) : path;
String link = FOLDER_VIEW_URL_PREFIX + URLEncoder.encode(linkParam, URL_ENCODING);
breadcrumbs.add(new Breadcrumb(label, link));
} catch (UnsupportedEncodingException e) {
throw new UnsupportedCharsetException(URL_ENCODING);
}
}
else {
breadcrumbs.add(new Breadcrumb(label));
}
}
}
public TimedTextObject parser() {
try {
if (!StringUtils.isEmpty(subtitlePath)) {
//解析字幕文件
File subtitleFile = new File(subtitlePath);
if (subtitleFile.exists()) {
//获取解析工具
TimedTextFileFormat format = SubtitleFormat.format(subtitlePath);
if (format != null) {
//获取字幕对象
TimedTextObject subtitleObj = format.parseFile(subtitleFile);
if (subtitleObj != null && subtitleObj.captions.size() > 0) {
return subtitleObj;
}else {
ToastUtils.showShort("解析字幕文件失败");
}
} else {
ToastUtils.showShort("字幕文件错误");
}
} else {
ToastUtils.showShort("字幕文件不存在");
}
} else {
ToastUtils.showShort("字幕文件地址错误:" + subtitlePath);
}
} catch (FatalParsingException | IOException e) {
e.printStackTrace();
ToastUtils.showShort("解析字幕文件失败");
} catch (UnsupportedCharsetException ex) {
ex.printStackTrace();
ToastUtils.showShort("解析编码格式失败");
}
return null;
}
private static Charset lookupCharset(String csName) {
if (Charset.isSupported(csName)) {
try {
return Charset.forName(csName);
} catch (UnsupportedCharsetException x) {
throw new Error(x);
}
}
return null;
}
/**
* Returns a charset object for the given charset name.
* @throws NullPointerException is csn is null
* @throws UnsupportedEncodingException if the charset is not supported
*/
private static Charset toCharset(String csn)
throws UnsupportedEncodingException
{
Objects.requireNonNull(csn, "charsetName");
try {
return Charset.forName(csn);
} catch (IllegalCharsetNameException|UnsupportedCharsetException unused) {
// UnsupportedEncodingException should be thrown
throw new UnsupportedEncodingException(csn);
}
}
private SearchKey c(ImapSession session, ImapRequestLineReader request, boolean isFirstToken, Charset charset) throws DecodingException, IllegalCharsetNameException, UnsupportedCharsetException {
final int next = consumeAndCap(request);
switch (next) {
case 'C':
return cc(request, charset);
case 'H':
return charset(session, request, isFirstToken);
default:
throw new DecodingException(HumanReadableText.ILLEGAL_ARGUMENTS, "Unknown search key");
}
}
/**
* Converts an arbitrary text encoding to its canonical name.
*/
public static String canonicalName(String encoding) {
if (encoding == null) {
return null;
}
try {
return Charset.forName(encoding).name();
} catch (IllegalCharsetNameException icne) {
return encoding;
} catch (UnsupportedCharsetException uce) {
return encoding;
}
}
/**
* Check whether a string can be converted to the specified encoding
*
* @param string the String to check if it can be converted
* @param NSStringEncoding the desired encoding
* @return true if the string can be converted
* @see NSStringEncoding
*/
@CMSelector(value = "- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding;", staticMapping = true)
public static boolean canBeConvertedToEncoding(String string, int NSStringEncoding) {
try {
return Charset.forName(convertIntToString(NSStringEncoding)).newEncoder().canEncode(string);
} catch (UnsupportedCharsetException e) {
return false;
}
}
/**
* Returns a charset object for the given charset name.
* @throws NullPointerException is csn is null
* @throws UnsupportedEncodingException if the charset is not supported
*/
private static Charset toCharset(String csn)
throws UnsupportedEncodingException
{
requireNonNull(csn, "charsetName");
try {
return Charset.forName(csn);
} catch (IllegalCharsetNameException|UnsupportedCharsetException unused) {
// UnsupportedEncodingException should be thrown
throw new UnsupportedEncodingException(csn);
}
}
public void setCharsetName(String charsetName) throws IllegalCharsetNameException, UnsupportedCharsetException {
if (charsetName == null) {
throw new NullPointerException();
}
if (!Charset.isSupported(charsetName)) {
throw new UnsupportedCharsetException("The charset " + charsetName + " is not supported.");
}
this.charsetName = charsetName;
}