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:io.anserini.search.SearchWebCollection.java

/**
 * Prints TREC submission file to the standard output stream.
 *
 * @param topics     queries// w  w w  . j  a va  2  s  .com
 * @param similarity similarity
 * @throws IOException
 * @throws ParseException
 */

public void search(SortedMap<Integer, String> topics, String submissionFile, Similarity similarity, int numHits,
        RerankerCascade cascade, boolean useQueryParser, boolean keepstopwords)
        throws IOException, ParseException {

    IndexSearcher searcher = new IndexSearcher(reader);
    searcher.setSimilarity(similarity);

    final String runTag = "BM25_EnglishAnalyzer_" + (keepstopwords ? "KeepStopwords_" : "") + FIELD_BODY + "_"
            + similarity.toString();

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

    EnglishAnalyzer ea = keepstopwords ? new EnglishAnalyzer(CharArraySet.EMPTY_SET) : new EnglishAnalyzer();
    QueryParser queryParser = new QueryParser(FIELD_BODY, ea);
    queryParser.setDefaultOperator(QueryParser.Operator.OR);

    for (Map.Entry<Integer, String> entry : topics.entrySet()) {

        int qID = entry.getKey();
        String queryString = entry.getValue();
        Query query = useQueryParser ? queryParser.parse(queryString)
                : AnalyzerUtils.buildBagOfWordsQuery(FIELD_BODY, ea, queryString);

        /**
         * For Web Tracks 2010,2011,and 2012; an experimental run consists of the top 10,000 documents for each topic query.
         */
        TopDocs rs = searcher.search(query, numHits);
        ScoreDoc[] hits = rs.scoreDocs;
        List<String> queryTokens = AnalyzerUtils.tokenize(ea, queryString);
        RerankerContext context = new RerankerContext(searcher, query, String.valueOf(qID), queryString,
                queryTokens, FIELD_BODY, null);
        ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher), context);

        /**
         * 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("%d Q0 %s %d %f %s", qID,
                    docs.documents[i].getField(FIELD_ID).stringValue(), (i + 1), docs.scores[i], runTag));
        }
    }
    out.flush();
    out.close();
}

From source file:com.joyent.manta.client.multipart.EncryptedMultipartManagerTest.java

public void canDoMultipartUpload() throws Exception {
    MantaMetadata metadata = new MantaMetadata();
    metadata.put("m-my-key", "my value");
    metadata.put("e-my-key-1", "my value 1");
    metadata.put("e-my-key-2", "my value 2");

    MantaHttpHeaders headers = new MantaHttpHeaders();

    String path = "/user/stor/testobject";

    EncryptedMultipartUpload<TestMultipartUpload> upload = manager.initiateUpload(path, 35L, metadata, headers);

    ArrayList<String> lines = new ArrayList<>();
    lines.add("01234567890ABCDEF|}{");
    lines.add("ZYXWVUTSRQPONMLKJIHG");
    lines.add("!@#$%^&*()_+-=[]/,.<");
    lines.add(">~`?abcdefghijklmnop");
    lines.add("qrstuvxyz");

    String expected = StringUtils.join(lines, "");

    MantaMultipartUploadPart[] parts = new MantaMultipartUploadPart[5];

    for (int i = 0; i < lines.size(); i++) {
        parts[i] = manager.uploadPart(upload, i + 1, lines.get(i));
    }/*from  w  w  w.j a va 2  s. c om*/

    Stream<MantaMultipartUploadTuple> partsStream = Stream.of(parts);

    manager.complete(upload, partsStream);

    TestMultipartUpload actualUpload = upload.getWrapped();

    MantaMetadata actualMetadata = MantaObjectMapper.INSTANCE.readValue(actualUpload.getMetadata(),
            MantaMetadata.class);

    Assert.assertEquals(actualMetadata, metadata, "Metadata wasn't stored correctly");

    MantaHttpHeaders actualHeaders = MantaObjectMapper.INSTANCE.readValue(actualUpload.getHeaders(),
            MantaHttpHeaders.class);

    Assert.assertEquals(actualHeaders, headers, "Headers were stored correctly");

    {
        Cipher cipher = cipherDetails.getCipher();
        byte[] iv = upload.getEncryptionState().getEncryptionContext().getCipher().getIV();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv));

        byte[] assumedCiphertext = cipher.doFinal(expected.getBytes(StandardCharsets.US_ASCII));
        byte[] contents = FileUtils.readFileToByteArray(upload.getWrapped().getContents());
        byte[] actualCiphertext = Arrays.copyOf(contents,
                contents.length - cipherDetails.getAuthenticationTagOrHmacLengthInBytes());

        try {
            AssertJUnit.assertEquals(assumedCiphertext, actualCiphertext);
        } catch (AssertionError e) {
            System.err.println("expected: " + Hex.encodeHexString(assumedCiphertext));
            System.err.println("actual  : " + Hex.encodeHexString(actualCiphertext));
            throw e;
        }
    }

    EncryptionContext encryptionContext = upload.getEncryptionState().getEncryptionContext();

    MantaHttpHeaders responseHttpHeaders = new MantaHttpHeaders();
    responseHttpHeaders.setContentLength(actualUpload.getContents().length());

    final String hmacName = SupportedHmacsLookupMap
            .hmacNameFromInstance(encryptionContext.getCipherDetails().getAuthenticationHmac());

    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_HMAC_TYPE, hmacName);
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_IV,
            Base64.getEncoder().encodeToString(encryptionContext.getCipher().getIV()));
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_KEY_ID, cipherDetails.getCipherId());

    MantaObjectResponse response = new MantaObjectResponse(path, responseHttpHeaders, metadata);

    CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);

    try (InputStream fin = new FileInputStream(actualUpload.getContents());
            EofSensorInputStream eofIn = new EofSensorInputStream(fin, null);
            MantaObjectInputStream objIn = new MantaObjectInputStream(response, httpResponse, eofIn);
            InputStream in = new MantaEncryptedObjectInputStream(objIn, cipherDetails, secretKey, true)) {
        String actual = IOUtils.toString(in, StandardCharsets.UTF_8);

        Assert.assertEquals(actual, expected);
    }
}

