Example usage for java.nio.charset StandardCharsets US_ASCII

List of usage examples for java.nio.charset StandardCharsets US_ASCII

Introduction

In this page you can find the example usage for java.nio.charset StandardCharsets US_ASCII.

Prototype

Charset US_ASCII

To view the source code for java.nio.charset StandardCharsets US_ASCII.

Click Source Link

Document

Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set.

Usage

From source file:org.springframework.http.converter.FormHttpMessageConverter.java

@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
    Object partBody = partEntity.getBody();
    if (partBody == null) {
        throw new IllegalStateException("Empty body for part '" + name + "': " + partEntity);
    }// w  ww.  j a v  a 2  s .  c  o m
    Class<?> partType = partBody.getClass();
    HttpHeaders partHeaders = partEntity.getHeaders();
    MediaType partContentType = partHeaders.getContentType();
    for (HttpMessageConverter<?> messageConverter : this.partConverters) {
        if (messageConverter.canWrite(partType, partContentType)) {
            Charset charset = isFilenameCharsetSet() ? StandardCharsets.US_ASCII : this.charset;
            HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, charset);
            multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
            if (!partHeaders.isEmpty()) {
                multipartMessage.getHeaders().putAll(partHeaders);
            }
            ((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType,
                    multipartMessage);
            return;
        }
    }
    throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter "
            + "found for request type [" + partType.getName() + "]");
}

From source file:com.microsoft.azure.management.datalake.store.uploader.StringExtensionsTests.java

@Test
public void StringExtensions_FindNewLine_ASCII() {
    for (Triple<String, Integer, Integer> t : TestDataUTF8) {
        byte[] exactBuffer = t.getLeft().getBytes(StandardCharsets.US_ASCII);
        byte[] largerBuffer = new byte[exactBuffer.length + 100];
        System.arraycopy(exactBuffer, 0, largerBuffer, 0, exactBuffer.length);

        int forwardInExactBuffer = StringExtensions.findNewline(exactBuffer, 0, exactBuffer.length, false,
                StandardCharsets.US_ASCII, null);
        Assert.assertEquals(t.getMiddle().intValue(), forwardInExactBuffer);

        int forwardInLargeBuffer = StringExtensions.findNewline(largerBuffer, 0, exactBuffer.length, false,
                StandardCharsets.US_ASCII, null);
        Assert.assertEquals(t.getMiddle().intValue(), forwardInLargeBuffer);

        int reverseInExactBuffer = StringExtensions.findNewline(exactBuffer,
                Math.max(0, exactBuffer.length - 1), exactBuffer.length, true, StandardCharsets.US_ASCII, null);
        Assert.assertEquals(t.getRight().intValue(), reverseInExactBuffer);

        int reverseInLargeBuffer = StringExtensions.findNewline(largerBuffer,
                Math.max(0, exactBuffer.length - 1), exactBuffer.length, true, StandardCharsets.US_ASCII, null);
        Assert.assertEquals(t.getRight().intValue(), reverseInLargeBuffer);
    }//w  w w.  j av  a 2 s .c o  m

    for (Triple<String, Integer, Integer> t : TestDataUTF8CustomDelim) {
        byte[] exactBuffer = t.getLeft().getBytes(StandardCharsets.US_ASCII);
        byte[] largerBuffer = new byte[exactBuffer.length + 100];
        System.arraycopy(exactBuffer, 0, largerBuffer, 0, exactBuffer.length);

        int forwardInExactBuffer = StringExtensions.findNewline(exactBuffer, 0, exactBuffer.length, false,
                StandardCharsets.US_ASCII, customDelim);
        Assert.assertEquals(t.getMiddle().intValue(), forwardInExactBuffer);

        int forwardInLargeBuffer = StringExtensions.findNewline(largerBuffer, 0, exactBuffer.length, false,
                StandardCharsets.US_ASCII, customDelim);
        Assert.assertEquals(t.getMiddle().intValue(), forwardInLargeBuffer);

        int reverseInExactBuffer = StringExtensions.findNewline(exactBuffer,
                Math.max(0, exactBuffer.length - 1), exactBuffer.length, true, StandardCharsets.US_ASCII,
                customDelim);
        Assert.assertEquals(t.getRight().intValue(), reverseInExactBuffer);

        int reverseInLargeBuffer = StringExtensions.findNewline(largerBuffer,
                Math.max(0, exactBuffer.length - 1), exactBuffer.length, true, StandardCharsets.US_ASCII,
                customDelim);
        Assert.assertEquals(t.getRight().intValue(), reverseInLargeBuffer);
    }
}

From source file:net.yacy.document.parser.htmlParser.java

