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.google.android.apps.forscience.ble.DeviceDiscoverer.java

protected String extractLongName(byte[] scanRecord) {
    String longname = "";
    int size = scanRecord.length;
    if (size == 62) {
        byte[] scanResponse = Arrays.copyOfRange(scanRecord, 32, 61);
        if (scanResponse[0] != 0) {
            byte[] shortname = Arrays.copyOfRange(scanResponse, 0, 7);
            int length = scanResponse[7];
            //                int adType = scanResponse[8];
            //                int uuidLsb = scanResponse[9];
            //                int uuidMsb = scanResponse[10];
            byte[] scandata = Arrays.copyOfRange(scanResponse, 11, length + 11);
            longname = new String(scandata, StandardCharsets.US_ASCII) + " ("
                    + new String(shortname, StandardCharsets.US_ASCII) + ")";
        }/*  w w  w .  ja v  a  2 s.co m*/
    }

    return longname;
}

From source file:com.cloudbees.plugins.credentials.SecretBytesTest.java

@Test
public void largeRawString__noChunking__noUrlSafe() throws Exception {
    byte[] data = new byte[2048];
    new Random().nextBytes(data);
    assertThat(SecretBytes/*w  w w .j  a v  a2s  .c om*/
            .fromString(new String(org.apache.commons.codec.binary.Base64.encodeBase64(data, false, false),
                    StandardCharsets.US_ASCII))
            .getPlainData(), is(data));
}

From source file:org.kse.gui.actions.ExportKeyPairAction.java

private void exportAsPem(File exportFile, PrivateKey privateKey, Certificate[] certs, Password password)
        throws CryptoException, IOException {

    String pemEncodedPrivKey = null;
    if (password.isEmpty()) {
        pemEncodedPrivKey = Pkcs8Util.getPem(privateKey);
    } else {//from w  w w . j ava2  s  .c om
        pemEncodedPrivKey = Pkcs8Util.getEncryptedPem(privateKey, Pkcs8PbeType.SHA1_3KEY_DESEDE, password);
    }

    X509Certificate[] orderedCerts = X509CertUtil.orderX509CertChain(X509CertUtil.convertCertificates(certs));
    String pemEncodedCerts = X509CertUtil.getCertsEncodedX509Pem(orderedCerts);

    FileUtils.write(exportFile, pemEncodedPrivKey + pemEncodedCerts, StandardCharsets.US_ASCII);
}

From source file:net.pms.util.AudioUtils.java

/**
 * Parses the old RealAudio 1.0 and 2.0 formats that's not supported by
 * neither {@link org.jaudiotagger} nor MediaInfo. Returns {@code false} if
 * {@code channel} isn't one of these formats or the parsing fails.
 * <p>//from   w  w  w .j  a  v  a  2 s . co  m
 * Primary references:
 * <ul>
 * <li><a href="https://wiki.multimedia.cx/index.php/RealMedia">RealAudio on
 * MultimediaWiki</a></li>
 * <li><a
 * href="https://github.com/FFmpeg/FFmpeg/blob/master/libavformat/rmdec.c"
 * >FFmpeg rmdec.c</a></li>
 * </ul>
 *
 * @param channel the {@link Channel} containing the input. Size will only
 *            be parsed if {@code channel} is a {@link FileChannel}
 *            instance.
 * @param media the {@link DLNAMediaInfo} instance to write the parsing
 *            results to.
 * @return {@code true} if the {@code channel} input is in RealAudio 1.0 or
 *         2.0 format and the parsing succeeds; false otherwise
 */
