List of usage examples for java.nio.charset StandardCharsets US_ASCII
Charset US_ASCII
To view the source code for java.nio.charset StandardCharsets US_ASCII.
Click Source Link
From source file:org.apache.hc.client5.http.impl.auth.TestBasicScheme.java
@Test public void testBasicProxyAuthentication() throws Exception { final AuthChallenge authChallenge = parse("Basic realm=\"test\""); final BasicScheme authscheme = new BasicScheme(); authscheme.processChallenge(authChallenge, null); final HttpHost host = new HttpHost("somehost", 80); final AuthScope authScope = new AuthScope(host, "test", null); final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass".toCharArray()); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authScope, creds); final HttpRequest request = new BasicHttpRequest("GET", "/"); Assert.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null)); final String authResponse = authscheme.generateAuthResponse(host, request, null); final String expected = "Basic " + new String(Base64.encodeBase64("testuser:testpass".getBytes(StandardCharsets.US_ASCII)), StandardCharsets.US_ASCII); Assert.assertEquals(expected, authResponse); Assert.assertEquals("test", authscheme.getRealm()); Assert.assertTrue(authscheme.isChallengeComplete()); Assert.assertFalse(authscheme.isConnectionBased()); }
From source file:org.sonar.process.AllProcessesCommands.java
void setSystemInfoUrl(int processNumber, String url) { byte[] urlBytes = rightPad(url, SYSTEM_INFO_URL_SIZE_IN_BYTES).getBytes(StandardCharsets.US_ASCII); if (urlBytes.length > SYSTEM_INFO_URL_SIZE_IN_BYTES) { throw new IllegalArgumentException(format("System Info URL is too long. Max is %d bytes. Got: %s", SYSTEM_INFO_URL_SIZE_IN_BYTES, url)); }/*from ww w . jav a 2 s . c o m*/ writeBytes(processNumber, SYSTEM_INFO_URL_BYTE_OFFSET, urlBytes); }
From source file:com.cloudbees.plugins.credentials.SecretBytesTest.java
@Test public void largeRawString__noChunking__urlSafe() throws Exception { byte[] data = new byte[2048]; new Random().nextBytes(data); assertThat(SecretBytes// w w w .j a v a2 s. co m .fromString(new String(org.apache.commons.codec.binary.Base64.encodeBase64(data, false, true), StandardCharsets.US_ASCII)) .getPlainData(), is(data)); }
From source file:org.schedoscope.export.ftp.outputformat.FtpUploadOutputFormat.java
/** * A method to configure the output format. * * @param job The job object./*from w ww . j a v a 2 s. co m*/ * @param tableName The Hive input table name * @param printHeader A flag indicating to print a csv header or not. * @param delimiter The delimiter to use for separating the records (CSV) * @param fileType The file type (csv / json) * @param codec The compresson codec (none / gzip / bzip2) * @param ftpEndpoint The (s)ftp endpoint. * @param ftpUser The (s)ftp user * @param ftpPass The (s)ftp password or sftp passphrase * @param keyFile The private ssh key file * @param filePrefix An optional file prefix * @param passiveMode Passive mode or not (only ftp) * @param userIsRoot User dir is root or not * @param cleanHdfsDir Clean up HDFS temporary files. * @throws Exception Is thrown if an error occurs. */ public static void setOutput(Job job, String tableName, boolean printHeader, String delimiter, FileOutputType fileType, FileCompressionCodec codec, String ftpEndpoint, String ftpUser, String ftpPass, String keyFile, String filePrefix, boolean passiveMode, boolean userIsRoot, boolean cleanHdfsDir) throws Exception { Configuration conf = job.getConfiguration(); String tmpDir = conf.get("hadoop.tmp.dir"); String localTmpDir = RandomStringUtils.randomNumeric(10); setOutputPath(job, new Path(tmpDir, FTP_EXPORT_TMP_OUTPUT_PATH + localTmpDir)); conf.setInt(FileOutputCommitter.FILEOUTPUTCOMMITTER_ALGORITHM_VERSION, 2); conf.set(FTP_EXPORT_TABLE_NAME, tableName); conf.set(FTP_EXPORT_ENDPOINT, ftpEndpoint); conf.set(FTP_EXPORT_USER, ftpUser); if (ftpPass != null) { conf.set(FTP_EXPORT_PASS, ftpPass); } if (delimiter != null) { if (delimiter.length() != 1) { throw new IllegalArgumentException("delimiter must be exactly 1 char"); } conf.set(FTP_EXPORT_CVS_DELIMITER, delimiter); } if (keyFile != null && Files.exists(Paths.get(keyFile))) { // Uploader.checkPrivateKey(keyFile); String privateKey = new String(Files.readAllBytes(Paths.get(keyFile)), StandardCharsets.US_ASCII); conf.set(FTP_EXPORT_KEY_FILE_CONTENT, privateKey); } conf.setBoolean(FTP_EXPORT_PASSIVE_MODE, passiveMode); conf.setBoolean(FTP_EXPORT_USER_IS_ROOT, userIsRoot); conf.setBoolean(FTP_EXPORT_CLEAN_HDFS_DIR, cleanHdfsDir); DateTimeFormatter fmt = ISODateTimeFormat.basicDateTimeNoMillis(); String timestamp = fmt.print(DateTime.now(DateTimeZone.UTC)); conf.set(FTP_EXPORT_FILE_PREFIX, filePrefix + "-" + timestamp + "-"); if (printHeader) { conf.setStrings(FTP_EXPORT_HEADER_COLUMNS, setCSVHeader(conf)); } conf.set(FTP_EXPORT_FILE_TYPE, fileType.toString()); if (codec.equals(FileCompressionCodec.gzip)) { setOutputCompressorClass(job, GzipCodec.class); } else if (codec.equals(FileCompressionCodec.bzip2)) { setOutputCompressorClass(job, BZip2Codec.class); } else if (codec.equals(FileCompressionCodec.none)) { extension = ""; } }
From source file:org.sejda.sambox.output.DefaultCOSWriterTest.java
@Test public void visitCOSStream() throws Exception { byte[] data = new byte[] { (byte) 0x41, (byte) 0x42, (byte) 0x43 }; COSStream stream = new COSStream(); stream.setInt(COSName.B, 2);/*from w w w .j av a2 s . c o m*/ try (OutputStream out = stream.createUnfilteredStream()) { out.write(data); } InOrder inOrder = Mockito.inOrder(writer); victim.visit(stream); inOrder.verify(writer, times(2)).write((byte) 0x3C); inOrder.verify(writer).writeEOL(); inOrder.verify(writer).write((byte) 0x2F); inOrder.verify(writer).write((byte) 0x42); inOrder.verify(writer).write((byte) 0x20); inOrder.verify(writer).write("2"); inOrder.verify(writer).writeEOL(); inOrder.verify(writer).write((byte) 0x2F); inOrder.verify(writer).write((byte) 0x4C); inOrder.verify(writer).write((byte) 0x65); inOrder.verify(writer).write((byte) 0x6E); inOrder.verify(writer).write((byte) 0x67); inOrder.verify(writer).write((byte) 0x74); inOrder.verify(writer).write((byte) 0x68); inOrder.verify(writer).write((byte) 0x20); inOrder.verify(writer).write("3"); inOrder.verify(writer).writeEOL(); inOrder.verify(writer, times(2)).write((byte) 0x3E); inOrder.verify(writer).writeEOL(); inOrder.verify(writer).write(AdditionalMatchers.aryEq("stream".getBytes(StandardCharsets.US_ASCII))); inOrder.verify(writer).write(AdditionalMatchers.aryEq(new byte[] { '\r', '\n' })); inOrder.verify(writer).write(any(InputStream.class)); inOrder.verify(writer).write(AdditionalMatchers.aryEq(new byte[] { '\r', '\n' })); inOrder.verify(writer).write(AdditionalMatchers.aryEq("endstream".getBytes(StandardCharsets.US_ASCII))); inOrder.verify(writer).writeEOL(); }
From source file:com.joyent.manta.client.crypto.AesCtrCipherDetailsTest.java
protected void canRandomlyReadPlaintextPositionFromCiphertext(final SecretKey secretKey, final SupportedCipherDetails cipherDetails) throws IOException, GeneralSecurityException { String text = "A SERGEANT OF THE LAW, wary and wise, " + "That often had y-been at the Parvis, <26> " + "There was also, full rich of excellence. " + "Discreet he was, and of great reverence: " + "He seemed such, his wordes were so wise, " + "Justice he was full often in assize, " + "By patent, and by plein* commission; " + "For his science, and for his high renown, " + "Of fees and robes had he many one. " + "So great a purchaser was nowhere none. " + "All was fee simple to him, in effect " + "His purchasing might not be in suspect* " + "Nowhere so busy a man as he there was " + "And yet he seemed busier than he was " + "In termes had he case' and doomes* all " + "That from the time of King Will. were fall. " + "Thereto he could indite, and make a thing " + "There coulde no wight *pinch at* his writing. " + "And every statute coud* he plain by rote " + "He rode but homely in a medley* coat, " + "Girt with a seint* of silk, with barres small; " + "Of his array tell I no longer tale."; byte[] plaintext = text.getBytes(StandardCharsets.US_ASCII); ContentType contentType = ContentType.APPLICATION_OCTET_STREAM; ExposedByteArrayEntity entity = new ExposedByteArrayEntity(plaintext, contentType); EncryptingEntity encryptingEntity = new EncryptingEntity(secretKey, cipherDetails, entity); final byte[] ciphertext; final byte[] iv = encryptingEntity.getCipher().getIV(); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { encryptingEntity.writeTo(out);/*from ww w .jav a 2 s . c o m*/ ciphertext = Arrays.copyOf(out.toByteArray(), out.toByteArray().length - cipherDetails.getAuthenticationTagOrHmacLengthInBytes()); } for (long startPlaintextRange = 0; startPlaintextRange < plaintext.length - 1; startPlaintextRange++) { for (long endPlaintextRange = startPlaintextRange; endPlaintextRange < plaintext.length; endPlaintextRange++) { byte[] adjustedPlaintext = Arrays.copyOfRange(plaintext, (int) startPlaintextRange, (int) endPlaintextRange + 1); ByteRangeConversion ranges = cipherDetails.translateByteRange(startPlaintextRange, endPlaintextRange); long startCipherTextRange = ranges.getCiphertextStartPositionInclusive(); long endCipherTextRange = ranges.getCiphertextEndPositionInclusive(); long adjustedPlaintextLength = ranges.getLengthOfPlaintextIncludingSkipBytes(); Cipher decryptor = cipherDetails.getCipher(); decryptor.init(Cipher.DECRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv)); long adjustedPlaintextRange = cipherDetails.updateCipherToPosition(decryptor, startPlaintextRange); byte[] adjustedCipherText = Arrays.copyOfRange(ciphertext, (int) startCipherTextRange, (int) Math.min(ciphertext.length, endCipherTextRange + 1)); byte[] out = decryptor.doFinal(adjustedCipherText); byte[] decrypted = Arrays.copyOfRange(out, (int) adjustedPlaintextRange, (int) Math.min(out.length, adjustedPlaintextLength)); String decryptedText = new String(decrypted, StandardCharsets.UTF_8); String adjustedText = new String(adjustedPlaintext, StandardCharsets.UTF_8); Assert.assertEquals(adjustedText, decryptedText, "Random read output from ciphertext doesn't match expectation " + "[cipher=" + cipherDetails.getCipherId() + "]"); } } }
From source file:io.syndesis.rest.v1.state.ClientSideState.java
byte[] atime() { final long nowInSec = timeSource.getAsLong(); final String nowAsStr = Long.toString(nowInSec); return nowAsStr.getBytes(StandardCharsets.US_ASCII); }
From source file:com.cloudbees.plugins.credentials.SecretBytesTest.java
@Test public void largeRawString__chunking__urlSafe() throws Exception { byte[] data = new byte[2048]; new Random().nextBytes(data); assertThat(SecretBytes//from w ww.j av a 2 s.c om .fromString(new String(org.apache.commons.codec.binary.Base64.encodeBase64(data, true, true), StandardCharsets.US_ASCII)) .getPlainData(), is(data)); }
From source file:org.openhab.binding.jeelabs.internal.connector.JeeLinkSerialConnector.java
@Override public void serialEvent(SerialPortEvent arg0) { switch (arg0.getEventType()) { case SerialPortEvent.DATA_AVAILABLE: { byte[] readBuffer = new byte[40]; int byteCountRead = 0; try {/* w w w . j av a 2 s. c o m*/ while (_serialPort.getInputStream().available() > 0) { int numBytesRead = _serialPort.getInputStream().read(readBuffer); _messageBuffer.addBytes(readBuffer, numBytesRead); byteCountRead += numBytesRead; } //logger.debug("Done chunck of reads for this event callback (Read {} bytes)", byteCountRead); //Now see if there are any messages to pull out of the buffer we have JeeLinkMessage msg = _messageBuffer.getNextMessage(); while (msg != null) { if (!msg.isComment()) { try { _queue.put(msg); } catch (InterruptedException e) { } } else { logger.trace("Comment: {}", new String(msg.data(), StandardCharsets.US_ASCII).trim()); } //Try and find another message msg = _messageBuffer.getNextMessage(); } } catch (IOException e) { logger.debug("Exception reading {}", e); } } } }
From source file:com.kibana.multitenancy.plugin.acl.DynamicACLFilter.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 = (String) ObjectUtils.defaultIfNull(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. ja v a2 s .c om*/ basicAuthorizationHeader = null; logger.debug("User '{}' is authenticated", username); } return username; }