/**
 * some html authors use wrong encoding names, either because they don't know exactly what they
 * are doing or they produce a type. Many times, the upper/downcase scheme of the name is fuzzy
 * This method patches wrong encoding names. The correct names are taken from
 * http://www.iana.org/assignments/character-sets
 * @param encoding/*from  w ww  .  j a va2  s. co  m*/
 * @return patched encoding name
 */
public static String patchCharsetEncoding(String encoding) {

    // do nothing with null
    if ((encoding == null) || (encoding.length() < 3))
        return null;

    // trim encoding string
    encoding = encoding.trim();

    // fix upper/lowercase
    encoding = encoding.toUpperCase(Locale.ROOT);
    if (encoding.startsWith("SHIFT"))
        return "Shift_JIS";
    if (encoding.startsWith("BIG"))
        return "Big5";
    // all other names but such with "windows" use uppercase
    if (encoding.startsWith("WINDOWS"))
        encoding = "windows" + encoding.substring(7);
    if (encoding.startsWith("MACINTOSH"))
        encoding = "MacRoman";

    // fix wrong fill characters
    encoding = CommonPattern.UNDERSCORE.matcher(encoding).replaceAll("-");

    if (encoding.matches("GB[_-]?2312([-_]80)?"))
        return "GB2312";
    if (encoding.matches(".*UTF[-_]?8.*"))
        return StandardCharsets.UTF_8.name();
    if (encoding.startsWith("US"))
        return StandardCharsets.US_ASCII.name();
    if (encoding.startsWith("KOI"))
        return "KOI8-R";

    // patch missing '-'
    if (encoding.startsWith("windows") && encoding.length() > 7) {
        final char c = encoding.charAt(7);
        if ((c >= '0') && (c <= '9')) {
            encoding = "windows-" + encoding.substring(7);
        }
    }

    if (encoding.startsWith("ISO")) {
        // patch typos
        if (encoding.length() > 3) {
            final char c = encoding.charAt(3);
            if ((c >= '0') && (c <= '9')) {
                encoding = "ISO-" + encoding.substring(3);
            }
        }
        if (encoding.length() > 8) {
            final char c = encoding.charAt(8);
            if ((c >= '0') && (c <= '9')) {
                encoding = encoding.substring(0, 8) + "-" + encoding.substring(8);
            }
        }
    }

    // patch wrong name
    if (encoding.startsWith("ISO-8559")) {
        // popular typo
        encoding = "ISO-8859" + encoding.substring(8);
    }

    // converting cp\d{4} -> windows-\d{4}
    if (encoding.matches("CP([_-])?125[0-8]")) {
        final char c = encoding.charAt(2);
        if ((c >= '0') && (c <= '9')) {
            encoding = "windows-" + encoding.substring(2);
        } else {
            encoding = "windows" + encoding.substring(2);
        }
    }

    return encoding;
}

From source file:org.parosproxy.paros.db.paros.ParosTableHistory.java

private synchronized RecordHistory write(long sessionId, int histType, long timeSentMillis,
        int timeElapsedMillis, String method, String uri, int statusCode, String reqHeader, byte[] reqBody,
        String resHeader, byte[] resBody, String tag, String note, boolean responseFromTargetHost)
        throws HttpMalformedHeaderException, SQLException, DatabaseException {

    //ZAP: Allow the request and response body sizes to be user-specifiable as far as possible
    if (reqBody.length > this.configuredrequestbodysize) {
        throw new SQLException("The actual Request Body length " + reqBody.length
                + " is greater than the configured request body length " + this.configuredrequestbodysize);
    }/* w  w w .  ja v a 2s  .  c  o  m*/
    if (resBody.length > this.configuredresponsebodysize) {
        throw new SQLException("The actual Response Body length " + resBody.length
                + " is greater than the configured response body length " + this.configuredresponsebodysize);
    }

    psInsert.setLong(1, sessionId);
    psInsert.setInt(2, histType);
    psInsert.setLong(3, timeSentMillis);
    psInsert.setInt(4, timeElapsedMillis);
    psInsert.setString(5, method);
    psInsert.setString(6, uri);
    psInsert.setString(7, reqHeader);
    if (bodiesAsBytes) {
        psInsert.setBytes(8, reqBody);
    } else {
        psInsert.setString(8, new String(reqBody, StandardCharsets.US_ASCII));
    }
    psInsert.setString(9, resHeader);
    if (bodiesAsBytes) {
        psInsert.setBytes(10, resBody);
    } else {
        psInsert.setString(10, new String(resBody, StandardCharsets.US_ASCII));
    }
    psInsert.setString(11, tag);

    // ZAP: Added the statement.
    int currentIdx = 12;

    if (isExistStatusCode) {
        psInsert.setInt(currentIdx, statusCode);
        // ZAP: Added the statement.
        ++currentIdx;
    }

    // ZAP: Added the statement.
    psInsert.setString(currentIdx, note);
    ++currentIdx;

    psInsert.setBoolean(currentIdx, responseFromTargetHost);

    psInsert.executeUpdate();

    /*
      String sql = "INSERT INTO HISTORY ("
      + REQHEADER + "," + REQBODY + "," + RESHEADER + "," + RESBODY +
    ") VALUES ('"+ reqHeader + "','" + reqBody + "','" + resHeader + "','" + resBody + "'); CALL IDENTITY();";
    Statement stmt = mConn.createStatement();
    stmt.executeQuery(sql);
    ResultSet rs = stmt.getResultSet();
    */

    try (ResultSet rs = psGetIdLastInsert.executeQuery()) {
        rs.next();
        int id = rs.getInt(1);
        lastInsertedIndex = id;
        return read(id);
    }
}

