Search in sources :

Example 46 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project webtools.sourceediting by eclipse.

the class AbstractResourceEncodingDetector method getAppropriateJavaCharset.

/**
 * This method can return null, if invalid charset name (in which case
 * "appropriateDefault" should be used, if a name is really need for some
 * "save anyway" cases).
 *
 * @param detectedCharsetName
 * @return
 */
private String getAppropriateJavaCharset(String detectedCharsetName) {
    String result = null;
    // 1. Check explicit mapping overrides from
    // property file -- its here we pick up "rules" for cases
    // that are not even in Java
    result = CodedIO.checkMappingOverrides(detectedCharsetName);
    // 2. Use the "canonical" name from JRE mappings
    // Note: see Charset JavaDoc, the name you get one
    // with can be alias,
    // the name you get back is "standard" name.
    Charset javaCharset = null;
    try {
        javaCharset = Charset.forName(detectedCharsetName);
    } catch (UnsupportedCharsetException e) {
        // overridden
        if (result != null && result.equals(detectedCharsetName)) {
            fEncodingMemento.setInvalidEncoding(detectedCharsetName);
        }
    } catch (IllegalCharsetNameException e) {
        // overridden
        if (result != null && result.equals(detectedCharsetName)) {
            fEncodingMemento.setInvalidEncoding(detectedCharsetName);
        }
    }
    // give priority to java cononical name, if present
    if (javaCharset != null) {
        result = javaCharset.name();
        // but still allow overrides
        result = CodedIO.checkMappingOverrides(result);
    }
    return result;
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Charset(java.nio.charset.Charset)

Example 47 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project webtools.sourceediting by eclipse.

the class CreateCodedReaderTester method testCreateAllFiles.

public void testCreateAllFiles() throws CoreException, IOException {
    if (RECREATE_FILES) {
        List allFiles = TestsPlugin.getAllTestFiles(TEST_FILE_DIR);
        URL outputDirURL = TestsPlugin.getInstallLocation();
        File zipoutFile = new File(outputDirURL.getPath(), TESTFILES_ZIPFILE_NAME);
        java.io.FileOutputStream zipOut = new FileOutputStream(zipoutFile);
        ZipOutputStream zipOutputStream = new ZipOutputStream(zipOut);
        int count = 1;
        for (Iterator iter = allFiles.iterator(); iter.hasNext(); ) {
            File file = (File) iter.next();
            createZipEntry(zipOutputStream, file);
            CodedReaderCreator codedReaderCreator = new CodedReaderCreator();
            codedReaderCreator.set(file.getName(), new FileInputStream(file));
            String detectedCharsetName = null;
            String javaCharsetName = null;
            String expectedException = null;
            try {
                // just used for debug info, but can throw exception
                javaCharsetName = codedReaderCreator.getEncodingMemento().getJavaCharsetName();
                detectedCharsetName = codedReaderCreator.getEncodingMemento().getDetectedCharsetName();
            } catch (UnsupportedCharsetExceptionWithDetail e) {
                // ignore for simply creating tests
                expectedException = e.getClass().getName() + ".class";
            } catch (MalformedInputException e) {
                // ignore for simply creating tests
                expectedException = e.getClass().getName() + ".class";
            } catch (IllegalCharsetNameException e) {
                // ignore for simply creating tests
                expectedException = e.getClass().getName() + ".class";
            }
            String subpath = getSubPathName(file);
            createTestMethodSource(count, subpath, detectedCharsetName, javaCharsetName, expectedException);
            count++;
        }
        zipOutputStream.close();
        zipOut.close();
        assertTrue(true);
    }
}
Also used : CodedReaderCreator(org.eclipse.wst.sse.core.internal.encoding.CodedReaderCreator) FileOutputStream(java.io.FileOutputStream) URL(java.net.URL) FileInputStream(java.io.FileInputStream) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) Iterator(java.util.Iterator) MalformedInputException(java.nio.charset.MalformedInputException) List(java.util.List) UnsupportedCharsetExceptionWithDetail(org.eclipse.wst.sse.core.internal.exceptions.UnsupportedCharsetExceptionWithDetail) File(java.io.File)

Example 48 with IllegalCharsetNameException

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

the class PMS method verifyPidName.

/*
	 * This method is only called for Windows OS'es, so specialized Windows charset handling is allowed
	 */
