Java Code Examples for java.nio.charset.StandardCharsets.US_ASCII

The following are Jave code examples for showing how to use US_ASCII of the java.nio.charset.StandardCharsets class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: influx-jmh-reporter   File: CommandLineArgs.java   Source Code and License Vote up 6 votes
private static String getHostName()
{
    String hostname = System.getenv().get("HOSTNAME");
    if (hostname == null)
    {
        try
        {
            final Process hostnameProcess = Runtime.getRuntime().exec("hostname");
            final String processOutput = new String(IOUtils.readFully(hostnameProcess.getInputStream(), Integer.MAX_VALUE, false), StandardCharsets.US_ASCII);
            hostname = processOutput.replace("\n", "").replace("\r", "").trim();
        }
        catch (final IOException ignored)
        {
            //ignored
        }
    }
    return hostname;
}
 
Example 2
Project: SilkAppDriver   File: JtfReplaySession.java   Source Code and License Vote up 6 votes
private String captureBitmap(TestObject object) {
	File tempFile;
	try {
		tempFile = File.createTempFile("SilkAppDriver", ".png");
		object.captureBitmap(tempFile.getAbsolutePath());

		byte[] encoded = Base64.encodeBase64(FileUtils.readFileToByteArray(tempFile));

		Files.delete(tempFile.toPath());

		return new String(encoded, StandardCharsets.US_ASCII);
	} catch (IOException e) {
		e.printStackTrace();
	}

	return null;
}
 
Example 3
Project: bytes-java   File: Base64.java   Source Code and License Vote up 6 votes
private static String encode(byte[] in, byte[] map) {
    int length = (in.length + 2) / 3 * 4;
    byte[] out = new byte[length];
    int index = 0, end = in.length - in.length % 3;
    for (int i = 0; i < end; i += 3) {
        out[index++] = map[(in[i] & 0xff) >> 2];
        out[index++] = map[((in[i] & 0x03) << 4) | ((in[i + 1] & 0xff) >> 4)];
        out[index++] = map[((in[i + 1] & 0x0f) << 2) | ((in[i + 2] & 0xff) >> 6)];
        out[index++] = map[(in[i + 2] & 0x3f)];
    }
    switch (in.length % 3) {
        case 1:
            out[index++] = map[(in[end] & 0xff) >> 2];
            out[index++] = map[(in[end] & 0x03) << 4];
            out[index++] = '=';
            out[index++] = '=';
            break;
        case 2:
            out[index++] = map[(in[end] & 0xff) >> 2];
            out[index++] = map[((in[end] & 0x03) << 4) | ((in[end + 1] & 0xff) >> 4)];
            out[index++] = map[((in[end + 1] & 0x0f) << 2)];
            out[index++] = '=';
            break;
    }
    return new String(out, StandardCharsets.US_ASCII);
}
 
Example 4
Project: influx-jmh-reporter   File: FileReader.java   Source Code and License Vote up 5 votes
String readFile(final String file)
{
    try
    {
        return new String(Files.readAllBytes(Paths.get(file)), StandardCharsets.US_ASCII);
    }
    catch (final IOException e)
    {
        throw new UncheckedIOException(e);
    }
}
 
Example 5
Project: bach   File: JdkToolTests.java   Source Code and License Vote up 5 votes
@Test
void dumpJavacOptions() {
  List<String> expectedLines =
      List.of(
          "javac",
          "--class-path",
          "  classes",
          "-g",
          "-deprecation",
          "-d",
          "  out",
          "-encoding",
          "  US-ASCII",
          "-Werror",
          "--patch-module",
          "  foo=bar",
          "--module-path",
          "  mods",
          "--module-source-path",
          "  src",
          "-parameters",
          "-verbose",
          ">> many .java files >>");
  Bach.JdkTool.Javac javac = new Bach.JdkTool.Javac();
  javac.generateAllDebuggingInformation = true;
  javac.deprecation = true;
  javac.destination = Paths.get("out");
  javac.encoding = StandardCharsets.US_ASCII;
  javac.failOnWarnings = true;
  javac.parameters = true;
  javac.verbose = true;
  javac.classPath = List.of(Paths.get("classes"));
  javac.classSourcePath = List.of(Paths.get("src/build"));
  javac.moduleSourcePath = List.of(Paths.get("src"));
  javac.modulePath = List.of(Paths.get("mods"));
  javac.patchModule = Map.of("foo", List.of(Paths.get("bar")));
  assertLinesMatch(expectedLines, dump(javac.toCommand()));
}
 
