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

The following examples show how to use java.nio.charset.Charset#name() .
Example 1
Project: ph-commons   File: XMLCharsetDeterminatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAllCharsetsSingleQuotes ()
{
  for (final Charset c : XMLCharsetDeterminator.getAllSupportedCharsets ())
  {
    final ICommonsList <String> aNames = new CommonsArrayList <> (c.name ());
    aNames.addAll (c.aliases ());
    for (final String sAlias : aNames)
    {
      final String sXML = "<?xml version=\"1.0\" encoding='" + sAlias + "'?><!-- " + c.name () + " --><root />";
      if (false)
        LOGGER.info (sXML);
      final byte [] aBytes = sXML.getBytes (c);
      final Charset aDetermined = XMLCharsetDeterminator.determineXMLCharset (aBytes);
      assertEquals (c, aDetermined);
    }
  }
}
 
Example 2
private String getBodyAsString( Charset charset, ByteArrayOutputStream os )
{
    if ( os != null )
    {

        byte[] bytes = os.toByteArray();

        try
        {
            return new String( bytes, charset.name() );
        }
        catch ( UnsupportedEncodingException ex )
        {
           log.error("Exception occurred while trying to convert ByteArray to String. ", ex );
        }
    }

    return null;
}
 
Example 3
Project: p4ic4idea   File: ClientSystemFileCommands.java    License: Apache License 2.0 6 votes vote down vote up
public Map<String, Object> convertFileDataMap(Map<String, Object> map, Charset charset, boolean isUnicodeServer) {

		if (map != null) {
			String dataString = null;
			byte[] dataBytes = null;

			try {
				dataBytes = (byte[]) map.get(RpcFunctionMapKey.DATA);
			} catch (Throwable thr) {
				Log.exception(thr);
			}

			if (dataBytes != null) {
				try {
					dataString = new String(dataBytes, charset == null ?
							RpcConnection.NON_UNICODE_SERVER_CHARSET_NAME :
							(isUnicodeServer ? CharsetDefs.UTF8_NAME : charset.name()));
					map.put(RpcFunctionMapKey.DATA, dataString);
				} catch (UnsupportedEncodingException e) {
					Log.exception(e);
				}
			}
		}

		return map;
	}
 
Example 4
Project: citygml4j   File: SAXWriter.java    License: Apache License 2.0 6 votes vote down vote up
public void setOutput(Writer writer) {
	this.writer = writer;

	if (writer instanceof OutputStreamWriter) {
		this.writer = new BufferedWriter(writer);
		String encoding = ((OutputStreamWriter) writer).getEncoding();

		if (encoding != null) {
			Charset charset = Charset.forName(encoding);
			streamEncoding = charset.name();
			writeEncoding = true;

			if (!streamEncoding.equalsIgnoreCase("utf-8"))
				charsetEncoder = charset.newEncoder();
		}
	}
}
 
Example 5
Project: p4ic4idea   File: ClientSystemFileCommands.java    License: Apache License 2.0 6 votes vote down vote up
public Map<String, Object> convertFileDataMap(Map<String, Object> map, Charset charset, boolean isUnicodeServer) {

		if (map != null) {
			String dataString = null;
			byte[] dataBytes = null;

			try {
				dataBytes = (byte[]) map.get(RpcFunctionMapKey.DATA);
			} catch (Throwable thr) {
				Log.exception(thr);
			}

			if (dataBytes != null) {
				try {
					dataString = new String(dataBytes, charset == null ?
							RpcConnection.NON_UNICODE_SERVER_CHARSET_NAME :
							(isUnicodeServer ? CharsetDefs.UTF8_NAME : charset.name()));
					map.put(RpcFunctionMapKey.DATA, dataString);
				} catch (UnsupportedEncodingException e) {
					Log.exception(e);
				}
			}
		}

		return map;
	}
 
Example 6
Project: openjdk-jdk8u-backup   File: Encodings.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the EncodingInfo object for the specified
 * encoding.
 * <p>
 * This is not a public API.
 *
 * @param encoding The encoding
 * @return The object that is used to determine if
 * characters are in the given encoding.
 * @xsl.usage internal
 */
