Java Code Examples for java.nio.charset.Charset#isSupported()

The following examples show how to use java.nio.charset.Charset#isSupported() . 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: ripple-lib-java   File: LocalizedMessage.java    License: ISC License 6 votes vote down vote up
/**
 * Constructs a new LocalizedMessage using <code>resource</code> as the base name for the 
 * RessourceBundle and <code>id</code> as the message bundle id the resource file. 
 * @param resource base name of the resource file 
 * @param id the id of the corresponding bundle in the resource file
 * @param encoding the encoding of the resource file
 * @throws NullPointerException if <code>resource</code> or <code>id</code> is <code>null</code>
 * @throws UnsupportedEncodingException if the encoding is not supported
 */
public LocalizedMessage(String resource,String id, String encoding) throws NullPointerException, UnsupportedEncodingException
{
    if (resource == null || id == null)
    {
        throw new NullPointerException();
    }
    this.id = id;
    this.resource = resource;
    arguments = new FilteredArguments();
    if (!Charset.isSupported(encoding))
    {
        throw new UnsupportedEncodingException("The encoding \"" + encoding + "\" is not supported.");
    }
    this.encoding = encoding;
}
 
Example 2
private String createEncoding(String encoding)
		throws MojoExecutionException {
	if (encoding == null) {
		return null;
	}
	try {
		if (!Charset.isSupported(encoding)) {
			throw new MojoExecutionException(MessageFormat.format(
					"Unsupported encoding [{0}].", encoding));
		}
		return encoding;
	} catch (IllegalCharsetNameException icne) {
		throw new MojoExecutionException(MessageFormat.format(
				"Unsupported encoding [{0}].", encoding));
	}

}
 
Example 3
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    super.init(filterConfig);
    if (encoding == null || encoding.length() == 0 ||
            encoding.equalsIgnoreCase("default")) {
        encoding = DEFAULT_ENCODING;
    } else if (encoding.equalsIgnoreCase("system")) {
        encoding = Charset.defaultCharset().name();
    } else if (!Charset.isSupported(encoding)) {
        throw new IllegalArgumentException(sm.getString(
                "addDefaultCharset.unsupportedCharset", encoding));
    }
}
 
Example 4
Source Project: stratosphere   File: TextInputFormat.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void configure(Configuration parameters) {
	super.configure(parameters);
	
	if (charsetName == null || !Charset.isSupported(charsetName)) {
		throw new RuntimeException("Unsupported charset: " + charsetName);
	}
	this.charset = Charset.forName(charsetName);
}
 
Example 5
/**
 * Determines whether this JRE can both encode and decode text in the
 * specified encoding.
 */
public static boolean isEncodingSupported(String encoding) {
    if (encoding == null) {
        return false;
    }
    try {
        return Charset.isSupported(encoding);
    } catch (IllegalCharsetNameException icne) {
        return false;
    }
}
 
Example 6
Source Project: stratosphere   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;
}
 
Example 7
Source Project: rawhttp   File: MessageSender.java    License: Apache License 2.0 5 votes vote down vote up
private static RawHttpHeaders withPlainTextExtension(RawHttpHeaders extensions) {
    RawHttpHeaders result = extensions.and(PLAIN_TEXT_HEADER);
    Optional<String> charset = result.getFirst("Charset");
    if (!charset.isPresent() || !Charset.isSupported(charset.get())) {
        result = result.and(UTF8_HEADER);
    }
    return result;
}
 
Example 8
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 9
Source Project: astor   File: CharEncoding.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Returns whether the named charset is supported.</p>
 *
 * <p>This is similar to <a
 * href="http://download.oracle.com/javase/1.4.2/docs/api/java/nio/charset/Charset.html#isSupported%28java.lang.String%29">
 * java.nio.charset.Charset.isSupported(String)</a> but handles more formats</p>
 *
 * @param name  the name of the requested charset; may be either a canonical name or an alias, null returns false
 * @return {@code true} if the charset is available in the current Java virtual machine
 */
public static boolean isSupported(String name) {
    if (name == null) {
        return false;
    }
    try {
        return Charset.isSupported(name);
    } catch (IllegalCharsetNameException ex) {
        return false;
    }
}
 
