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:com.joyent.manta.client.crypto.EncryptingEntityTest.java

private void canEncryptAndDecryptToAndFromFileWithManySizes(SupportedCipherDetails cipherDetails)
        throws Exception {
    final Charset charset = StandardCharsets.US_ASCII;
    final int maxLength = 1025;

    for (int i = 0; i < maxLength; i++) {
        final char[] chars = new char[i];
        Arrays.fill(chars, 'z');
        final String expectedString = String.valueOf(chars);

        ExposedStringEntity stringEntity = new ExposedStringEntity(expectedString, charset);

        byte[] keyBytes = SecretKeyUtils.generate(cipherDetails).getEncoded();

        verifyEncryptionWorksRoundTrip(keyBytes, cipherDetails, stringEntity, (actualBytes) -> {
            final String actual = new String(actualBytes, charset);
            Assert.assertEquals(actual, expectedString, "Plaintext doesn't match decrypted value");
            return true;
        });//from   w w  w.  ja v a2s. c om
    }
}

From source file:org.wso2.identity.scenarios.access.delegation.oauth2.code.pkce.OAuth2AuthorizationCodeGrantWithPKCES256Test.java

/**
 * Generates PKCE code challenge./*  w ww.j  a v  a2s.  c om*/
 *
 * @param codeVerifier PKCE code verifier.
 * @return Code challenge.
 * @throws NoSuchAlgorithmException No Such Algorithm Exception.
 */
private String getPKCECodeChallenge(String codeVerifier) throws NoSuchAlgorithmException {

    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] hash = digest.digest(codeVerifier.getBytes(StandardCharsets.US_ASCII));
    //Base64 encoded string is trimmed to remove trailing CR LF
    return new String(Base64.encodeBase64URLSafe(hash), StandardCharsets.UTF_8).trim();
}

From source file:net.cyllene.hackerrank.downloader.HackerrankDownloader.java

/**
 * Gets a secret key from configuration file in user.home.
 * The secret key is a _hackerrank_session variable stored in cookies by server.
 * To simplify things, no login logic is present in this program, it means
 * you should login somewhere else and then provide this value in the config.
 *
 * @return String representing a _hackerrank_session id, about 430 characters long.
 *///from   w w w . j a  v  a2  s.c o m
private static String getSecretFromConfig() {
    final String confPathStr = System.getProperty("user.home") + File.separator
            + DownloaderSettings.KEYFILE_NAME;
    final Path confPath = Paths.get(confPathStr);
    String result = null;
    try {
        result = Files.readAllLines(confPath, StandardCharsets.US_ASCII).get(0);
    } catch (IOException e) {
        System.err.println("Fatal Error: Unable to open configuration file " + confPathStr
                + System.lineSeparator() + "File might be missing, empty or inaccessible by user."
                + System.lineSeparator() + "It must contain a single ASCII line, a value of \""
                + DownloaderSettings.SECRET_COOKIE_ID + "\" cookie variable," + System.lineSeparator()
                + "which length is about 430 symbols.");
        System.exit(1);
    }

    return result;
}

From source file:com.linecorp.armeria.server.http.auth.AuthServiceTest.java

private static HttpRequestBase basicGetRequest(String path, BasicToken basicToken) {
    HttpGet request = new HttpGet(uri(path));
    request.addHeader("Authorization", "Basic " + BASE64_ENCODER.encodeToString(
            (basicToken.username() + ':' + basicToken.password()).getBytes(StandardCharsets.US_ASCII)));
    return request;
}

From source file:edu.ksu.cis.santos.mdcf.dms.test.SymbolTableTest.java

void testExpectedResult(final String name, final String content)
        throws URISyntaxException, IOException, Exception {
    final File testDir = new File(
            new URI(getClass().getResource("").toURI().toString().replace("/bin/", "/src/test/resources/")));

    final File expected = new File(testDir, "expected/" + name + ".rst");
    final File result = new File(testDir, "result/" + name + ".rst");
    if (SymbolTableTest.GENERATE_EXPECTED || !expected.exists()) {
        expected.getParentFile().mkdirs();
        Files.write(content, expected, StandardCharsets.US_ASCII);
    } else {//  w w  w .ja  v  a  2s. c om
        result.getParentFile().mkdirs();
        Files.write(content, result, StandardCharsets.US_ASCII);
        assertEquals(expected, result);
    }
}

From source file:com.linecorp.armeria.server.ServerTest.java

private static void testSimple(String reqLine, String expectedStatusLine, String... expectedHeaders)
        throws Exception {

    try (Socket socket = new Socket()) {
        socket.setSoTimeout((int) (idleTimeoutMillis * 4));
        socket.connect(server().activePort().get().localAddress());
        PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), false);

        outWriter.print(reqLine);/*from  ww w.  ja  v  a 2  s  . co m*/
        outWriter.print("\r\n");
        outWriter.print("Connection: close\r\n");
        outWriter.print("Content-Length: 0\r\n");
        outWriter.print("\r\n");
        outWriter.flush();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII));

        assertThat(in.readLine(), is(expectedStatusLine));
        // Read till the end of the connection.
        List<String> headers = new ArrayList<>();
        for (;;) {
            String line = in.readLine();
            if (line == null) {
                break;
            }

            // This is not really correct, but just wanna make it as simple as possible.
            headers.add(line);
        }

        for (String expectedHeader : expectedHeaders) {
            if (!headers.contains(expectedHeader)) {
                fail("does not contain '" + expectedHeader + "': " + headers);
            }
        }
    }
}

From source file:io.syndesis.rest.v1.state.ClientSideState.java