public static boolean parseRealAudio(ReadableByteChannel channel, DLNAMediaInfo media) {
    final byte[] magicBytes = { 0x2E, 0x72, 0x61, (byte) 0xFD };
    ByteBuffer buffer = ByteBuffer.allocate(8);
    buffer.order(ByteOrder.BIG_ENDIAN);
    DLNAMediaAudio audio = new DLNAMediaAudio();
    try {
        int count = channel.read(buffer);
        if (count < 4) {
            LOGGER.trace("Input is too short to be RealAudio");
            return false;
        }
        buffer.flip();
        byte[] signature = new byte[4];
        buffer.get(signature);
        if (!Arrays.equals(magicBytes, signature)) {
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Input signature ({}) mismatches RealAudio version 1.0 or 2.0",
                        new String(signature, StandardCharsets.US_ASCII));
            }
            return false;
        }
        media.setContainer(FormatConfiguration.RA);
        short version = buffer.getShort();
        int reportedHeaderSize = 0;
        int reportedDataSize = 0;
        if (version == 3) {
            audio.setCodecA(FormatConfiguration.REALAUDIO_14_4);
            audio.getAudioProperties().setNumberOfChannels(1);
            audio.getAudioProperties().setSampleFrequency(8000);
            short headerSize = buffer.getShort();

            buffer = ByteBuffer.allocate(headerSize);
            channel.read(buffer);
            buffer.flip();
            buffer.position(8);
            int bytesPerMinute = buffer.getShort() & 0xFFFF;
            reportedDataSize = buffer.getInt();
            byte b = buffer.get();
            if (b != 0) {
                byte[] title = new byte[b & 0xFF];
                buffer.get(title);
                String titleString = new String(title, StandardCharsets.US_ASCII);
                audio.setSongname(titleString);
                audio.setAudioTrackTitleFromMetadata(titleString);
            }
            b = buffer.get();
            if (b != 0) {
                byte[] artist = new byte[b & 0xFF];
                buffer.get(artist);
                audio.setArtist(new String(artist, StandardCharsets.US_ASCII));
            }
            audio.setBitRate(bytesPerMinute * 8 / 60);
            media.setBitrate(bytesPerMinute * 8 / 60);
        } else if (version == 4 || version == 5) {
            buffer = ByteBuffer.allocate(14);
            channel.read(buffer);
            buffer.flip();
            buffer.get(signature);
            if (!".ra4".equals(new String(signature, StandardCharsets.US_ASCII))) {
                LOGGER.debug("Invalid RealAudio 2.0 signature \"{}\"",
                        new String(signature, StandardCharsets.US_ASCII));
                return false;
            }
            reportedDataSize = buffer.getInt();
            buffer.getShort(); //skip version repeated
            reportedHeaderSize = buffer.getInt();

            buffer = ByteBuffer.allocate(reportedHeaderSize);
            channel.read(buffer);
            buffer.flip();
            buffer.getShort(); // skip codec flavor
            buffer.getInt(); // skip coded frame size
            buffer.getInt(); // skip unknown
            long bytesPerMinute = buffer.getInt() & 0xFFFFFFFFL;
            buffer.getInt(); // skip unknown
            buffer.getShort(); // skip sub packet
            buffer.getShort(); // skip frame size
            buffer.getShort(); // skip sub packet size
            buffer.getShort(); // skip unknown
            if (version == 5) {
                buffer.position(buffer.position() + 6); // skip unknown
            }
            short sampleRate = buffer.getShort();
            buffer.getShort(); // skip unknown
            short sampleSize = buffer.getShort();
            short nrChannels = buffer.getShort();
            byte[] fourCC;
            if (version == 4) {
                buffer.position(buffer.get() + buffer.position()); // skip interleaver id
                fourCC = new byte[buffer.get()];
                buffer.get(fourCC);
            } else {
                buffer.getFloat(); // skip deinterlace id
                fourCC = new byte[4];
                buffer.get(fourCC);
            }
            String fourCCString = new String(fourCC, StandardCharsets.US_ASCII).toLowerCase(Locale.ROOT);
            switch (fourCCString) {
            case "lpcJ":
                audio.setCodecA(FormatConfiguration.REALAUDIO_14_4);
                break;
            case "28_8":
                audio.setCodecA(FormatConfiguration.REALAUDIO_28_8);
                break;
            case "dnet":
                audio.setCodecA(FormatConfiguration.AC3);
                break;
            case "sipr":
                audio.setCodecA(FormatConfiguration.SIPRO);
                break;
            case "cook":
                audio.setCodecA(FormatConfiguration.COOK);
            case "atrc":
                audio.setCodecA(FormatConfiguration.ATRAC);
            case "ralf":
                audio.setCodecA(FormatConfiguration.RALF);
            case "raac":
                audio.setCodecA(FormatConfiguration.AAC_LC);
            case "racp":
                audio.setCodecA(FormatConfiguration.HE_AAC);
            default:
                LOGGER.debug("Unknown RealMedia codec FourCC \"{}\" - parsing failed", fourCCString);
                return false;
            }

            if (buffer.hasRemaining()) {
                parseRealAudioMetaData(buffer, audio, version);
            }

            audio.setBitRate((int) (bytesPerMinute * 8 / 60));
            media.setBitrate((int) (bytesPerMinute * 8 / 60));
            audio.setBitsperSample(sampleSize);
            audio.getAudioProperties().setNumberOfChannels(nrChannels);
            audio.getAudioProperties().setSampleFrequency(sampleRate);
        } else {
            LOGGER.error("Could not parse RealAudio format - unknown format version {}", version);
            return false;
        }

        media.getAudioTracksList().add(audio);
        long fileSize = 0;
        if (channel instanceof FileChannel) {
            fileSize = ((FileChannel) channel).size();
            media.setSize(fileSize);
        }
        // Duration is estimated based on bitrate and might not be accurate
        if (audio.getBitRate() > 0) {
            int dataSize;
            if (fileSize > 0 && reportedHeaderSize > 0) {
                int fullHeaderSize = reportedHeaderSize + (version == 3 ? 8 : 16);
                if (reportedDataSize > 0) {
                    dataSize = (int) Math.min(reportedDataSize, fileSize - fullHeaderSize);
                } else {
                    dataSize = (int) (fileSize - fullHeaderSize);
                }
            } else {
                dataSize = reportedDataSize;
            }
            media.setDuration((double) dataSize / audio.getBitRate() * 8);
        }

    } catch (IOException e) {
        LOGGER.debug("Error while trying to parse RealAudio version 1 or 2: {}", e.getMessage());
        LOGGER.trace("", e);
        return false;
    }
    if (PMS.getConfiguration() != null
            && !PMS.getConfiguration().getAudioThumbnailMethod().equals(CoverSupplier.NONE)
            && (StringUtils.isNotBlank(media.getFirstAudioTrack().getSongname())
                    || StringUtils.isNotBlank(media.getFirstAudioTrack().getArtist()))) {
        ID3v1Tag tag = new ID3v1Tag();
        if (StringUtils.isNotBlank(media.getFirstAudioTrack().getSongname())) {
            tag.setTitle(media.getFirstAudioTrack().getSongname());
        }
        if (StringUtils.isNotBlank(media.getFirstAudioTrack().getArtist())) {
            tag.setArtist(media.getFirstAudioTrack().getArtist());
        }
        try {
            media.setThumb(DLNAThumbnail.toThumbnail(CoverUtil.get().getThumbnail(tag), 640, 480, ScaleType.MAX,
                    ImageFormat.SOURCE, false));
        } catch (IOException e) {
            LOGGER.error("An error occurred while generating thumbnail for RealAudio source: [\"{}\", \"{}\"]",
                    tag.getFirstTitle(), tag.getFirstArtist());
        }
    }
    media.setThumbready(true);
    media.setMediaparsed(true);

    return true;
}

