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

The following examples show how to use java.nio.charset.Charset#name() . 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: DefaultMetadataVersionService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 2
Source File: ClientSystemFileCommands.java    From p4ic4idea with 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 3
Source File: SAXWriter.java    From citygml4j with 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 4
Source File: ClientSystemFileCommands.java    From p4ic4idea with 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 5
Source File: XMLCharsetDeterminatorTest.java    From ph-commons with 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 6
Source File: Encodings.java    From openjdk-jdk8u-backup with 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
Source File: FileInfoReader.java    From editorconfig-netbeans with 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
Source File: HttpStatusCodeException.java    From spring4-understanding with 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 9
Source File: CustomizerSources.java    From netbeans with 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 10
Source File: FontDescriptor.java    From TencentKona-8 with 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 11
Source File: CommonsFileUploadSupport.java    From lams with 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 12
Source File: AbstractNativeProcess.java    From netbeans with 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 13
Source File: FileEncodingConfigurable.java    From consulo with 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 14
Source File: AddEditAction.java    From p4ic4idea with 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 15
Source File: Funnels.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
SerializedForm(Charset charset) {
  this.charsetCanonicalName = charset.name();
}
 
Example 16
Source File: Format.java    From arctic-sea with 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 17
Source File: LoadTextUtil.java    From consulo with 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 18
Source File: StandardMultipartResolver.java    From AndServer with 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
Source File: Closure_56_SourceFile_s.java    From coming with 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();
}
 
Example 20
Source File: RandomAccessReader.java    From metadata-extractor with 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());
}