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

The following examples show how to use java.nio.charset.Charset#displayName() . 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 File: EncodeConverter.java    From a with GNU General Public License v3.0 6 votes vote down vote up
@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));
    };
}
 
Example 2
Source File: HttpHeaders.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example 3
Source File: HttpHeaders.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
Source File: EncodeConverter.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
@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));
    };
}
 
Example 5
Source File: MD_CharacterSetCode.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: _Private_Utils.java    From ion-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 7
Source File: SelectValuesDialog.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: TextRecord.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
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());
	}
}
 
Example 9
Source File: DiffUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 10
Source File: Result.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * @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();
    }
}
 
Example 11
Source File: ERDiagramMultiPageEditor.java    From ermasterr with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 12
Source File: DefaultCharsetProvider.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@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()]);
}
 
Example 13
Source File: AbstractMatcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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()});
}
 
Example 14
Source File: Util.java    From oauth1-signer-java with MIT License 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 15
Source File: SelectValuesDialog.java    From hop with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 16
Source File: ImportManager.java    From opencards with BSD 2-Clause "Simplified" License 4 votes vote down vote up
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;
}
 
Example 17
Source File: CharsetMapping.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/** 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);
}
 
Example 18
Source File: CharsetMapping.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/** Create a mapping for a charset
 *
 * @param c The charset for this mapping
 */
public CharsetMapping(final Charset c) {
	this(c, c.displayName(), true);
}