Example 6
Project: tdb3   File: BuildR.java   Source Code and License Vote up 5 votes
public static ColumnFamilyHandle findHandle(RocksTDB db, ColumnFamilyDescriptor columnFamilyDescriptor) {
    String n = new String(columnFamilyDescriptor.columnFamilyName(), StandardCharsets.US_ASCII);
    ColumnFamilyDescriptor cfd = BuildR.families.get(n);
    int i = db.descriptors.indexOf(cfd);
    if ( i < 0 )
        throw new InternalErrorException();
    
    ColumnFamilyHandle h = db.cfHandles.get(i);
    return h ;
}
 
Example 7
Project: java-course   File: ClientWorker.java   Source Code and License Vote up 5 votes
/**
 * Reads HTTP request and splits it into list of lines.
 * 
 * @return HTTP request lines.
 * @throws IOException
 *             On request reading.
 */
private List<String> getRequest() throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int ch;
    while ((ch = istream.read()) != -1) {
        if (ch != 13 && ch != 10) {
            bos.write(ch);
        } else if (ch == 13) {
            byte[] chars = new byte[STREAM_BUFFER_SIZE];
            istream.read(chars);
            if (chars[0] == 10 && chars[1] == 13 && chars[2] == 10) {
                bos.write(10);
                bos.write(10);
                break;
            }
            istream.unread(chars);
        } else if (ch == 10) {
            bos.write(ch);
            int ch1 = istream.read();
            if (ch1 == 10) {
                bos.write(ch1);
                break;
            }
            istream.unread(ch1);
        }
    }

    if (bos.size() == 0 || ch == -1) {
        return null;
    }
    String request = new String(bos.toByteArray(),
            StandardCharsets.US_ASCII);
    return Arrays.asList(request.split("\n"));
}
 
Example 8
Project: openjdk-jdk10   File: Http2TestServerConnection.java   Source Code and License Vote up 5 votes
String readHttp1Request() throws IOException {
    String headers = readUntil(CRLF + CRLF);
    int clen = getContentLength(headers);
    // read the content.
    byte[] buf = new byte[clen];
    is.readNBytes(buf, 0, clen);
    String body = new String(buf, StandardCharsets.US_ASCII);
    return headers + body;
}
 
Example 9
Project: ServerBrowser   File: FavouritesController.java   Source Code and License Vote up 5 votes
/**
 * TODO (Marcel 13.01.2018) I am still not using this ... why
 *
 * @return the List of all SampServers that the legacy favourite file contains.
 */
public static List<SampServer> retrieveLegacyFavourites() {
	final List<SampServer> legacyFavourites = new ArrayList<>();

	try {
		final byte[] data = Files.readAllBytes(Paths.get(PathConstants.SAMP_USERDATA));
		final ByteBuffer buffer = ByteBuffer.wrap(data);
		buffer.order(ByteOrder.LITTLE_ENDIAN);

		// Skiping trash at the beginning
		buffer.position(buffer.position() + 8);

		final int serverCount = buffer.getInt();
		for (int i = 0; i < serverCount; i++) {
			final byte[] ipBytes = new byte[buffer.getInt()];
			buffer.get(ipBytes);
			final String ip = new String(ipBytes, StandardCharsets.US_ASCII);

			final int port = buffer.getInt();

			/* Skip unimportant stuff */
			int skip = buffer.getInt(); // Hostname
			buffer.position(buffer.position() + skip);
			skip = buffer.getInt(); // Rcon pw
			buffer.position(buffer.position() + skip);
			skip = buffer.getInt(); // Server pw
			buffer.position(buffer.position() + skip);

			legacyFavourites.add(new SampServer(ip, port));
		}

		return legacyFavourites;
	}
	catch (final IOException exception) {
		Logging.warn("Error loading legacy favourites.", exception);
		return legacyFavourites;
	}
}
 