static EncodingInfo getEncodingInfo(String encoding)
{
    EncodingInfo ei;

    String normalizedEncoding = toUpperCaseFast(encoding);
    ei = _encodingInfos.findEncoding(normalizedEncoding);
    if (ei == null) {
        // We shouldn't have to do this, but just in case.
        try {
            // This may happen if the caller tries to use
            // an encoding that wasn't registered in the
            // (java name)->(preferred mime name) mapping file.
            // In that case we attempt to load the charset for the
            // given encoding, and if that succeeds - we create a new
            // EncodingInfo instance - assuming the canonical name
            // of the charset can be used as the mime name.
            final Charset c = Charset.forName(encoding);
            final String name = c.name();
            ei = new EncodingInfo(name, name);
            _encodingInfos.putEncoding(normalizedEncoding, ei);
        } catch (IllegalCharsetNameException | UnsupportedCharsetException x) {
            ei = new EncodingInfo(null,null);
        }
    }

    return ei;
}
 
Example 7
Project: editorconfig-netbeans   File: FileInfoReader.java    License: MIT License 5 votes vote down vote up
public static MappedCharset readCharset(FileObject fo) {
  MappedCharset mappedCharset;

  Object charsetName = fo.getAttribute(ENCODING_SETTING);

  if (charsetName != null) {
    mappedCharset = new MappedCharset(charsetName.toString());
  } else {
    Charset charset = guessCharset(fo);
    mappedCharset = new MappedCharset(charset.name());
  }

  return mappedCharset;
}
 
Example 8
Project: netbeans   File: CustomizerSources.java    License: Apache License 2.0 5 votes vote down vote up
private void handleEncodingChange() {
    Charset enc = (Charset) encoding.getSelectedItem();
    String encName;
    if (enc != null) {
        encName = enc.name();
    } else {
        encName = originalEncoding;
    }
    if (!notified && encName != null && !encName.equals(originalEncoding)) {
        DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                NbBundle.getMessage(CustomizerSources.class, "MSG_EncodingWarning"), NotifyDescriptor.WARNING_MESSAGE));
        notified = true;
    }
    this.uiProperties.putAdditionalProperty(EjbJarProjectProperties.SOURCE_ENCODING, encName);
}
 
Example 9
Project: lams   File: CommonsFileUploadSupport.java    License: GNU General Public License v2.0 5 votes vote down vote up
private String determineEncoding(String contentTypeHeader, String defaultEncoding) {
	if (!StringUtils.hasText(contentTypeHeader)) {
		return defaultEncoding;
	}
	MediaType contentType = MediaType.parseMediaType(contentTypeHeader);
	Charset charset = contentType.getCharset();
	return (charset != null ? charset.name() : defaultEncoding);
}
 
Example 10
Project: netbeans   File: AbstractNativeProcess.java    License: Apache License 2.0 5 votes vote down vote up
String getCharset() {
    Charset charset = info.getCharset();
    if (charset != null) {
        return charset.name();
    }
    return null;
}
 
Example 11
Project: TencentKona-8   File: FontDescriptor.java    License: GNU General Public License v2.0 5 votes vote down vote up
public FontDescriptor(String nativeName, CharsetEncoder encoder,
                      int[] exclusionRanges){

    this.nativeName = nativeName;
    this.encoder = encoder;
    this.exclusionRanges = exclusionRanges;
    this.useUnicode = false;
    Charset cs = encoder.charset();
    if (cs instanceof HistoricallyNamedCharset)
        this.charsetName = ((HistoricallyNamedCharset)cs).historicalName();
    else
        this.charsetName = cs.name();

}
 
Example 12
Project: spring4-understanding   File: HttpStatusCodeException.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new instance of {@code HttpStatusCodeException} based on an
 * {@link HttpStatus}, status text, and response body content.
 * @param statusCode the status code
 * @param statusText the status text
 * @param responseHeaders the response headers, may be {@code null}
 * @param responseBody the response body content, may be {@code null}
 * @param responseCharset the response body charset, may be {@code null}
 * @since 3.1.2
 */