From source file:com.turo.pushy.apns.AuthenticationToken.java

public boolean verifySignature(final ApnsVerificationKey verificationKey)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    if (!this.header.getKeyId().equals(verificationKey.getKeyId())) {
        return false;
    }/*from   w w w .j a v a2 s  .  co m*/

    if (!this.claims.getIssuer().equals(verificationKey.getTeamId())) {
        return false;
    }

    final byte[] headerAndClaimsBytes;

    final String headerJson = GSON.toJson(this.header);
    final String claimsJson = GSON.toJson(this.claims);

    final StringBuilder headerAndClaimsBuilder = new StringBuilder();

    headerAndClaimsBuilder
            .append(Base64.encodeBase64URLSafeString(headerJson.getBytes(StandardCharsets.US_ASCII)));
    headerAndClaimsBuilder.append('.');
    headerAndClaimsBuilder
            .append(Base64.encodeBase64URLSafeString(claimsJson.getBytes(StandardCharsets.US_ASCII)));

    headerAndClaimsBytes = headerAndClaimsBuilder.toString().getBytes(StandardCharsets.US_ASCII);

    final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM);
    signature.initVerify(verificationKey);
    signature.update(headerAndClaimsBytes);

    return signature.verify(this.signatureBytes);
}

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

@SuppressWarnings("unchecked")
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();//from w w w. j av a2  s. co  m
    try {
        this.charset = Charset.forName(in.readUTF());
    } catch (final UnsupportedCharsetException ex) {
        this.charset = StandardCharsets.US_ASCII;
    }
}

From source file:com.cloudbees.plugins.credentials.SecretBytesTest.java