Example 10
Project: sstable-adaptor   File: AsciiSerializer.java   Source Code and License Vote up 4 votes
private AsciiSerializer()
{
    super(StandardCharsets.US_ASCII);
}
 
Example 11
Project: Matcher   File: MappingReader.java   Source Code and License Vote up 4 votes
public static void read(Path file, MappingFormat format, IMappingAcceptor mappingAcceptor) throws IOException {
	if (format == null) {
		if (Files.isDirectory(file)) {
			format = MappingFormat.ENIGMA;
		} else {
			try (SeekableByteChannel channel = Files.newByteChannel(file)) {
				byte[] header = new byte[3];
				ByteBuffer buffer = ByteBuffer.wrap(header);

				while (buffer.hasRemaining()) {
					if (channel.read(buffer) == -1) throw new IOException("invalid/truncated tiny mapping file");
				}

				if (header[0] == (byte) 0x1f && header[1] == (byte) 0x8b && header[2] == (byte) 0x08) { // gzip with deflate header
					format = MappingFormat.TINY_GZIP;
				} else if ((header[0] & 0xff) < 0x80 && (header[1] & 0xff) < 0x80 && (header[2] & 0xff) < 0x80) {
					String headerStr = new String(header, StandardCharsets.US_ASCII);

					switch (headerStr) {
					case "v1\t":
						format = MappingFormat.TINY;
						break;
					case "PK:":
					case "CL:":
					case "MD:":
					case "FD:":
						format = MappingFormat.SRG;
						break;
					default:
						throw new IOException("invalid/unsupported mapping format");
					}
				} else {
					throw new IOException("invalid/unsupported mapping format");
				}
			}
		}
	}

	switch (format) {
	case TINY:
		readtiny(file, mappingAcceptor);
		break;
	case TINY_GZIP:
		readGztiny(file, mappingAcceptor);
		break;
	case ENIGMA:
		readEnigma(file, mappingAcceptor);
		break;
	case MCP:
		readMcp(file, mappingAcceptor);
		break;
	case SRG:
		readSrg(file, mappingAcceptor);
		break;
	default:
		throw new IllegalStateException();
	}
}
 