Example 10
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 11
Source Project: sumk   File: AppInfo.java    License: Apache License 2.0 5 votes vote down vote up
public static Charset systemCharset() {

		String charsetName = info == null ? null : info.get("sumk.charset");
		if (StringUtil.isEmpty(charsetName) || charsetName.equalsIgnoreCase(UTF8.name())) {
			return UTF8;
		}
		if (!Charset.isSupported(charsetName)) {
			RawLog.error("sumk.conf", "charset '" + charsetName + "' is not supported");
			return UTF8;
		}
		return Charset.forName(charsetName);
	}
 
Example 12
Source Project: ldp4j   File: EndpointControllerUtils.java    License: Apache License 2.0 5 votes vote down vote up
static void populateResponseBody(ResponseBuilder builder, String entity, Variant variant, boolean includeEntity) {
	MediaType mediaType = variant.getMediaType();

	String charsetName=mediaType.getParameters().get(MediaType.CHARSET_PARAMETER);
	Charset charset=StandardCharsets.UTF_8;
	if(charsetName!=null && !charsetName.isEmpty() && Charset.isSupported(charsetName)) {
		charset=Charset.forName(charsetName);
	} else {
		LOGGER.error("Missing of invalid charset information {}",mediaType);
		charsetName=charset.name();
	}

	MediaType target=
		Configuration.includeCharsetInformation()?
			mediaType.withCharset(charsetName):
			new MediaType(mediaType.getType(),mediaType.getSubtype());

	byte[] bytes = entity.getBytes(charset);
	builder.
		type(target).
		header(MoreHttp.CONTENT_LENGTH_HEADER,bytes.length);

	if(variant.getLanguage()!=null) {
		builder.language(variant.getLanguage());
	}

	if(includeEntity) {
		builder.entity(new ByteArrayInputStream(bytes));
	}
}
 
Example 13
Source Project: jdk8u-dev-jdk   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 14
Source Project: astor   File: DataUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static String validateCharset(String cs) {
    if (cs == null || cs.length() == 0) return null;
    cs = cs.trim().replaceAll("[\"']", "");
    try {
        if (Charset.isSupported(cs)) return cs;
        cs = cs.toUpperCase(Locale.ENGLISH);
        if (Charset.isSupported(cs)) return cs;
    } catch (IllegalCharsetNameException e) {
        // if our this charset matching fails.... we just take the default
    }
    return null;
}
 
Example 15
Source Project: hottub   File: Options.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses an option <code>args[i]</code> and return
 * the number of tokens consumed.
 *
 * @return
 *      0 if the argument is not understood. Returning 0
 *      will let the caller report an error.
 * @exception BadCommandLineException
 *      If the callee wants to provide a custom message for an error.
 */
protected int parseArguments(String[] args, int i) throws BadCommandLineException {
    if (args[i].equals("-g")) {
        debug = true;
        return 1;
    } else if (args[i].equals("-Xdebug")) {
        debugMode = true;
        return 1;
    } else if (args[i].equals("-Xendorsed")) {
        // this option is processed much earlier, so just ignore.
        return 1;
    } else if (args[i].equals("-verbose")) {
        verbose = true;
        return 1;
    } else if (args[i].equals("-quiet")) {
        quiet = true;
        return 1;
    } else if (args[i].equals("-keep")) {
        keep = true;
        return 1;
    }  else if (args[i].equals("-target")) {
        String token = requireArgument("-target", args, ++i);
        target = Target.parse(token);
        if(target == null)
            throw new BadCommandLineException(WscompileMessages.WSIMPORT_ILLEGAL_TARGET_VERSION(token));
        return 2;
    } else if (args[i].equals("-classpath") || args[i].equals("-cp")) {
        classpath = requireArgument("-classpath", args, ++i) + File.pathSeparator + System.getProperty("java.class.path");
        return 2;
    } else if (args[i].equals("-d")) {
        destDir = new File(requireArgument("-d", args, ++i));
        if (!destDir.exists())
            throw new BadCommandLineException(WscompileMessages.WSCOMPILE_NO_SUCH_DIRECTORY(destDir.getPath()));
        return 2;
    } else if (args[i].equals("-s")) {
        sourceDir = new File(requireArgument("-s", args, ++i));
        keep = true;
        if (!sourceDir.exists()) {
            throw new BadCommandLineException(WscompileMessages.WSCOMPILE_NO_SUCH_DIRECTORY(sourceDir.getPath()));
        }
        return 2;
    } else if (args[i].equals("-extension")) {
        compatibilityMode = EXTENSION;
        return 1;
    } else if (args[i].startsWith("-help")) {
        WeAreDone done = new WeAreDone();
        done.initOptions(this);
        throw done;
    } else if (args[i].equals("-Xnocompile")) {
        // -nocompile implies -keep. this is undocumented switch.
        nocompile = true;
        keep = true;
        return 1;
    } else if (args[i].equals("-encoding")) {
        encoding = requireArgument("-encoding", args, ++i);
        try {
            if (!Charset.isSupported(encoding)) {
                throw new BadCommandLineException(WscompileMessages.WSCOMPILE_UNSUPPORTED_ENCODING(encoding));
            }
        } catch (IllegalCharsetNameException icne) {
            throw new BadCommandLineException(WscompileMessages.WSCOMPILE_UNSUPPORTED_ENCODING(encoding));
        }
        return 2;
    } else if (args[i].equals("-disableXmlSecurity")) {
        disableXmlSecurity();
        return 1;
    } else if (args[i].startsWith("-J")) {
        if (javacOptions == null) {
            javacOptions = new ArrayList<String>();
        }
        javacOptions.add(args[i].substring(2));
        return 1;
    }
    return 0;
}
 