protected HttpStatusCodeException(HttpStatus statusCode, String statusText,
		HttpHeaders responseHeaders, byte[] responseBody, Charset responseCharset) {

	super(statusCode.value() + " " + statusText);
	this.statusCode = statusCode;
	this.statusText = statusText;
	this.responseHeaders = responseHeaders;
	this.responseBody = responseBody != null ? responseBody : new byte[0];
	this.responseCharset = responseCharset != null ? responseCharset.name() : DEFAULT_CHARSET;
}
 
Example 13
Project: consulo   File: LoadTextUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * should be {@code this.name().contains(CharsetToolkit.UTF8)} for {@link #getOverriddenCharsetByBOM(byte[], Charset)} to work
 */
SevenBitCharset(Charset baseCharset) {
  super("IJ__7BIT_" + baseCharset.name(), ArrayUtilRt.EMPTY_STRING_ARRAY);
  myBaseCharset = baseCharset;
}
 
Example 14
Project: arctic-sea   File: Format.java    License: Apache License 2.0 4 votes vote down vote up
public Format(String mimeType, Charset encoding) {
    this(mimeType, encoding == null ? null : encoding.name(), null);
}
 
Example 15
Project: consulo   File: FileEncodingConfigurable.java    License: Apache License 2.0 4 votes vote down vote up
@Nonnull // charset name or empty for System Default
private static String getSelectedCharsetName(@Nonnull Ref<Charset> selectedCharset) {
  Charset charset = selectedCharset.get();
  return charset == null ? "" : charset.name();
}
 
Example 16
Project: codebuff   File: Funnels.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
SerializedForm(Charset charset) {
  this.charsetCanonicalName = charset.name();
}
 
Example 17
Project: p4ic4idea   File: AddEditAction.java    License: Apache License 2.0 4 votes vote down vote up
public AddEditAction(@NotNull FilePath file, @Nullable P4FileType type,
        @Nullable P4ChangelistId changelistId, @Nullable Charset charset) {
    this(file, type, changelistId, charset == null ? null : charset.name());
}
 
Example 18
Project: AndServer   File: StandardMultipartResolver.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Determine the encoding for the given request.
 *
 * <p>The default implementation checks the request encoding, falling back to the default encoding specified for
 * this resolver.
 *
 * @param request current request
 *
 * @return the encoding for the request .
 */
@NonNull
private String determineEncoding(HttpRequest request) {
    MediaType mimeType = request.getContentType();
    if (mimeType == null) {
        return Charsets.UTF_8.name();
    }
    Charset charset = mimeType.getCharset();
    return charset == null ? Charsets.UTF_8.name() : charset.name();
}
 
Example 19
Project: metadata-extractor   File: RandomAccessReader.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Creates a String from the _data buffer starting at the specified index,
 * and ending where <code>byte=='\0'</code> or where <code>length==maxLength</code>.
 *
 * @param index          The index within the buffer at which to start reading the string.
 * @param maxLengthBytes The maximum number of bytes to read.  If a zero-byte is not reached within this limit,
 *                       reading will stop and the string will be truncated to this length.
 * @return The read string.
 * @throws IOException The buffer does not contain enough bytes to satisfy this request.
 */
@NotNull
public String getNullTerminatedString(int index, int maxLengthBytes, @NotNull Charset charset) throws IOException
{
    return new String(getNullTerminatedBytes(index, maxLengthBytes), charset.name());
}
 
Example 20
Project: coming   File: Closure_56_SourceFile_s.java    License: MIT License 2 votes vote down vote up
/**
 * Store the Charset specification as the string version of the name,
 * rather than the Charset itself.  This allows us to serialize the
 * SourceFile class.
 * @param c charset to use when reading the input.
 */
public void setCharset(Charset c) {
  inputCharset = c.name();
}