下面列出了java.nio.charset.Charset#displayName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Set the value of the {@linkplain #AUTHORIZATION Authorization} header to
* Basic Authentication based on the given username and password.
* @param username the username
* @param password the password
* @param charset the charset to use to convert the credentials into an octet
* sequence. Defaults to {@linkplain StandardCharsets#ISO_8859_1 ISO-8859-1}.
* @throws IllegalArgumentException if {@code username} or {@code password}
* contains characters that cannot be encoded to the given charset
* @since 5.1
* @see <a href="https://tools.ietf.org/html/rfc7617">RFC 7617</a>
*/
public void setBasicAuth(String username, String password, @Nullable Charset charset) {
Assert.notNull(username, "Username must not be null");
Assert.notNull(password, "Password must not be null");
if (charset == null) {
charset = StandardCharsets.ISO_8859_1;
}
CharsetEncoder encoder = charset.newEncoder();
if (!encoder.canEncode(username) || !encoder.canEncode(password)) {
throw new IllegalArgumentException(
"Username or password contains characters that cannot be encoded to " + charset.displayName());
}
String credentialsString = username + ":" + password;
byte[] encodedBytes = Base64.getEncoder().encode(credentialsString.getBytes(charset));
String encodedCredentials = new String(encodedBytes, charset);
set(AUTHORIZATION, "Basic " + encodedCredentials);
}
@Override
public Converter<ResponseBody, String> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return value -> {
if (!TextUtils.isEmpty(encode)) {
return new String((value.bytes()), encode);
}
String charsetStr;
MediaType mediaType = value.contentType();
byte[] responseBytes = value.bytes();
//根据http头判断
if (mediaType != null) {
Charset charset = mediaType.charset();
if (charset != null) {
charsetStr = charset.displayName();
if (!isEmpty(charsetStr)) {
return new String(responseBytes, Charset.forName(charsetStr));
}
}
}
//根据内容判断
charsetStr = EncodingDetect.getEncodeInHtml(responseBytes);
return new String(responseBytes, Charset.forName(charsetStr));
};
}
/**
* Set the value of the {@linkplain #AUTHORIZATION Authorization} header to
* Basic Authentication based on the given username and password.
* @param username the username
* @param password the password
* @param charset the charset to use to convert the credentials into an octet
* sequence. Defaults to {@linkplain StandardCharsets#ISO_8859_1 ISO-8859-1}.
* @throws IllegalArgumentException if {@code username} or {@code password}
* contains characters that cannot be encoded to the given charset
* @since 5.1
* @see <a href="https://tools.ietf.org/html/rfc7617">RFC 7617</a>
*/
public void setBasicAuth(String username, String password, @Nullable Charset charset) {
Assert.notNull(username, "Username must not be null");
Assert.notNull(password, "Password must not be null");
if (charset == null) {
charset = StandardCharsets.ISO_8859_1;
}
CharsetEncoder encoder = charset.newEncoder();
if (!encoder.canEncode(username) || !encoder.canEncode(password)) {
throw new IllegalArgumentException(
"Username or password contains characters that cannot be encoded to " + charset.displayName());
}
String credentialsString = username + ":" + password;
byte[] encodedBytes = Base64.getEncoder().encode(credentialsString.getBytes(charset));
String encodedCredentials = new String(encodedBytes, charset);
set(AUTHORIZATION, "Basic " + encodedCredentials);
}
@Override
public Converter<ResponseBody, String> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return value -> {
final byte[] responseBytes = value.bytes();
if (!TextUtils.isEmpty(encode)) {
return new String(responseBytes, encode);
}
String charsetStr = null;
MediaType mediaType = value.contentType();
//根据http头判断
if (mediaType != null) {
Charset charset = mediaType.charset();
if (charset != null) {
charsetStr = charset.displayName();
}
}
if (charsetStr == null) {
charsetStr = EncodingDetect.getHtmlEncode(responseBytes);
}
return new String(responseBytes, Charset.forName(charsetStr));
};
}
/**
* Decodes a byte sequence into a string, given a {@link Charset}.
* <p>
* This method is preferred to {@link Charset#decode(ByteBuffer)} and
* {@link String#String(byte[], Charset)} (<em>etc.</em>)
* since those methods will replace or ignore bad input, and here we throw
* an exception.
*
* @param bytes the data to decode.
*
* @return the decoded string, not null.
*
* @throws IonException if there's a {@link CharacterCodingException}.
*/
public static String decode(byte[] bytes, Charset charset)
{
CharsetDecoder decoder = charset.newDecoder();
try
{
CharBuffer buffer = decoder.decode(ByteBuffer.wrap(bytes));
return buffer.toString();
}
catch (CharacterCodingException e)
{
String message =
"Input is not valid " + charset.displayName() + " data";
throw new IonException(message, e);
}
}
/**
* Substitutes the code list by the adapter to be marshalled into an XML file
* or stream. JAXB calls automatically this method at marshalling time.
*
* @param value the code list value.
* @return the adapter for the given code list.
*/
@Override
public final MD_CharacterSetCode marshal(final Charset value) {
final Context context = Context.current();
final ValueConverter converter = Context.converter(context);
final String code = converter.toCharsetCode(context, value);
if (code != null) {
final Locale locale = context.getLocale();
final MD_CharacterSetCode c = new MD_CharacterSetCode();
c.identifier = new CodeListUID(context, "MD_CharacterSetCode", code,
(locale != null) ? converter.toLanguageCode(context, locale) : null,
(locale != null) ? value.displayName(locale) : value.displayName());
return c;
}
return null;
}
private String[] getCharsets() {
if ( charsets == null ) {
Collection<Charset> charsetCol = Charset.availableCharsets().values();
charsets = new String[ charsetCol.size() ];
int i = 0;
for ( Charset charset : charsetCol ) {
charsets[ i++ ] = charset.displayName();
}
}
return charsets;
}
/**
* Percent encodes entities as per https://tools.ietf.org/html/rfc3986
*
* @param str - string to encode
* @param charset - desired charset encoding
* @return The percent encoded string in specified charset encoding
*/
public static String percentEncode(String str, Charset charset) {
if (str == null || str.isEmpty()) {
return OAuth.EMPTY_STRING;
}
try {
return URLEncoder.encode(str, charset.name())
.replace("+", "%20")
.replace("*", "%2A")
.replace("%7E", "~");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Unable to decode URL using " + charset.displayName() + " encoding", e);
}
}
/**
* Handle an error thrown while file decoding. Inform search listener and
* append detailed info into the IDE Log.
*/
protected final void handleDecodingError(SearchListener listener,
FileObject file, CharsetDecoder decoder,
CharacterCodingException e) {
String charsetName;
try {
if (decoder.isAutoDetecting() && decoder.isCharsetDetected()) {
Charset c = decoder.detectedCharset();
if (c != null) {
charsetName = c.displayName();
} else {
charsetName = decoder.charset().displayName();
}
} else {
charsetName = decoder.charset().displayName();
}
} catch (Exception ex) {
LOG.log(Level.INFO, "Failed to obtain actual charset", ex); //NOI18N
charsetName = decoder == null ? "null" : decoder.toString();//NOI18N
}
String msg = NbBundle.getMessage(ResultView.class,
"TEXT_INFO_ERROR_ENCODING", charsetName); //NOI18N
listener.fileContentMatchingError(file.getPath(),
new Exception(msg, e));
LOG.log(Level.INFO, "{0}; UnmappableCharacterException: {1}", //NOI18N
new Object[]{file.getPath(), e.getMessage()});
}
@Override
public String[] availableCharsets() {
List<String> charsets = new Collection<String>();
for(Charset charset : Charset.availableCharsets().values()) {
final String name = charset.displayName();
if(!(name.startsWith("IBM") || ((name.startsWith("x-") && !name.startsWith("x-Mac"))))) {
charsets.add(name);
}
}
return charsets.toArray(new String[charsets.size()]);
}
public String getDefaultCharset() {
if (inputFile != null) {
final IProject project = inputFile.getProject();
try {
final Charset defautlCharset = Charset.forName(project.getDefaultCharset());
return defautlCharset.displayName();
} catch (final CoreException e) {}
}
return Charset.defaultCharset().displayName();
}
/**
* @return the full content-type containing the mime type and the charset if set.
*/
public String getFullContentType() {
if (getContentType() == null) {
// Will use the renderable content type.
return null;
}
Charset localCharset = getCharset();
if (localCharset == null || getContentType().contains("charset")) {
return getContentType();
} else {
return getContentType() + "; charset=" + localCharset.displayName();
}
}
@Nonnull
private static JComponent createCharsetPanel(@Nonnull Charset charset) {
JLabel label = new JLabel(charset.displayName());
// TODO: specific colors for other charsets
if (charset.equals(Charset.forName("UTF-8"))) {
label.setForeground(JBColor.BLUE);
}
else if (charset.equals(Charset.forName("ISO-8859-1"))) {
label.setForeground(JBColor.RED);
}
else {
label.setForeground(JBColor.BLACK);
}
return label;
}
public TextRecord(String text, Charset encoding, Locale locale) {
this.encoding = encoding;
this.text = text;
this.locale = locale;
if (!encoding.equals(UTF8) && !encoding.equals(UTF16)) {
throw new IllegalArgumentException("Expected UTF-8 or UTF-16 encoding, not " + encoding.displayName());
}
}
private String[] getCharsets() {
if ( charsets == null ) {
Collection<Charset> charsetCol = Charset.availableCharsets().values();
charsets = new String[charsetCol.size()];
int i = 0;
for ( Charset charset : charsetCol ) {
charsets[i++] = charset.displayName();
}
}
return charsets;
}
public static Map<String, String> readCsvFile(File selectedFile, String separatorString) {
if (selectedFile.isDirectory()) {
return Collections.emptyMap();
}
try {
Charset encoding = new SmartEncodingInputStream(new FileInputStream(selectedFile)).getEncoding();
BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(selectedFile), encoding.displayName()));
Map<String, String> title2contents = new LinkedHashMap<String, String>();
String line;
while ((line = fileReader.readLine()) != null) {
String[] splitLine = line.split(separatorString);
if (splitLine.length < 2)
continue;
String title = splitLine[0].trim();
String content = splitLine[1].trim();
if (title.length() > 0 && content.length() > 0) {
// fix initial and final " if space separator has been used
if (separatorString.equals(ImpSeparatorPanel.SPACE_SEPARATOR)) {
title = title.replace("\"", "");
content = content.replace("\"", "");
}
// make sure that the card set does not already contains the key
while (title2contents.containsKey(title))
title = title + " ";
title2contents.put(title, content);
}
}
fileReader.close();
return title2contents;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/** Create a mapping for a charset
*
* @param c The charset for this mapping
*/
public CharsetMapping(final Charset c) {
this(c, c.displayName(), true);
}
/** Create a mapping for a charset with the obtion to turn on or off display
* of aliases next to the the charset canonical name.
*
* @param c The charset for this mapping
* @param sa
*/
public CharsetMapping(final Charset c, boolean sa) {
this(c, c.displayName(), sa);
}