Java Code Examples for java.nio.charset.UnsupportedCharsetException

The following examples show how to use java.nio.charset.UnsupportedCharsetException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: tracee   Source File: Utilities.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 2
@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;
}
 
Example 3
Source Project: p4ic4idea   Source File: CharsetConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 4
Source Project: saros   Source File: SharedResourcesManager.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
  }
}
 
Example 5
@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;
}
 
Example 6
Source Project: HeadsUp   Source File: FastXmlSerializer.java    License: GNU General Public License v2.0 6 votes vote down vote up
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));
    }
}
 
Example 7
Source Project: netbeans   Source File: BaseJspEditorSupport.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 8
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;
}
 
Example 9
Source Project: sql-layer   Source File: Encoders.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 10
Source Project: kafka-connect-fs   Source File: TextFileReaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
        }
    });
}
 
Example 11
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;
}
 
Example 12
Source Project: backlog4j   Source File: MimeHelper.java    License: MIT License 6 votes vote down vote up
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;
    }
}
 
Example 13
Source Project: datacollector   Source File: XmlParserConfig.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 14
Source Project: FoxTelem   Source File: StringUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Source Project: java-android-websocket-client   Source File: ContentType.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 16
@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");
    }
}
 
Example 17
Source Project: j2objc   Source File: ChannelsTest.java    License: Apache License 2.0 5 votes vote down vote up
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
    }
}
 
Example 18
Source Project: Asqatasun   Source File: CrawlUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source Project: jdk1.8-source-analysis   Source File: StringCoding.java    License: Apache License 2.0 5 votes vote down vote up
private static Charset lookupCharset(String csn) {
    if (Charset.isSupported(csn)) {
        try {
            return Charset.forName(csn);
        } catch (UnsupportedCharsetException x) {
            throw new Error(x);
        }
    }
    return null;
}
 
Example 20
Source Project: jdk1.8-source-analysis   Source File: PrintWriter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 21
Source Project: cs-actions   Source File: HttpResponseConsumer.java    License: Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 22
Source Project: lognavigator   Source File: BreadcrumbFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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));
		}
	}
	
}
 
Example 23
Source Project: DanDanPlayForAndroid   Source File: SubtitleParser.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 24
Source Project: openjdk-jdk8u-backup   Source File: Main.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Charset lookupCharset(String csName) {
    if (Charset.isSupported(csName)) {
       try {
            return Charset.forName(csName);
       } catch (UnsupportedCharsetException x) {
            throw new Error(x);
       }
    }
    return null;
}
 
Example 25
Source Project: openjdk-8   Source File: Formatter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 26
Source Project: james-project   Source File: SearchCommandParser.java    License: Apache License 2.0 5 votes vote down vote up
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");
    }
}
 
Example 27
Source Project: Bytecoder   Source File: DataFlavorUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 28
Source Project: CrossMobile   Source File: NSString.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 29
Source Project: openjdk-jdk9   Source File: PrintStream.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 30
Source Project: stratosphere   Source File: TextOutputFormat.java    License: Apache License 2.0 5 votes vote down vote up
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;
}