Example 16
Source Project: enkan   File: MultipartParser.java    License: Eclipse Public License 1.0 4 votes vote down vote up
private String getFilename(String head) {
    String filename = null;
    Matcher rfc2183Matcher = RFC2183.matcher(head);
    Matcher brokenQuotedMatcher = BROKEN_QUOTED.matcher(head);
    Matcher brokenUnQuotedMatcher = BROKEN_UNQUOTED.matcher(head);

    if (rfc2183Matcher.find()) {
        Map<String, String> params = new HashMap<>();
        Matcher disparmMatchr = DISPPARM.matcher(head);
        while (disparmMatchr.find()) {
            int cnt = disparmMatchr.groupCount();
            for (int i=1; i<cnt; i+=2) {
                if (disparmMatchr.group(i) != null) {
                    params.put(disparmMatchr.group(i), disparmMatchr.group(i + 1));
                }
            }
        }

        if (params.containsKey("filename")) {
            filename = params.get("filename").replaceAll("^\"(.*)\"$", "$1");
        } else if (params.containsKey("filename*")) {
            String[] tokens = params.get("filename*").split("'", 3);
            filename = tokens[2];
            if (Charset.isSupported(tokens[0])) {
                filename = CodecUtils.urlDecode(filename, tokens[0]);
            }
        }
    } else if (brokenQuotedMatcher.find()) {
        filename = brokenQuotedMatcher.group(1);
    } else if (brokenUnQuotedMatcher.find()) {
        filename = brokenUnQuotedMatcher.group(1);
    }

    if (filename == null) return null;

    filename = CodecUtils.urlDecode(filename);
    if (!filename.matches("\\[^\"]")) {
        filename = filename.replaceAll("\\\\(.)", "$1");
    }

    return filename;
}
 
Example 17
Source Project: jivejdon   File: TitleExtractor.java    License: Apache License 2.0 4 votes vote down vote up
private static Charset getCharset(ContentType contentType) {
	if (contentType != null && contentType.charsetName != null && Charset.isSupported(contentType.charsetName))
		return Charset.forName(contentType.charsetName);
	else
		return null;
}
 
Example 18
Source Project: p4ic4idea   File: PerforceCharsetsTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Test Perforce charsets cp1253, cp737, and iso8859-7.
 */
@Test
public void testPerforceCharsets() {

	// Printout the supported Perforce charsets
	String[] knownCharsets = PerforceCharsets.getKnownCharsets();
	StringBuffer badCharsets = new StringBuffer();
	
	for (int i=0; i<knownCharsets.length; i++ ) {
		String p4CharsetName = PerforceCharsets.getJavaCharsetName(knownCharsets[i]);
		System.out.println(knownCharsets[i] + "=" +	p4CharsetName);
		
		if (Charset.isSupported(p4CharsetName)) {
			Charset charset = Charset.forName(p4CharsetName);
			if (charset == null) {
				System.out.println("Cannot find charset: " + PerforceCharsets.getJavaCharsetName(knownCharsets[i]));
				badCharsets.append(p4CharsetName).append(",");
			} else {
				System.out.println("Java charset: " + charset.name());
			}
		} else {
			System.out.println("Charset not supported: " + p4CharsetName);
		}
	}
	if(badCharsets.length() > 0) {
	    fail("failed to load charsets: " + badCharsets.toString());
	}
	
	try {
		assertTrue(server.isConnected());
		assertTrue(server.supportsUnicode());
		// Set the Perforce charsets
		server.setCharsetName("cp1253");
		server.setCharsetName("cp737");
		server.setCharsetName("iso8859-7");
		server.setCharsetName("cp1250");
		server.setCharsetName("cp852");
		server.setCharsetName("iso8859-2");
	} catch (P4JavaException e) {
		fail("Unexpected exception: " + e.getLocalizedMessage());
	} finally {
		if (server != null) {
			this.endServerSession(server);
		}
		if (superserver != null) {
			this.endServerSession(superserver);
		}
	}
}
 