From source file:org.sejda.sambox.pdmodel.font.FileSystemFontProvider.java

/**
 * Adds an OTF or TTF font to the file cache. To reduce memory, the parsed font is not cached.
 *//* w w w. ja v  a2  s . c  o m*/
private void addTrueTypeFontImpl(TrueTypeFont ttf, File file) throws IOException {
    try {
        // read PostScript name, if any
        if (ttf.getName() != null) {
            // ignore bitmap fonts
            if (ttf.getHeader() == null) {
                fontInfoList.add(new FSIgnored(file, FontFormat.TTF, ttf.getName()));
                return;
            }
            int macStyle = ttf.getHeader().getMacStyle();

            int sFamilyClass = -1;
            int usWeightClass = -1;
            int ulCodePageRange1 = 0;
            int ulCodePageRange2 = 0;
            byte[] panose = null;

            // Apple's AAT fonts don't have an OS/2 table
            if (ttf.getOS2Windows() != null) {
                sFamilyClass = ttf.getOS2Windows().getFamilyClass();
                usWeightClass = ttf.getOS2Windows().getWeightClass();
                ulCodePageRange1 = (int) ttf.getOS2Windows().getCodePageRange1();
                ulCodePageRange2 = (int) ttf.getOS2Windows().getCodePageRange2();
                panose = ttf.getOS2Windows().getPanose();
            }

            String format;
            if (ttf instanceof OpenTypeFont && ((OpenTypeFont) ttf).isPostScript()) {
                format = "OTF";
                CFFFont cff = ((OpenTypeFont) ttf).getCFF().getFont();
                CIDSystemInfo ros = null;
                if (cff instanceof CFFCIDFont) {
                    CFFCIDFont cidFont = (CFFCIDFont) cff;
                    String registry = cidFont.getRegistry();
                    String ordering = cidFont.getOrdering();
                    int supplement = cidFont.getSupplement();
                    ros = new CIDSystemInfo(registry, ordering, supplement);
                }
                fontInfoList.add(new FSFontInfo(file, FontFormat.OTF, ttf.getName(), ros, usWeightClass,
                        sFamilyClass, ulCodePageRange1, ulCodePageRange2, macStyle, panose, this));
            } else {
                CIDSystemInfo ros = null;
                if (ttf.getTableMap().containsKey("gcid")) {
                    // Apple's AAT fonts have a "gcid" table with CID info
                    byte[] bytes = ttf.getTableBytes(ttf.getTableMap().get("gcid"));
                    String reg = new String(bytes, 10, 64, StandardCharsets.US_ASCII);
                    String registryName = reg.substring(0, reg.indexOf('\0'));
                    String ord = new String(bytes, 76, 64, StandardCharsets.US_ASCII);
                    String orderName = ord.substring(0, ord.indexOf('\0'));
                    int supplementVersion = bytes[140] << 8 & bytes[141];
                    ros = new CIDSystemInfo(registryName, orderName, supplementVersion);
                }

                format = "TTF";
                fontInfoList.add(new FSFontInfo(file, FontFormat.TTF, ttf.getName(), ros, usWeightClass,
                        sFamilyClass, ulCodePageRange1, ulCodePageRange2, macStyle, panose, this));
            }

            if (LOG.isTraceEnabled()) {
                NamingTable name = ttf.getNaming();
                if (name != null) {
                    LOG.trace(format + ": '" + name.getPostScriptName() + "' / '" + name.getFontFamily()
                            + "' / '" + name.getFontSubFamily() + "'");
                }
            }
        } else {
            fontInfoList.add(new FSIgnored(file, FontFormat.TTF, "*skipnoname*"));
            LOG.warn("Missing 'name' entry for PostScript name in font " + file);
        }
    } catch (IOException e) {
        fontInfoList.add(new FSIgnored(file, FontFormat.TTF, "*skipexception*"));
        LOG.error("Could not load font file: " + file, e);
    } finally {
        if (ttf != null) {
            ttf.close();
        }
    }
}