Example 12
Project: URTorrent   File: PeerWireConnection.java   Source Code and License Vote up 4 votes
/**
	 * r Validates an incoming handshake message from the remote peer on this
	 * connection.
	 * 
	 * @throws IOException
	 *             if an error occurs when reading from this connection's
	 *             {@link #java.nio.channels.SocketChannel} or if handshake message
	 *             is invalid.
	 */
	public synchronized void verifyHandshake() throws IOException {
		// ByteBuffer recvData = ByteBuffer.allocate(49 + PSTRLEN);
//		System.out.println("Are we blocking: " + clientSocketChannel.isBlocking());
//		System.out.println("Are we connected: " + clientSocketChannel.isConnected());
		ByteBuffer recvData = ByteBuffer.allocate(49 + PSTRLEN);

		recvData.limit(1);
		clientSocketChannel.read(recvData);
		recvData.rewind();
		byte recvPSTRLEN = recvData.get();
		recvData.mark();
		if (recvPSTRLEN != PSTRLEN) {// If the length does not match the length specified by the project
										// specifications, then the handshake is invalid.
			throw new PeerWireProtocolException("Received invalid PSTRLEN: " + Byte.toUnsignedInt(recvPSTRLEN));
		}
		recvData.limit(PSTRLEN + recvData.limit());

		byte[] recvPSTR = new byte[PSTRLEN];
		clientSocketChannel.read(recvData);
		recvData.reset();
		recvData.get(recvPSTR);
		if (!Arrays.equals(PSTR, recvPSTR)) {// If the protocol name does not match the name specified by the project
												// specifications, then the handshake is invalid.
			throw new PeerWireProtocolException(
					"Recieved invalid PSTR: " + new String(recvPSTR, StandardCharsets.US_ASCII));
		}
		recvData.limit(28 + recvData.limit());

		clientSocketChannel.read(recvData);

		if (!sentHandshake)
			sendHandshake();// Project instructions indicate the the response handshake be sent immediate
							// after reading the bytes of the info_hash, so send the response even before
							// checking the contents of said info_hash.
		recvData.position(recvData.position() - 20);
		byte[] recvInfoHash = new byte[20];
		recvData.get(recvInfoHash);

		if (!Arrays.equals(MetaInfo.INFO_HASH, recvInfoHash)) {// If the info_hash received does not match the info_hash
																// stored in this client, then the handshake is invalid.
			throw new PeerWireProtocolException(
					"Received invalid info_hash: " + Hex.encodeHexString(recvInfoHash, true));
		}
		recvData.mark();
		recvData.limit(recvData.limit() + 20);
		byte[] recvPeerID = new byte[20];
		clientSocketChannel.read(recvData);
		recvData.reset();
		recvData.get(recvPeerID);
		remotePeerID = Hex.encodeHexString(recvPeerID, true);
		// TODO any other processing or what to do with the clientID.
	}
 
Example 13
Project: IO   File: HeaderSection.java   Source Code and License Vote up 4 votes
@Override
protected String getBytesAsString(byte[] bytes) {
   	return new String(bytes, StandardCharsets.US_ASCII);
   }
 
Example 14
Project: IO   File: ByteUtils.java   Source Code and License Vote up 4 votes
public static Map<Integer, String> printableSpansWithIndexes(byte[] bytes, int minLength, boolean filterRandom, int randomThreshold) {

        Map<Integer, String> spanPairs = new HashMap<>();
        int[] table = new int[bytes.length];
        int tableSize = 0;
        int strStart, strSize;
        byte[] byteSpan;
        String span;


        for (int i = 0; i < bytes.length; i++)
        {
            if (!isPrintable(bytes[i]))
            {
                table[tableSize++] = i;
            }
        }

        for (int j = 1; j < tableSize; j++)
        {
            if (table[j] == 0)
            {
                continue;
            }

            strStart = table[j - 1] + 1;
            strSize = table[j] - strStart;

            if (strSize < minLength)
            {
                continue;
            }


            byteSpan = Arrays.copyOfRange(bytes, strStart, strStart + strSize);
            span = new String(byteSpan, StandardCharsets.US_ASCII);
            spanPairs.put(strStart, span);
        }

        if (filterRandom)
        {
            //TODO: Bother with this?
            return spanPairs;
        }
        else
        {
            return spanPairs;
        }
    }
 
