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

The following are Jave code examples for showing how to use name() of the java.nio.charset.Charset class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: JpaControllerUtil.java   View Source Code Vote up 6 votes
/**
 * Get the encoding of the supplied project as a String (by performing a lookup and invoking Charset.name).
 * @param project The project
 * @param file A file in the project
 * @return The project encoding, or a suitable default if the project encoding cannot be determined. Never null
 */
public static String getProjectEncodingAsString(Project project, FileObject file) {
    Charset encoding = project.getLookup().lookup(FileEncodingQueryImplementation.class).getEncoding(file);
    if (encoding == null) {
        encoding = FileEncodingQuery.getDefaultEncoding();
        if (encoding == null) {
            return "UTF-8";
        }
        else {
            return encoding.name();
        }
    }
    else {
        return encoding.name();
    }
}
 
Example 2
Project: openjdk-jdk10   File: NIOJISAutoDetectTest.java   View Source Code Vote up 6 votes
private static String detectingCharset(byte[] bytes) throws Exception {
    //----------------------------------------------------------------
    // Test special public methods of CharsetDecoder while we're here
    //----------------------------------------------------------------
    CharsetDecoder cd = Charset.forName("JISAutodetect").newDecoder();
    check(cd.isAutoDetecting(), "isAutodecting()");
    check(! cd.isCharsetDetected(), "isCharsetDetected");
    cd.decode(ByteBuffer.wrap(new byte[] {(byte)'A'}));
    check(! cd.isCharsetDetected(), "isCharsetDetected");
    try {
        cd.detectedCharset();
        fail("no IllegalStateException");
    } catch (IllegalStateException e) {}
    cd.decode(ByteBuffer.wrap(bytes));
    check(cd.isCharsetDetected(), "isCharsetDetected");
    Charset cs = cd.detectedCharset();
    check(cs != null, "cs != null");
    check(! cs.newDecoder().isAutoDetecting(), "isAutodetecting()");
    return cs.name();
}
 
Example 3
Project: lams   File: HttpStatusCodeException.java   View Source Code Vote up 6 votes
/**
 * 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 4
Project: Elasticsearch   File: LocalRestRequest.java   View Source Code Vote up 6 votes
public void setContent(final String source, final ContentType contentType) throws UnsupportedCharsetException {
    Args.notNull(source, "Source string");
    Charset charset = contentType != null?contentType.getCharset():null;
    if(charset == null) {
        charset = HTTP.DEF_CONTENT_CHARSET;
    }

    try {
        this.content = new BytesArray(source.getBytes(charset.name()));
    } catch (UnsupportedEncodingException var) {
        throw new UnsupportedCharsetException(charset.name());
    }

    if(contentType != null) {
        addHeader("Content-Type", contentType.toString());
    }
}
 
Example 5
Project: FirefoxData-android   File: StringEntity.java   View Source Code Vote up 6 votes
/**
 * Creates a StringEntity with the specified content and content type.
 *
 * @param string content to be used. Not {@code null}.
 * @param contentType content type to be used. May be {@code null}, in which case the default
 *   MIME type {@link ContentType#TEXT_PLAIN} is assumed.
 *
 * @throws IllegalArgumentException if the string parameter is null
 * @throws UnsupportedCharsetException Thrown when the named charset is not available in
 * this instance of the Java virtual machine
 * @since 4.2
 */
public StringEntity(final String string, final ContentType contentType) throws UnsupportedCharsetException {
    super();
    Args.notNull(string, "Source string");
    Charset charset = contentType != null ? contentType.getCharset() : null;
    if (charset == null) {
        charset = HTTP.DEF_CONTENT_CHARSET;
    }
    try {
        this.content = string.getBytes(charset.name());
    } catch (final UnsupportedEncodingException ex) {
        // should never happen
        throw new UnsupportedCharsetException(charset.name());
    }
    if (contentType != null) {
        setContentType(contentType.toString());
    }
}
 
Example 6
Project: lams   File: UnknownHttpStatusCodeException.java   View Source Code Vote up 5 votes
/**
 * Construct a new instance of {@code HttpStatusCodeException} based on an
 * {@link HttpStatus}, status text, and response body content.
 * @param rawStatusCode the raw status code value
 * @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}
 */
public UnknownHttpStatusCodeException(int rawStatusCode, String statusText,
		HttpHeaders responseHeaders, byte[] responseBody, Charset responseCharset) {

	super("Unknown status code [" + String.valueOf(rawStatusCode) + "]" + " " + statusText);
	this.rawStatusCode = rawStatusCode;
	this.statusText = statusText;
	this.responseHeaders = responseHeaders;
	this.responseBody = responseBody != null ? responseBody : new byte[0];
	this.responseCharset = responseCharset != null ? responseCharset.name() : DEFAULT_CHARSET;
}
 