static byte[] mac(final String authenticationAlgorithm, final CharSequence base,
        final SecretKey authenticationKey) {
    try {// w  w w  .  j  av  a 2  s . c  o  m
        final String baseString = base.toString();

        final Mac mac = Mac.getInstance(authenticationAlgorithm);
        mac.init(authenticationKey);

        // base contains only BASE64 characters and '|', so we use ASCII
        final byte[] raw = baseString.getBytes(StandardCharsets.US_ASCII);

        return mac.doFinal(raw);
    } catch (final GeneralSecurityException e) {
        throw new IllegalStateException("Unable to compute MAC of the given value", e);
    }
}

From source file:itdelatrisu.opsu.replay.Replay.java

/**
 * Saves the replay data to a file in the replays directory.
 *///from www  .j  a  v  a  2s  .co  m
public void save() {
    // create replay directory
    File dir = Options.getReplayDir();
    if (!dir.isDirectory()) {
        if (!dir.mkdir()) {
            ErrorHandler.error("Failed to create replay directory.", null, false);
            return;
        }
    }

    // write file in new thread
    final File file = new File(dir, String.format("%s.osr", getReplayFilename()));
    new Thread() {
        @Override
        public void run() {
            try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
                OsuWriter writer = new OsuWriter(out);

                // header
                writer.write(mode);
                writer.write(version);
                writer.write(beatmapHash);
                writer.write(playerName);
                writer.write(replayHash);
                writer.write(hit300);
                writer.write(hit100);
                writer.write(hit50);
                writer.write(geki);
                writer.write(katu);
                writer.write(miss);
                writer.write(score);
                writer.write(combo);
                writer.write(perfect);
                writer.write(mods);

                // life data
                StringBuilder sb = new StringBuilder();
                if (lifeFrames != null) {
                    NumberFormat nf = new DecimalFormat("##.##");
                    for (int i = 0; i < lifeFrames.length; i++) {
                        LifeFrame frame = lifeFrames[i];
                        sb.append(String.format("%d|%s,", frame.getTime(), nf.format(frame.getPercentage())));
                    }
                }
                writer.write(sb.toString());

                // timestamp
                writer.write(timestamp);

                // LZMA-encoded replay data
                if (frames != null && frames.length > 0) {
                    // build full frame string
                    NumberFormat nf = new DecimalFormat("###.#####");
                    sb = new StringBuilder();
                    for (int i = 0; i < frames.length; i++) {
                        ReplayFrame frame = frames[i];
                        sb.append(String.format("%d|%s|%s|%d,", frame.getTimeDiff(), nf.format(frame.getX()),
                                nf.format(frame.getY()), frame.getKeys()));
                    }
                    sb.append(String.format("%s|0|0|%d", SEED_STRING, seed));

                    // get bytes from string
                    CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder();
                    CharBuffer buffer = CharBuffer.wrap(sb);
                    byte[] bytes = encoder.encode(buffer).array();

                    // compress data
                    ByteArrayOutputStream bout = new ByteArrayOutputStream();
                    LzmaOutputStream compressedOut = new LzmaOutputStream.Builder(bout)
                            .useMediumDictionarySize().build();
                    try {
                        compressedOut.write(bytes);
                    } catch (IOException e) {
                        // possible OOM: https://github.com/jponge/lzma-java/issues/9
                        ErrorHandler.error("LZMA compression failed (possible out-of-memory error).", e, true);
                    }
                    compressedOut.close();
                    bout.close();

                    // write to file
                    byte[] compressed = bout.toByteArray();
                    writer.write(compressed.length);
                    writer.write(compressed);
                } else
                    writer.write(0);

                writer.close();
            } catch (IOException e) {
                ErrorHandler.error("Could not save replay data.", e, true);
            }
        }
    }.start();
}

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

License:asdf

@Test
public void testStandardParseParamsAndFillStreamsISO88591() throws Exception {
    final String getParams = "qt=%FC&dup=foo&ie=iso-8859-1&dup=%FC", postParams = "qt2=%FC&q=hello&d%75p=bar";
    final byte[] postBytes = postParams.getBytes(StandardCharsets.US_ASCII);
    final String contentType = "application/x-www-form-urlencoded; charset=iso-8859-1";

    // Set up the expected behavior
    HttpServletRequest request = getMock("/solr/select", contentType, postBytes.length);
    expect(request.getMethod()).andReturn("POST").anyTimes();
    expect(request.getQueryString()).andReturn(getParams).anyTimes();
    expect(request.getInputStream()).andReturn(new ByteServletInputStream(postBytes));
    replay(request);//from   ww  w .  ja  v a  2 s  .  com

    MultipartRequestParser multipart = new MultipartRequestParser(2048);
    RawRequestParser raw = new RawRequestParser();
    FormDataRequestParser formdata = new FormDataRequestParser(2048);
    StandardRequestParser standard = new StandardRequestParser(multipart, raw, formdata);

    SolrParams p = standard.parseParamsAndFillStreams(request, new ArrayList<ContentStream>());

    assertEquals("contentType: " + contentType, "hello", p.get("q"));
    assertEquals("contentType: " + contentType, "\u00FC", p.get("qt"));
    assertEquals("contentType: " + contentType, "\u00FC", p.get("qt2"));
    assertArrayEquals("contentType: " + contentType, new String[] { "foo", "\u00FC", "bar" },
            p.getParams("dup"));
}

From source file:com.linecorp.armeria.server.http.auth.HttpAuthServiceTest.java

private static HttpRequestBase basicGetRequest(String path, BasicToken basicToken) {
    HttpGet request = new HttpGet(server.uri(path));
    request.addHeader("Authorization", "Basic " + BASE64_ENCODER.encodeToString(
            (basicToken.username() + ':' + basicToken.password()).getBytes(StandardCharsets.US_ASCII)));
    return request;
}