From source file:com.kibana.multitenancy.plugin.KibanaUserReindexFilter.java

private String getUser(RestRequest request) {
    //Sushant:Getting user in case of Basic Authentication
    String username = "";
    //Sushant:Scenario when user Authenticated at Proxy level itself
    String proxyAuthUser = StringUtils.defaultIfBlank(request.header(proxyUserHeader), "");
    //Sushant: Scenario when user Authenticated at Proxy level itself

    String basicAuthorizationHeader = StringUtils.defaultIfBlank(request.header("Authorization"), "");
    if (StringUtils.isNotEmpty(basicAuthorizationHeader)) {
        String decodedBasicHeader = new String(
                DatatypeConverter.parseBase64Binary(basicAuthorizationHeader.split(" ")[1]),
                StandardCharsets.US_ASCII);
        final String[] decodedBasicHeaderParts = decodedBasicHeader.split(":");
        username = decodedBasicHeaderParts[0];
        decodedBasicHeader = null;//from  w w w  .j a v  a  2  s.co  m
        basicAuthorizationHeader = null;
        logger.debug("User '{}' is authenticated", username);
    }
    return username;
}

From source file:com.acciente.oacc.encryptor.jasypt.PasswordEncoderDecoder.java

/**
 * Decodes a previously encoded Jasypt password into its constituent parts (algorithm, iterations, salt size, digest).
 *
 * @param encodedPassword an encoded password that was previously returned by
 *                        {{@link #encode(String, int, int, byte[])}}.
 * @return an object containing the decoded parts of the password (algorithm, iterations, salt size, digest).
 *//* www  . j av a2 s .c  om*/