Example 19
public Connection.Request postDataCharset(String charset) {
    Validate.notNull(charset, "Charset must not be null");
    if (!Charset.isSupported(charset)) throw new IllegalCharsetNameException(charset);
    this.postDataCharset = charset;
    return this;
}
 
Example 20
/**
 * Parses an option {@code args[i]} and return
 * the number of tokens consumed.
 *
 * @return
 *      0 if the argument is not understood. Returning 0
 *      will let the caller report an error.
 * @exception BadCommandLineException
 *      If the callee wants to provide a custom message for an error.
 */
protected int parseArguments(String[] args, int i) throws BadCommandLineException {
    if (args[i].equals("-g")) {
        debug = true;
        return 1;
    } else if (args[i].equals("-Xdebug")) {
        debugMode = true;
        return 1;
    } else if (args[i].equals("-Xendorsed")) {
        // this option is processed much earlier, so just ignore.
        return 1;
    } else if (args[i].equals("-verbose")) {
        verbose = true;
        return 1;
    } else if (args[i].equals("-quiet")) {
        quiet = true;
        return 1;
    } else if (args[i].equals("-keep")) {
        keep = true;
        return 1;
    }  else if (args[i].equals("-target")) {
        String token = requireArgument("-target", args, ++i);
        target = Target.parse(token);
        if(target == null)
            throw new BadCommandLineException(WscompileMessages.WSIMPORT_ILLEGAL_TARGET_VERSION(token));
        return 2;
    } else if (args[i].equals("-classpath") || args[i].equals("-cp")) {
        classpath = requireArgument("-classpath", args, ++i) + File.pathSeparator + System.getProperty("java.class.path");
        return 2;
    } else if (args[i].equals("-d")) {
        destDir = new File(requireArgument("-d", args, ++i));
        if (!destDir.exists())
            throw new BadCommandLineException(WscompileMessages.WSCOMPILE_NO_SUCH_DIRECTORY(destDir.getPath()));
        return 2;
    } else if (args[i].equals("-s")) {
        sourceDir = new File(requireArgument("-s", args, ++i));
        keep = true;
        if (!sourceDir.exists()) {
            throw new BadCommandLineException(WscompileMessages.WSCOMPILE_NO_SUCH_DIRECTORY(sourceDir.getPath()));
        }
        return 2;
    } else if (args[i].equals("-extension")) {
        compatibilityMode = EXTENSION;
        return 1;
    } else if (args[i].startsWith("-help")) {
        WeAreDone done = new WeAreDone();
        done.initOptions(this);
        throw done;
    } else if (args[i].equals("-Xnocompile")) {
        // -nocompile implies -keep. this is undocumented switch.
        nocompile = true;
        keep = true;
        return 1;
    } else if (args[i].equals("-encoding")) {
        encoding = requireArgument("-encoding", args, ++i);
        try {
            if (!Charset.isSupported(encoding)) {
                throw new BadCommandLineException(WscompileMessages.WSCOMPILE_UNSUPPORTED_ENCODING(encoding));
            }
        } catch (IllegalCharsetNameException icne) {
            throw new BadCommandLineException(WscompileMessages.WSCOMPILE_UNSUPPORTED_ENCODING(encoding));
        }
        return 2;
    } else if (args[i].equals("-disableXmlSecurity")) {
        disableXmlSecurity();
        return 1;
    } else if (args[i].startsWith("-J")) {
        if (javacOptions == null) {
            javacOptions = new ArrayList<String>();
        }
        javacOptions.add(args[i].substring(2));
        return 1;
    }
    return 0;
}