Example 7
Project: incubator-netbeans   File: ProjectTemplateAttributesProvider.java   View Source Code Vote up 5 votes
private static void ensureProjectAttrs(Map<String, Object> map, FileObject parent) {
    if (map.get(ATTR_LICENSE) == null) {
        map.put(ATTR_LICENSE, "default"); // NOI18N
    }
    if (map.get(ATTR_LICENSE_PATH) == null) {
        map.put(ATTR_LICENSE_PATH, "Templates/Licenses/license-" + map.get(ATTR_LICENSE).toString() + ".txt"); // NOI18N
    }
    String url = map.get(ATTR_LICENSE_PATH).toString();
    if (FileUtil.getConfigFile(url) == null) { //now we have filesystem based template for sure, convert to file:///path to have freemarker process it
        try {
            URI uri = URI.create(url);
            //freemarker.cache.TemplateCache.normalizeName appears to 
            // check for :// to skip processing the path
            map.put(ATTR_LICENSE_PATH, new URI("file", "", uri.getPath(), null).toString());
        } catch (Exception malformedURLException) {
        }
    } else {
        // now we have to assume we are dealing with the teplate from system filesystem.
        // in order to get through the freemarker, the path needs to "absolute" in freemarker terms - http://freemarker.sourceforge.net/docs/ref_directive_include.html
        // relative would mean relative to the template and we cannot be sure what the path from template to license template is..
        // it used to be, ../Licenses/ or ../../Licenses but can be anything similar, just based on where the template resides.
        map.put(ATTR_LICENSE_PATH, "/" + url);
        //appears to cover both the new and old default value of the include path
    }  
    if (map.get(ATTR_ENCODING) == null) {
        Charset charset = FileEncodingQuery.getEncoding(parent);
        String encoding = charset != null ? charset.name() : "UTF-8"; // NOI18N
        map.put(ATTR_ENCODING, encoding);
    }
}
 
Example 8
Project: incubator-netbeans   File: AbstractNativeProcess.java   View Source Code Vote up 5 votes
String getCharset() {
    Charset charset = info.getCharset();
    if (charset != null) {
        return charset.name();
    }
    return null;
}
 
Example 9
Project: jdk8u-jdk   File: FontDescriptor.java   View Source Code Vote up 5 votes
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 10
Project: openjdk-jdk10   File: XMLFormatter.java   View Source Code Vote up 5 votes
/**
 * Return the header string for a set of XML formatted records.
 *
 * @param   h  The target handler (can be null)
 * @return  a valid XML string
 */
@Override
public String getHead(Handler h) {
    StringBuilder sb = new StringBuilder();
    String encoding;
    sb.append("<?xml version=\"1.0\"");

    if (h != null) {
        encoding = h.getEncoding();
    } else {
        encoding = null;
    }

    if (encoding == null) {
        // Figure out the default encoding.
        encoding = java.nio.charset.Charset.defaultCharset().name();
    }
    // Try to map the encoding name to a canonical name.
    try {
        Charset cs = Charset.forName(encoding);
        encoding = cs.name();
    } catch (Exception ex) {
        // We hit problems finding a canonical name.
        // Just use the raw encoding name.
    }

    sb.append(" encoding=\"");
    sb.append(encoding);
    sb.append("\"");
    sb.append(" standalone=\"no\"?>\n");

    sb.append("<!DOCTYPE log SYSTEM \"logger.dtd\">\n");
    sb.append("<log>\n");
    return sb.toString();
}
 
Example 11
Project: alfresco-core   File: Convert.java   View Source Code Vote up 5 votes
private static byte[] convertTabs(byte[] bytes, Charset charset, int replaceTabs) throws Exception
{
    // The tab character
    char tab = '\t';
    char space = ' ';

    // The output
    StringBuilder sb = new StringBuilder(bytes.length);
    
    String charsetName = charset.name();
    // Using the charset, convert to a string
    String str = new String(bytes, charsetName);
    char[] chars = str.toCharArray();
    for (char c : chars)
    {
        if (c == tab)
        {
            // Replace the tab
            for (int i = 0; i < replaceTabs; i++)
            {
                sb.append(space);
            }
        }
        else
        {
            sb.append(c);
        }
    }
    // Done
    return sb.toString().getBytes(charsetName);
}
 
Example 12
Project: jach   File: ACHReader.java   View Source Code Vote up 5 votes
ACHDocument readDocument(InputStream is, Charset charset) {
    Scanner sc = new Scanner(is, charset.name());

    while (sc.hasNextLine()) {
        ++lineNumber;
        currentLine = sc.nextLine();
        validateString();

        ACHRecord record = readRecord(currentLine, findRecordType())
                .setLineNumber(lineNumber);

        if (record.is(FILE_HEADER)) {
            document.setFileHeader((FileHeader) record);
        } else if (record.is(FILE_CONTROL)) {
            document.setFileControl((FileControl) record);
            return returnDocument();
        } else if (record.is(BATCH_HEADER)) {
            currentBatch = new ACHBatch().setBatchHeader((BatchHeader) record);
            document.addBatch(currentBatch);
        } else if (record.is(BATCH_CONTROL)) {
            currentBatch.setBatchControl((BatchControl) record);
            currentBatch = null;
            currentDetail = null;
        } else if (record.is(ENTRY_DETAIL)) {
            currentDetail = new ACHBatchDetail()
                    .setDetailRecord((EntryDetail) record);
            currentBatch.addDetail(currentDetail);

        } else if (record.is(ADDENDA)) {
            currentDetail.addAddendaRecord((AddendaRecord) record);
        }
    }
    return returnDocument();
}
 