private static boolean verifyPidName(String pid) throws IOException, IllegalAccessException {
    if (!Platform.isWindows()) {
        throw new IllegalAccessException("verifyPidName can only be called from Windows!");
    }
    ProcessBuilder pb = new ProcessBuilder("tasklist", "/FI", "\"PID eq " + pid + "\"", "/V", "/NH", "/FO", "CSV");
    pb.redirectErrorStream(true);
    Process p = pb.start();
    String line;
    Charset charset = null;
    int codepage = WinUtils.getOEMCP();
    String[] aliases = { "cp" + codepage, "MS" + codepage };
    for (String alias : aliases) {
        try {
            charset = Charset.forName(alias);
            break;
        } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
            charset = null;
        }
    }
    if (charset == null) {
        charset = Charset.defaultCharset();
        LOGGER.warn("Couldn't find a supported charset for {}, using default ({})", aliases, charset);
    }
    try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream(), charset))) {
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            in.close();
            return false;
        }
        line = in.readLine();
    }
    if (line == null) {
        return false;
    }
    // remove all " and convert to common case before splitting result on ,
    String[] tmp = line.toLowerCase().replaceAll("\"", "").split(",");
    // if the line is too short we don't kill the process
    if (tmp.length < 9) {
        return false;
    }
    // check first and last, update since taskkill changed
    // also check 2nd last since we migh have ", POSSIBLY UNSTABLE" in there
    boolean ums = tmp[tmp.length - 1].contains("universal media server") || tmp[tmp.length - 2].contains("universal media server");
    return tmp[0].equals("javaw.exe") && ums;
}
Also used : Charset(java.nio.charset.Charset) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException)

Example 49 with IllegalCharsetNameException

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

the class FileUtil method getFileCharset.

/**
 * Detects charset/encoding for given file. Not 100% accurate for
 * non-Unicode files.
 *
 * @param file the file for which to detect charset/encoding
 * @return The detected <code>Charset</code> or <code>null</code> if not detected
 * @throws IOException
 */
public static Charset getFileCharset(File file) throws IOException {
    CharsetMatch match = getFileCharsetMatch(file);
    if (match != null) {
        try {
            if (Charset.isSupported(match.getName())) {
                LOGGER.debug("Detected charset \"{}\" in file {}", match.getName(), file.getAbsolutePath());
                return Charset.forName(match.getName());
            }
            LOGGER.debug("Detected charset \"{}\" in file {}, but cannot use it because it's not supported by the Java Virual Machine", match.getName(), file.getAbsolutePath());
            return null;
        } catch (IllegalCharsetNameException e) {
            LOGGER.debug("Illegal charset deteceted \"{}\" in file {}", match.getName(), file.getAbsolutePath());
        }
    }
    LOGGER.debug("Found no matching charset for file {}", file.getAbsolutePath());
    return null;
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) CharsetMatch(com.ibm.icu.text.CharsetMatch)

Example 50 with IllegalCharsetNameException

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

the class UrlEncoder method encode.

/**
 * @param unsafeInput
 *            string to encode
 * @param charsetName
 *            encoding to use
 * @return encoded string
 * @see java.net.URLEncoder#encode(String, String)
 */
public String encode(final String unsafeInput, final String charsetName) {
    final String s = unsafeInput.replace("\0", "NULL");
    StringBuilder out = new StringBuilder(s.length());
    Charset charset;
    CharArrayWriter charArrayWriter = new CharArrayWriter();
    Args.notNull(charsetName, "charsetName");
    try {
        charset = Charset.forName(charsetName);
    } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
        throw new RuntimeException(new UnsupportedEncodingException(charsetName));
    }
    for (int i = 0; i < s.length(); ) {
        int c = s.charAt(i);
        // System.out.println("Examining character: " + c);
        if (dontNeedEncoding.get(c)) {
            if (c == ' ') {
                c = '+';
            }
            // 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 = 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 = s.charAt(i))));
            charArrayWriter.flush();
            String str = new String(charArrayWriter.toCharArray());
            byte[] ba = str.getBytes(charset);
            for (byte b : ba) {
                out.append('%');
                char ch = Character.forDigit((b >> 4) & 0xF, 16);
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(b & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            charArrayWriter.reset();
        }
    }
    return out.toString();
}
Also used : Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CharArrayWriter(java.io.CharArrayWriter) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException)

Aggregations

IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)69 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)44 Charset (java.nio.charset.Charset)34 IOException (java.io.IOException)13 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 File (java.io.File)9 ByteBuffer (java.nio.ByteBuffer)7 ByteArrayInputStream (java.io.ByteArrayInputStream)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