DecodedPassword decode(String encodedPassword) {
    if (encodedPassword.startsWith(MARKER)) {
        final String[] decodedPasswordArray = encodedPassword.substring(MARKER.length())
                .split(QUOTED_PARAM_DELIMITER);

        if (decodedPasswordArray.length != DECODED_PASSWORD_ARRAY_COUNT) {
            throw new IllegalArgumentException(
                    "Unexpected format for Jasypt password: " + encodedPassword.substring(0, MARKER.length()));
        }

        final String algorithm;
        final int iterations;
        final int saltSizeBytes;
        final byte[] digest;

        algorithm = decodedPasswordArray[DECODED_PASSWORD_ARRAY_ALGORITHM];
        try {
            iterations = Integer.parseInt(decodedPasswordArray[DECODED_PASSWORD_ARRAY_ITERATIONS]);
            saltSizeBytes = Integer.parseInt(decodedPasswordArray[DECODED_PASSWORD_ARRAY_SALT_SIZE_BYTES]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(
                    "Unexpected value in Jasypt password header for iterations and/or salt size: "
                            + encodedPassword);
        }
        digest = base64.decode(
                decodedPasswordArray[DECODED_PASSWORD_ARRAY_DIGEST].getBytes(StandardCharsets.US_ASCII));

        return new DecodedPassword.Builder().algorithm(algorithm).iterations(iterations)
                .saltSizeBytes(saltSizeBytes).digest(digest).build();
    } else {
        throw new IllegalArgumentException(
                "Unexpected marker for Jasypt password: " + encodedPassword.substring(0, MARKER.length()));
    }
}

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

public AuthenticationToken(final String base64EncodedToken) {
    this.base64EncodedToken = base64EncodedToken;

    final String[] pieces = this.base64EncodedToken.split("\\.");

    if (pieces.length != 3) {
        throw new IllegalArgumentException();
    }/*from   w ww  .j av  a 2  s  . c  om*/

    this.header = GSON.fromJson(new String(Base64.decodeBase64(pieces[0]), StandardCharsets.US_ASCII),
            AuthenticationTokenHeader.class);
    this.claims = GSON.fromJson(new String(Base64.decodeBase64(pieces[1]), StandardCharsets.US_ASCII),
            AuthenticationTokenClaims.class);
    this.signatureBytes = Base64.decodeBase64(pieces[2]);
}

From source file:aiai.ai.station.LaunchpadRequester.java

/**
 * this scheduler is being run at the station side
 *
 * long fixedDelay()//  w  ww .jav  a 2  s.  co  m
 * Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
 */
public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;
    }
    if (!globals.isStationEnabled) {
        return;
    }

    ExchangeData data = new ExchangeData();
    String stationId = stationService.getStationId();
    if (stationId == null) {
        data.setCommand(new Protocol.RequestStationId());
    }
    data.setStationId(stationId);

    if (stationId != null) {
        // always report about current active sequences, if we have actual stationId
        data.setCommand(stationTaskService.produceStationSequenceStatus());
        data.setCommand(stationService.produceReportStationStatus());
        final boolean b = stationTaskService.isNeedNewExperimentSequence(stationId);
        if (b) {
            data.setCommand(new Protocol.RequestTask(globals.isAcceptOnlySignedSnippets));
        }
        if (System.currentTimeMillis() - lastRequestForMissingResources > 15_000) {
            data.setCommand(new Protocol.CheckForMissingOutputResources());
            lastRequestForMissingResources = System.currentTimeMillis();
        }
    }

    reportSequenceProcessingResult(data);

    List<Command> cmds;
    synchronized (commands) {
        cmds = new ArrayList<>(commands);
        commands.clear();
    }
    data.setCommands(cmds);

    // !!! always use data.setCommand() for correct initializing stationId !!!

    // we have to pull new tasks from server constantly
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (globals.isSecureRestUrl) {
            String auth = globals.restUsername + '=' + globals.restToken + ':' + globals.stationRestPassword;
            byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.US_ASCII));
            String authHeader = "Basic " + new String(encodedAuth);
            headers.set("Authorization", authHeader);
        }

        HttpEntity<ExchangeData> request = new HttpEntity<>(data, headers);

        ResponseEntity<ExchangeData> response = restTemplate.exchange(globals.serverRestUrl, HttpMethod.POST,
                request, ExchangeData.class);
        ExchangeData result = response.getBody();

        addCommands(commandProcessor.processExchangeData(result).getCommands());
        log.debug("fixedDelay(), {}", result);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            log.error("Error 401 accessing url {}, globals.isSecureRestUrl: {}", globals.serverRestUrl,
                    globals.isSecureRestUrl);
        } else {
            throw e;
        }
    } catch (RestClientException e) {
        log.error("Error accessing url: {}", globals.serverRestUrl);
        log.error("Stacktrace", e);
    }
}

