Search in sources :

Example 1 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project che by eclipse.

the class FileStoreTextFileBuffer method commitFileBufferContent.

/*
	 * @see org.eclipse.core.internal.filebuffers.FileBuffer#commitFileBufferContent(org.eclipse.core.runtime.IProgressMonitor, boolean)
	 */
protected void commitFileBufferContent(IProgressMonitor monitor, boolean overwrite) throws CoreException {
    //		if (!isSynchronized() && !overwrite)
    //			throw new CoreException(new Status(IStatus.WARNING, FileBuffersPlugin.PLUGIN_ID, IResourceStatus.OUT_OF_SYNC_LOCAL, FileBuffersMessages.FileBuffer_error_outOfSync, null));
    String encoding = computeEncoding();
    Charset charset;
    try {
        charset = Charset.forName(encoding);
    } catch (UnsupportedCharsetException ex) {
        String message = NLSUtility.format(FileBuffersMessages.ResourceTextFileBuffer_error_unsupported_encoding_message_arg, encoding);
        IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, message, ex);
        throw new CoreException(s);
    } catch (IllegalCharsetNameException ex) {
        String message = NLSUtility.format(FileBuffersMessages.ResourceTextFileBuffer_error_illegal_encoding_message_arg, encoding);
        IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, message, ex);
        throw new CoreException(s);
    }
    CharsetEncoder encoder = charset.newEncoder();
    encoder.onMalformedInput(CodingErrorAction.REPLACE);
    encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
    byte[] bytes;
    int bytesLength;
    try {
        ByteBuffer byteBuffer = encoder.encode(CharBuffer.wrap(fDocument.get()));
        bytesLength = byteBuffer.limit();
        if (byteBuffer.hasArray())
            bytes = byteBuffer.array();
        else {
            bytes = new byte[bytesLength];
            byteBuffer.get(bytes);
        }
    } catch (CharacterCodingException ex) {
        Assert.isTrue(ex instanceof UnmappableCharacterException);
        String message = NLSUtility.format(FileBuffersMessages.ResourceTextFileBuffer_error_charset_mapping_failed_message_arg, encoding);
        IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IFileBufferStatusCodes.CHARSET_MAPPING_FAILED, message, null);
        throw new CoreException(s);
    }
    IFileInfo fileInfo = fFileStore.fetchInfo();
    if (fileInfo != null && fileInfo.exists()) {
        if (!overwrite)
            checkSynchronizationState();
        InputStream stream = new ByteArrayInputStream(bytes, 0, bytesLength);
        /*
			 * XXX:
			 * This is a workaround for a corresponding bug in Java readers and writer,
			 * see http://developer.java.sun.com/developer/bugParade/bugs/4508058.html
			 */
        if (fHasBOM && CHARSET_UTF_8.equals(encoding))
            stream = new SequenceInputStream(new ByteArrayInputStream(IContentDescription.BOM_UTF_8), stream);
        // here the file synchronizer should actually be removed and afterwards added again. However,
        // we are already inside an operation, so the delta is sent AFTER we have added the listener
        setFileContents(stream, monitor);
        // set synchronization stamp to know whether the file synchronizer must become active
        fSynchronizationStamp = fFileStore.fetchInfo().getLastModified();
    //			if (fAnnotationModel instanceof IPersistableAnnotationModel) {
    //				IPersistableAnnotationModel persistableModel= (IPersistableAnnotationModel) fAnnotationModel;
    //				persistableModel.commit(fDocument);
    //			}
    } else {
        fFileStore.getParent().mkdir(EFS.NONE, null);
        OutputStream out = fFileStore.openOutputStream(EFS.NONE, null);
        try {
            /*
				 * XXX:
				 * This is a workaround for a corresponding bug in Java readers and writer,
				 * see http://developer.java.sun.com/developer/bugParade/bugs/4508058.html
				 */
            if (fHasBOM && CHARSET_UTF_8.equals(encoding))
                out.write(IContentDescription.BOM_UTF_8);
            out.write(bytes, 0, bytesLength);
            out.flush();
            out.close();
        } catch (IOException x) {
            IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, x.getLocalizedMessage(), x);
            throw new CoreException(s);
        } finally {
            try {
                out.close();
            } catch (IOException x) {
            }
        }
        // set synchronization stamp to know whether the file synchronizer must become active
        fSynchronizationStamp = fFileStore.fetchInfo().getLastModified();
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IStatus(org.eclipse.core.runtime.IStatus) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Charset(java.nio.charset.Charset) CharacterCodingException(java.nio.charset.CharacterCodingException) IOException(java.io.IOException) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) IFileInfo(org.eclipse.core.filesystem.IFileInfo) CoreException(org.eclipse.core.runtime.CoreException) SequenceInputStream(java.io.SequenceInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UnmappableCharacterException(java.nio.charset.UnmappableCharacterException)

Example 2 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project robovm by robovm.

the class IllegalCharsetNameExceptionTest method testConstructor.

public void testConstructor() {
    IllegalCharsetNameException ex = new IllegalCharsetNameException("impossible");
    assertTrue(ex instanceof IllegalArgumentException);
    assertNull(ex.getCause());
    assertEquals(ex.getCharsetName(), "impossible");
    assertTrue(ex.getMessage().indexOf("impossible") != -1);
    ex = new IllegalCharsetNameException("ascii");
    assertNull(ex.getCause());
    assertEquals(ex.getCharsetName(), "ascii");
    assertTrue(ex.getMessage().indexOf("ascii") != -1);
    ex = new IllegalCharsetNameException("");
    assertNull(ex.getCause());
    assertEquals(ex.getCharsetName(), "");
    ex.getMessage();
    ex = new IllegalCharsetNameException(null);
    assertNull(ex.getCause());
    assertNull(ex.getCharsetName());
    assertTrue(ex.getMessage().indexOf("null") != -1);
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException)

Example 3 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project jdk8u_jdk by JetBrains.

the class Main method initializeConverter.

private static void initializeConverter() throws UnsupportedEncodingException {
    Charset cs = null;
    try {
        cs = (encodingString == null) ? lookupCharset(defaultEncoding) : lookupCharset(encodingString);
        encoder = (cs != null) ? cs.newEncoder() : null;
    } catch (IllegalCharsetNameException e) {
        throw new Error(e);
    }
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) Charset(java.nio.charset.Charset)

Example 4 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project jdk8u_jdk by JetBrains.

the class URLEncoder method encode.

/**
     * Translates a string into {@code application/x-www-form-urlencoded}
     * format using a specific encoding scheme. This method uses the
     * supplied encoding scheme to obtain the bytes for unsafe
     * characters.
     * <p>
     * <em><strong>Note:</strong> The <a href=
     * "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
     * World Wide Web Consortium Recommendation</a> states that
     * UTF-8 should be used. Not doing so may introduce
     * incompatibilities.</em>
     *
     * @param   s   {@code String} to be translated.
     * @param   enc   The name of a supported
     *    <a href="../lang/package-summary.html#charenc">character
     *    encoding</a>.
     * @return  the translated {@code String}.
     * @exception  UnsupportedEncodingException
     *             If the named encoding is not supported
     * @see URLDecoder#decode(java.lang.String, java.lang.String)
     * @since 1.4
     */
public static String encode(String s, String enc) throws UnsupportedEncodingException {
    boolean needToChange = false;
    StringBuffer out = new StringBuffer(s.length());
    Charset charset;
    CharArrayWriter charArrayWriter = new CharArrayWriter();
    if (enc == null)
        throw new NullPointerException("charsetName");
    try {
        charset = Charset.forName(enc);
    } catch (IllegalCharsetNameException e) {
        throw new UnsupportedEncodingException(enc);
    } catch (UnsupportedCharsetException e) {
        throw new UnsupportedEncodingException(enc);
    }
    for (int i = 0; i < s.length(); ) {
        int c = (int) s.charAt(i);
        //System.out.println("Examining character: " + c);
        if (dontNeedEncoding.get(c)) {
            if (c == ' ') {
                c = '+';
                needToChange = true;
            }
            //System.out.println("Storing: " + c);
            out.append((char) c);
            i++;
        } else {
            // convert to external encoding before hex conversion
            do {
                charArrayWriter.write(c);
                /*
                     * If this character represents the start of a Unicode
                     * surrogate pair, then pass in two characters. It's not
                     * clear what should be done if a bytes reserved in the
                     * surrogate pairs range occurs outside of a legal
                     * surrogate pair. For now, just treat it as if it were
                     * any other character.
                     */
                if (c >= 0xD800 && c <= 0xDBFF) {
                    /*
                          System.out.println(Integer.toHexString(c)
                          + " is high surrogate");
                        */
                    if ((i + 1) < s.length()) {
                        int d = (int) s.charAt(i + 1);
                        /*
                              System.out.println("\tExamining "
                              + Integer.toHexString(d));
                            */
                        if (d >= 0xDC00 && d <= 0xDFFF) {
                            /*
                                  System.out.println("\t"
                                  + Integer.toHexString(d)
                                  + " is low surrogate");
                                */
                            charArrayWriter.write(d);
                            i++;
                        }
                    }
                }
                i++;
            } while (i < s.length() && !dontNeedEncoding.get((c = (int) s.charAt(i))));
            charArrayWriter.flush();
            String str = new String(charArrayWriter.toCharArray());
            byte[] ba = str.getBytes(charset);
            for (int j = 0; j < ba.length; j++) {
                out.append('%');
                char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(ba[j] & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            charArrayWriter.reset();
            needToChange = true;
        }
    }
    return (needToChange ? out.toString() : s);
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CharArrayWriter(java.io.CharArrayWriter)

Example 5 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project tika by apache.

the class CharsetUtils method forName.

/** Returns Charset impl, if one exists.  This method
     *  optionally uses ICU4J's CharsetICU.forNameICU,
     *  if it is found on the classpath, else only uses
     *  JDK's builtin Charset.forName. */
public static Charset forName(String name) {
    if (name == null) {
        throw new IllegalArgumentException();
    }
    // Get rid of cruft around names, like <>, trailing commas, etc.
    Matcher m = CHARSET_NAME_PATTERN.matcher(name);
    if (!m.matches()) {
        throw new IllegalCharsetNameException(name);
    }
    name = m.group(1);
    String lower = name.toLowerCase(Locale.ENGLISH);
    Charset charset = COMMON_CHARSETS.get(lower);
    if (charset != null) {
        return charset;
    } else if ("none".equals(lower) || "no".equals(lower)) {
        throw new IllegalCharsetNameException(name);
    } else {
        Matcher iso = ISO_NAME_PATTERN.matcher(lower);
        Matcher cp = CP_NAME_PATTERN.matcher(lower);
        Matcher win = WIN_NAME_PATTERN.matcher(lower);
        if (iso.matches()) {
            // Handle "iso 8859-x" error
            name = "iso-8859-" + iso.group(1);
            charset = COMMON_CHARSETS.get(name);
        } else if (cp.matches()) {
            // Handle "cp-xxx" error
            name = "cp" + cp.group(1);
            charset = COMMON_CHARSETS.get(name);
        } else if (win.matches()) {
            // Handle "winxxx" and "win-xxx" errors
            name = "windows-" + win.group(1);
            charset = COMMON_CHARSETS.get(name);
        }
        if (charset != null) {
            return charset;
        }
    }
    if (getCharsetICU != null) {
        try {
            Charset cs = (Charset) getCharsetICU.invoke(null, name);
            if (cs != null) {
                return cs;
            }
        } catch (Exception e) {
        // ignore
        }
    }
    return Charset.forName(name);
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) Matcher(java.util.regex.Matcher) Charset(java.nio.charset.Charset) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException)

Aggregations

IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)65 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)42 Charset (java.nio.charset.Charset)34 IOException (java.io.IOException)11 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 ByteBuffer (java.nio.ByteBuffer)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 File (java.io.File)6 InputStream (java.io.InputStream)6 CharacterCodingException (java.nio.charset.CharacterCodingException)6 CoreException (org.eclipse.core.runtime.CoreException)6 IStatus (org.eclipse.core.runtime.IStatus)6 Status (org.eclipse.core.runtime.Status)6 HistoricallyNamedCharset (sun.nio.cs.HistoricallyNamedCharset)6 CharsetEncoder (java.nio.charset.CharsetEncoder)5 UnmappableCharacterException (java.nio.charset.UnmappableCharacterException)5 SequenceInputStream (java.io.SequenceInputStream)4 XmlPullParserException (org.codehaus.plexus.util.xml.pull.XmlPullParserException)4 CharArrayWriter (java.io.CharArrayWriter)3 FileInputStream (java.io.FileInputStream)3