@Test
public void largeRawString__chunking__noUrlSafe() throws Exception {
    byte[] data = new byte[2048];
    new Random().nextBytes(data);
    assertThat(SecretBytes/*from  w ww  .j av a  2  s  . co m*/
            .fromString(new String(org.apache.commons.codec.binary.Base64.encodeBase64(data, true, false),
                    StandardCharsets.US_ASCII))
            .getPlainData(), is(data));
}

From source file:io.anserini.search.SearchCollection.java

@SuppressWarnings("unchecked")
public <K> int runTopics() throws IOException {
    IndexSearcher searcher = new IndexSearcher(reader);
    searcher.setSimilarity(similarity);//  ww w. ja  v a 2 s. co  m

    Path topicsFile = Paths.get(args.topics);

    if (!Files.exists(topicsFile) || !Files.isRegularFile(topicsFile) || !Files.isReadable(topicsFile)) {
        throw new IllegalArgumentException(
                "Topics file : " + topicsFile + " does not exist or is not a (readable) file.");
    }

    TopicReader<K> tr;
    SortedMap<K, Map<String, String>> topics;
    try {
        tr = (TopicReader<K>) Class.forName("io.anserini.search.query." + args.topicReader + "TopicReader")
                .getConstructor(Path.class).newInstance(topicsFile);
        topics = tr.read();
    } catch (Exception e) {
        throw new IllegalArgumentException("Unable to load topic reader: " + args.topicReader);
    }

    final String runTag = "Anserini_" + args.topicfield + "_" + (args.keepstop ? "KeepStopwords_" : "")
            + FIELD_BODY + "_" + (args.searchtweets ? "SearchTweets_" : "") + similarity.toString();

    PrintWriter out = new PrintWriter(
            Files.newBufferedWriter(Paths.get(args.output), StandardCharsets.US_ASCII));

    for (Map.Entry<K, Map<String, String>> entry : topics.entrySet()) {
        K qid = entry.getKey();
        String queryString = entry.getValue().get(args.topicfield);

        ScoredDocuments docs;
        if (args.searchtweets) {
            docs = searchTweets(searcher, qid, queryString, Long.parseLong(entry.getValue().get("time")));
        } else {
            docs = search(searcher, qid, queryString);
        }

        /**
         * the first column is the topic number.
         * the second column is currently unused and should always be "Q0".
         * the third column is the official document identifier of the retrieved document.
         * the fourth column is the rank the document is retrieved.
         * the fifth column shows the score (integer or floating point) that generated the ranking.
         * the sixth column is called the "run tag" and should be a unique identifier for your
         */
        for (int i = 0; i < docs.documents.length; i++) {
            out.println(String.format(Locale.US, "%s Q0 %s %d %f %s", qid,
                    docs.documents[i].getField(FIELD_ID).stringValue(), (i + 1), docs.scores[i],
                    ((i == 0 || i == docs.documents.length - 1) ? runTag : "See_Line1")));
        }
    }
    out.flush();
    out.close();

    return topics.size();
}

From source file:org.sonar.process.AllProcessesCommands.java

String getSystemInfoUrl(int processNumber) {
    byte[] urlBytes = readBytes(processNumber, SYSTEM_INFO_URL_BYTE_OFFSET, SYSTEM_INFO_URL_SIZE_IN_BYTES);
    return new String(urlBytes, StandardCharsets.US_ASCII).trim();
}

From source file:org.asynchttpclient.ntlm.NtlmTest.java

@Test(expectedExceptions = NtlmEngineException.class)
public void testGenerateType3MsgThrowsExceptionWhenUnicodeSupportNotIndicated() throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    buf.write("NTLMSSP".getBytes(StandardCharsets.US_ASCII));
    buf.write(0);//from w  ww .  j  a  va 2 s .  com
    // type 2 indicator
    buf.write(2);
    buf.write(0);
    buf.write(0);
    buf.write(0);

    buf.write(longToBytes(1L)); // we want to write a Long

    // flags
    buf.write(0);// unicode support indicator
    buf.write(0);
    buf.write(0);
    buf.write(0);

    buf.write(longToBytes(1L));// challenge
    NtlmEngine engine = new NtlmEngine();
    engine.generateType3Msg("username", "password", "localhost", "workstation",
            Base64.encode(buf.toByteArray()));
    buf.close();
    fail("An NtlmEngineException must have occurred as unicode support is not indicated");
}