Example 15
Project: datarouter   File: StringByteTool.java   Source Code and License Vote up 4 votes
@Test
public void testAsciiExtensions(){
	Assert.assertTrue(unknownCharacterInt.equals(65533));

	for(int i = 0; i < 256; ++i){
		String ascii = new String(new byte[]{ByteTool.fromUnsignedInt0To255(i)}, StandardCharsets.US_ASCII);

		String latin1 = new String(new byte[]{ByteTool.fromUnsignedInt0To255(i)},
				StandardCharsets.ISO_8859_1);

		String windows1252 = new String(new byte[]{ByteTool.fromUnsignedInt0To255(i)}, Charset.forName(
				"windows-1252"));

		String utf16be = new String(new byte[]{(byte)0, ByteTool.fromUnsignedInt0To255(i)},
				StandardCharsets.UTF_16BE);

		String utf8 = new String(new byte[]{ByteTool.fromUnsignedInt0To255(i)}, StandardCharsets.UTF_8);

		if(i < 0x80){
			Assert.assertEquals(latin1, ascii);
			Assert.assertEquals(windows1252, latin1);
			Assert.assertEquals(utf16be, windows1252);
			Assert.assertEquals(utf8, utf16be);
		}else if(i < 160){
			Assert.assertEquals(unknownCharacter.toString(), ascii);// invalid octet
			Assert.assertEquals(latin1.charAt(0), i);// valid octet, but not not mapped to any character
			Assert.assertTrue(StringTool.notEmpty(windows1252));
			Assert.assertTrue(latin1.equals(utf16be));
			Assert.assertTrue(!windows1252.equals(utf16be));
			Assert.assertEquals(unknownCharacter.toString(), utf8);// utf8 will expect 2 bytes here, so our 1
																	// byte is junk
		}else{
			Assert.assertEquals(unknownCharacter.toString(), ascii);// invalid octet
			Assert.assertTrue(StringTool.notEmpty(latin1));
			Assert.assertTrue(StringTool.notEmpty(windows1252));
			Assert.assertEquals(windows1252, latin1);
			Assert.assertEquals(utf16be, windows1252);
			Assert.assertEquals(unknownCharacter.toString(), utf8);// utf8 will expect 2 bytes here, so our 1
																	// byte is junk
		}
	}
}
 
Example 16
Project: libsodium-jna   File: SodiumLibrary.java   Source Code and License Vote up 4 votes
/**
* Returns a US-ASCII encoded key derived from the password.
* 
* The key can be stored for verification. Memory-hard, CPU-intensive hash function is applied to the  
* password in key generation process. Automatically generated salt is used in the key generation
* Uses opslimit as <code>crypto_pwhash_opslimit_interactive()</code> and memlimit as 
* <code>crypto_pwhash_memlimit_interactive()</code>
* @param password The password 
* @throws SodiumLibraryException on error
* @return derived key as US-ASCII encoded string
* <h3>Example</h3>
* <pre>
* <code>
*  String password = new String("বাংলা");
*  // convert to UTF-8 encoded bytes
*  byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8); // requires jdk 1.7+
*  String key = SodiumLibrary.cryptoPwhashStr(passwordBytes);
* </code>
* </pre>
*/
public static String cryptoPwhashStr(byte[] password) throws SodiumLibraryException
{
    byte[] hashedPassword = new byte[sodium().crypto_pwhash_strbytes()];
    int rc = sodium().crypto_pwhash_str(hashedPassword,
            password, password.length,
            sodium().crypto_pwhash_opslimit_interactive(),
            sodium().crypto_pwhash_memlimit_interactive());
    if (rc != 0)
    {
        throw new SodiumLibraryException("libsodium crypto_pwhash_str failed, returned " + rc + ", expected 0");
    }
    String usAscii = new String(hashedPassword,StandardCharsets.US_ASCII);

    return usAscii;
}
 
Example 17
Project: openjdk-jdk10   File: Utils.java   Source Code and License Vote up 4 votes
static String asString(ByteBuffer buf) {
    byte[] b = new byte[buf.remaining()];
    buf.get(b);
    return new String(b, StandardCharsets.US_ASCII);
}
 
Example 18
Project: OpenJSharp   File: Source.java   Source Code and License Vote up 2 votes
/**
 * Get a Base64-encoded SHA1 digest for this source.
 *
 * @return a Base64-encoded SHA1 digest for this source
 */
public String getDigest() {
    return new String(getDigestBytes(), StandardCharsets.US_ASCII);
}
 
Example 19
Project: openjdk-jdk10   File: Source.java   Source Code and License Vote up 2 votes
/**
 * Get a Base64-encoded SHA1 digest for this source.
 *
 * @return a Base64-encoded SHA1 digest for this source
 */
public String getDigest() {
    return new String(getDigestBytes(), StandardCharsets.US_ASCII);
}