From source file:net.rptools.gui.GuiBuilder.java

/** Fill in all fields we know of. */
@ThreadPolicy(ThreadPolicy.ThreadId.JFX)
private void fillIn() {
    final String server = component.getFramework().getState("server");
    if (server != null) {
        final String[] serverParams = server.split(":");
        ((TextInputControl) component.lookup("#networkServer")).setText(serverParams[0]);
        ((TextInputControl) component.lookup("#networkPort")).setText(serverParams[1]);
    }/*from w w  w  .  ja v a2s .  c  om*/
    final String login = component.getFramework().getState("login");
    if (login != null) {
        final String[] loginParams = login.split("/");
        ((TextInputControl) component.lookup("#networkUser")).setText(loginParams[0]);
    }
    try {
        ((TextInputControl) component.lookup("#networkLocalIP"))
                .setText(InetAddress.getLocalHost().getHostAddress().toString());
    } catch (final UnknownHostException e) {
        LOGGER.error("InetAddress.getLocalHost", e);
    }

    component.getFramework().submit(new Runnable() {
        @Override
        public void run() {
            try {
                final URL url = new URL("http://icanhazip.com/");
                final URLConnection con = (URLConnection) url.openConnection();

                try (final BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream(), StandardCharsets.US_ASCII))) {
                    final String response = in.readLine();
                    ((TextInputControl) component.lookup("#networkRemoteIP")).setText(response);
                }
            } catch (final IOException e) {
                LOGGER.error("No result from http://icanhazip.com/", e);
            }
        }
    });

    AssetConnector.connect("#penTexture", PATTERN, component);
    AssetConnector.connect("#fillTexture", PATTERN, component);
}

From source file:org.apache.cloudstack.storage.configdrive.ConfigDriveBuilderTest.java

@Test
public void base64StringToFileTest() throws Exception {
    String encodedIsoData = "Y29udGVudA==";

    String parentFolder = "parentFolder";
    String fileName = "fileName";

    File parentFolderFile = new File(parentFolder);
    parentFolderFile.mkdir();/*from w w w.ja  v a2 s  .  c  om*/

    ConfigDriveBuilder.base64StringToFile(encodedIsoData, parentFolder, fileName);

    File file = new File(parentFolderFile, fileName);
    String contentOfFile = new String(FileUtils.readFileToByteArray(file), StandardCharsets.US_ASCII);

    Assert.assertEquals("content", contentOfFile);

    file.delete();
    parentFolderFile.delete();
}

From source file:nl.esciencecenter.osmium.mac.MacScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data/*w w w  .  ja va  2  s .com*/
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @param algorithm
 *            MAC algorithm implemented by javax.crypto.MAC
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws AuthenticationException
 *             when signature generation fails
 */
private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException {
    try {
        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec macKey = new SecretKeySpec(key.getBytes(StandardCharsets.US_ASCII), "RAW");
        mac.init(macKey);
        byte[] signature = mac.doFinal(data.getBytes(StandardCharsets.US_ASCII));
        return Base64.encodeBase64String(signature);
    } catch (InvalidKeyException e) {
        throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AuthenticationException("Algorithm is not supported", e);
    }
}

From source file:org.sonar.scanner.scan.filesystem.MetadataGeneratorTest.java

@Test
public void use_default_charset_if_detection_fails() throws IOException {
    Path tempFile = temp.newFile().toPath();
    byte[] b = { (byte) 0xDF, (byte) 0xFF, (byte) 0xFF };
    FileUtils.writeByteArrayToFile(tempFile.toFile(), b);
    DefaultInputFile inputFile = createInputFileWithMetadata(tempFile);
    assertThat(inputFile.charset()).isEqualTo(StandardCharsets.US_ASCII);
}