Example 13
Project: apache-tomcat-7.0.73-with-comment   File: TestB2CConverter.java   View Source Code Vote up 5 votes
@Test
public void testLeftoverSize() {
    float maxLeftover = 0;
    String charsetName = "UNSET";
    for (Charset charset : Charset.availableCharsets().values()) {
        float leftover;
        if (charset.name().toLowerCase(Locale.ENGLISH).startsWith("x-")) {
            // Non-standard charset that browsers won't be using
            // Likely something used internally by the JRE
            continue;
        }
        if (charset.name().equals("COMPOUND_TEXT")) {
            // Java for-internal-use-only charset
            // See:
            // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6392670
            // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6381697
            continue;
        }
        try {
            leftover = charset.newEncoder().maxBytesPerChar();
        } catch (UnsupportedOperationException uoe) {
            // Skip it
            continue;
        }
        if (leftover > maxLeftover) {
            maxLeftover = leftover;
            charsetName = charset.name();
        }
    }
    Assert.assertTrue("Limit needs to be at least " + maxLeftover +
            " (used in charset '" + charsetName + "')",
            maxLeftover <= B2CConverter.LEFTOVER_SIZE);
}
 
Example 14
Project: googles-monorepo-demo   File: Funnels.java   View Source Code Vote up 4 votes
SerializedForm(Charset charset) {
  this.charsetCanonicalName = charset.name();
}
 
Example 15
Project: rs-aggregator   File: AbstractUriReader.java   View Source Code Vote up 4 votes
public static String getCharset(HttpResponse response) {
  ContentType contentType = ContentType.getOrDefault(response.getEntity());
  Charset charset = contentType.getCharset();
  return charset == null ? "UTF-8" : charset.name();
}
 
Example 16
Project: lams   File: CharsetEditor.java   View Source Code Vote up 4 votes
@Override
public String getAsText() {
	Charset value = (Charset) getValue();
	return (value != null ? value.name() : "");
}
 
Example 17
Project: FireFiles   File: Strings.java   View Source Code Vote up 3 votes
/**
 * Converts the byte array to a string using the given charset.
 *
 * <p>The behavior when the bytes cannot be decoded by the given charset
 * is to replace malformed input and unmappable characters with the charset's default
 * replacement string. Use {@link java.nio.charset.CharsetDecoder} for more control.
 *
 * @throws IndexOutOfBoundsException
 *             if {@code byteCount < 0 || offset < 0 || offset + byteCount > data.length}
 * @throws NullPointerException
 *             if {@code data == null}
 */
public static final String construct(byte[] data, int offset, int byteCount, Charset charset) {
    try {
        return new String(data, offset, byteCount, charset.name());
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 18
Project: luna   File: ByteStringBuilder.java   View Source Code Vote up 3 votes
/**
 * Appends a char sequence {@code charSequence} interpreted as a sequence
 * of bytes using the specified {@code Charset}.
 *
 * @param charSequence the char sequence to append, must not be {@code null}
 * @param charset the charset to use for encoding, must not be {@code null}
 * @return this builder
 * @throws NullPointerException if {@code string} is {@code null}
 * @throws IllegalArgumentException if {@code charset} cannot does not provide encoding capability
 * (see {@link Charset#canEncode()})
 */
public ByteStringBuilder append(CharSequence charSequence, Charset charset) {
  if (!charset.canEncode()) {
    throw new IllegalArgumentException("Charset cannot encode: " + charset.name());
  }

  // FIXME: inefficient, could be done more directly
  append(ByteString.of(charSequence.toString(), charset));
  return this;
}
 
Example 19
Project: easyfilemanager   File: Strings.java   View Source Code Vote up 3 votes
/**
 * Converts the byte array to a string using the given charset.
 *
 * <p>The behavior when the bytes cannot be decoded by the given charset
 * is to replace malformed input and unmappable characters with the charset's default
 * replacement string. Use {@link java.nio.charset.CharsetDecoder} for more control.
 *
 * @throws IndexOutOfBoundsException
 *             if {@code byteCount < 0 || offset < 0 || offset + byteCount > data.length}
 * @throws NullPointerException
 *             if {@code data == null}
 */
public static final String construct(byte[] data, int offset, int byteCount, Charset charset) {
    try {
        return new String(data, offset, byteCount, charset.name());
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 20
Project: cactoos   File: BytesOf.java   View Source Code Vote up 2 votes
/**
 * Ctor.
 * @param error The exception to serialize
 * @param charset Charset
 */
public BytesOf(final Throwable error, final Charset charset) {
    this(error, charset.name());
}