From source file:htsjdk.samtools.reference.FastaReferenceWriter.java

/**
 * Adds bases to current sequence from a {@code byte} array.
 *
 * @param basesBases String containing the bases to be added.
 *                   string will be interpreted using ascii and will throw if any character is >= 127.
 * @return this instance./*from ww  w .  ja v a2  s.  co  m*/
 * @throws IllegalArgumentException if {@code bases} is {@code null} or
 *                                  the input array contains invalid bases (as assessed by: {@link SequenceUtil#isIUPAC(byte)}).
 * @throws IllegalStateException    if no sequence was started or the writer is already closed.
 * @throws IOException              if such exception is throw when writing in any of the outputs.
 */
public FastaReferenceWriter appendBases(final String basesBases) throws IOException {
    return appendBases(basesBases.getBytes(StandardCharsets.US_ASCII));
}

From source file:org.apache.solr.servlet.SolrRequestParserTest.java

License:asdf

public void doAutoDetect(String userAgent, String method, final String body, String expectedContentType,
        String expectedKey, String expectedValue) throws Exception {
    String uri = "/solr/select";
    String contentType = "application/x-www-form-urlencoded";
    int contentLength = -1; // does this mean auto-detect?

    HttpServletRequest request = createMock(HttpServletRequest.class);
    expect(request.getHeader("User-Agent")).andReturn(userAgent).anyTimes();
    expect(request.getHeader("Content-Length")).andReturn(null).anyTimes();
    expect(request.getRequestURI()).andReturn(uri).anyTimes();
    expect(request.getContentType()).andReturn(contentType).anyTimes();
    expect(request.getContentLength()).andReturn(contentLength).anyTimes();
    expect(request.getAttribute(SolrRequestParsers.REQUEST_TIMER_SERVLET_ATTRIBUTE)).andReturn(null).anyTimes();

    expect(request.getMethod()).andReturn(method).anyTimes();
    // we dont pass a content-length to let the security mechanism limit it:
    expect(request.getQueryString()).andReturn("foo=1&bar=2").anyTimes();
    expect(request.getInputStream())//from  www . j a  v a 2  s. co  m
            .andReturn(new ByteServletInputStream(body.getBytes(StandardCharsets.US_ASCII)));
    expect(request.getAttribute(EasyMock.anyObject(String.class))).andReturn(null).anyTimes();
    replay(request);

    SolrRequestParsers parsers = new SolrRequestParsers(h.getCore().getSolrConfig());
    SolrQueryRequest req = parsers.parse(h.getCore(), "/select", request);
    int num = 0;
    if (expectedContentType != null) {
        for (ContentStream cs : req.getContentStreams()) {
            num++;
            assertTrue(cs.getContentType().startsWith(expectedContentType));
            String returnedBody = IOUtils.toString(cs.getReader());
            assertEquals(body, returnedBody);
        }
        assertEquals(1, num);
    }

    assertEquals("1", req.getParams().get("foo"));
    assertEquals("2", req.getParams().get("bar"));

    if (expectedKey != null) {
        assertEquals(expectedValue, req.getParams().get(expectedKey));
    }

    req.close();
}

From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java

private String encodeBase64(final ByteBuffer buffer) {
    final int limit = buffer.limit();
    final byte[] bytes = new byte[limit];
    buffer.get(bytes);//from   w ww  .ja v  a  2 s .c  o  m
    return new String(Base64.encodeBase64(bytes), StandardCharsets.US_ASCII);
}

From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java

private ByteBuffer decodeBase64(final String inputString) {
    final byte[] inputBytes = Base64.decodeBase64(inputString.getBytes(StandardCharsets.US_ASCII));
    final ByteBuffer buffer = ByteBuffer.wrap(inputBytes);
    return buffer;
}

From source file:nl.salp.warcraft4j.casc.cdn.CdnCascContext.java

/**
 * Create a hash for a filename./*ww  w .  j av a2 s .com*/
 *
 * @param filename The filename.
 *
 * @return The hash.
 */
public static long hashFilename(String filename) {
    long hash;
    if (isEmpty(filename)) {
        hash = 0;
    } else {
        ;
        byte[] data = cleanFilename(filename).getBytes(StandardCharsets.US_ASCII);
        hash = JenkinsHash.hashLittle2(data, data.length);
    }
    return hash;
}