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

The following examples show how to use java.nio.charset.StandardCharsets#US_ASCII . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MiscUtils.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Description("Returns a string with random printable ASCII characters.<br/>"
           + "<b>length</b> - the length of the result string.<br/>"
           + "Example:<br/>"
           + "#{GetRandomString(23)}")
@UtilityMethod
public String GetRandomString(int length)
{
       byte[] asciiBytes = new byte[length];

       // range for printable symbols except 'space'(32)
       int range = 127 - 33;

       for(int i = 0; i < length; i++) {
           asciiBytes[i] = (byte)(33 + (Math.random() * range));
       }

       return new String(asciiBytes, StandardCharsets.US_ASCII);
}
 
Example 2
Source File: DefaultMultipartMessageReader.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Convert the given data buffer into a {@link HttpHeaders} instance. The given string is read
 * as US-ASCII, then split along \r\n line boundaries, each line containing a header name and
 * value(s).
 */
private static HttpHeaders toHeaders(DataBuffer dataBuffer) {
	byte[] bytes = new byte[dataBuffer.readableByteCount()];
	dataBuffer.read(bytes);
	DataBufferUtils.release(dataBuffer);
	String string = new String(bytes, StandardCharsets.US_ASCII);
	String[] lines = string.split(HEADER_SEPARATOR);
	HttpHeaders result = new HttpHeaders();
	for (String line : lines) {
		int idx = line.indexOf(':');
		if (idx != -1) {
			String name = line.substring(0, idx);
			String value = line.substring(idx + 1);
			while (value.startsWith(" ")) {
				value = value.substring(1);
			}
			String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
			for (String token : tokens) {
				result.add(name, token);
			}
		}
	}
	return result;
}
 
Example 3
Source File: ByteReader.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Read a String from the provided number of bytes
 *
 * @param offset byte offset
 * @param num number of bytes
 * @return String
 * @throws UnsupportedEncodingException
 */
public String readString(int offset, int num)
        throws UnsupportedEncodingException {
    verifyRemainingBytes(offset, num);
    String value = null;
    if (num != 1 || bytes[offset] != 0) {
        value = new String(bytes, offset, num, StandardCharsets.US_ASCII);
    }
    return value;
}
 
Example 4
Source File: EncryptionUtil.java    From CapturePacket with MIT License 5 votes vote down vote up
/**
 * Convenience method to read PEM data from a file. The file encoding must be US_ASCII.
 *
 * @param file file to read from
 * @return PEM data from file
 */
public static String readPemStringFromFile(File file) {
    try {
        byte[] fileContents = Files.readAllBytes(file.toPath());
        return new String(fileContents, StandardCharsets.US_ASCII);
    } catch (IOException e) {
        throw new ImportException("Unable to read PEM-encoded data from file: " + file.getName());
    }
}
 
Example 5
Source File: ChunkDecoder.java    From amazon-kinesis-video-streams-producer-sdk-java with Apache License 2.0 5 votes vote down vote up
public static Response parseEntireTextResponse(final InputStream inputStream) {
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.US_ASCII));
    return Response.builder()
            .responseStatus(parseStatusLine(inputStream))
            .responseHeaders(parseHeaders(inputStream))
            .responseBody(parseTextBody(reader))
            .responsePayload(inputStream)
            .build();
}
 
Example 6
Source File: ChunkDecoder.java    From amazon-kinesis-video-streams-producer-sdk-java with Apache License 2.0 5 votes vote down vote up
public static Integer decodeAckInResponseBody(final InputStream inputStream,
                                              final Consumer<String> ackTimestampConsumer) {
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.US_ASCII));

    try {
        skipResponseHeaders(reader);
        return parseResponseBodyAndDecodeAck(reader, ackTimestampConsumer);
    } catch (final Throwable e) {
        throw new RuntimeException("Exception while decoding Ack in response ! ", e);
    }
}
 
Example 7
Source File: GeoTiffStore.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new GeoTIFF store from the given file, URL or stream object.
 * This constructor invokes {@link StorageConnector#closeAllExcept(Object)},
 * keeping open only the needed resource.
 *
 * @param  provider   the factory that created this {@code DataStore} instance, or {@code null} if unspecified.
 * @param  connector  information about the storage (URL, stream, <i>etc</i>).
 * @throws DataStoreException if an error occurred while opening the GeoTIFF file.
 */
public GeoTiffStore(final GeoTiffStoreProvider provider, final StorageConnector connector) throws DataStoreException {
    super(provider, connector);
    final Charset encoding = connector.getOption(OptionKey.ENCODING);
    this.encoding = (encoding != null) ? encoding : StandardCharsets.US_ASCII;
    final ChannelDataInput input = connector.getStorageAs(ChannelDataInput.class);
    if (input == null) {
        throw new UnsupportedStorageException(super.getLocale(), Constants.GEOTIFF,
                connector.getStorage(), connector.getOption(OptionKey.OPEN_OPTIONS));
    }
    location = connector.getStorageAs(URI.class);
    connector.closeAllExcept(input);
    try {
        reader = new Reader(this, input);
    } catch (IOException e) {
        throw new DataStoreException(e);
    }
    if (location != null) {
        final NameFactory f = reader.nameFactory;
        String filename = IOUtilities.filenameWithoutExtension(input.filename);
        if (Numerics.isUnsignedInteger(filename)) filename += ".tiff";
        identifier = f.createNameSpace(f.createLocalName(null, filename), null);
    } else {
        // Location not convertible to URI. The string representation is probably a class name, which is not useful.
        identifier = null;
    }
}
 
Example 8
Source File: EncodableObject.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public EncodableObject decode(final ByteBuffer s) throws DecodeException {
    if(!initalized) {
        throw new DecodeException(s, "not initialized");
    }
    byte[] data = new byte[s.remaining()];
    s.get(data);
    return new EncodableObject(new String(data, StandardCharsets.US_ASCII));
}
 
Example 9
Source File: UnixCrypt.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Encrypts String into crypt (Unix) code.
 * @param key the key to be encrypted
 * @param setting the salt to be used
 * @return the encrypted String
 */
public static String crypt(String key, String setting)
{
    long constdatablock = 0L;		/* encryption constant */
    byte[] cryptresult = new byte[13];	/* encrypted result */
    long keyword = 0L;
    /* invalid parameters! */
    if(key==null||setting==null) 
        return "*"; // will NOT match under ANY circumstances!

    int keylen = key.length();

    for (int i=0; i<8 ; i++) {
        keyword = (keyword << 8) | ((i < keylen)? 2*key.charAt(i): 0);
    }

    long[] KS = des_setkey(keyword);

    int salt = 0;
    for (int i=2; --i>=0;) {
        char c = (i < setting.length())? setting.charAt(i): '.';
        cryptresult[i] = (byte)c;
        salt = (salt<<6) | (0x00ff&A64TOI[c]);
    }

    long rsltblock = des_cipher(constdatablock, salt, 25, KS);

    cryptresult[12] = ITOA64[(((int)rsltblock)<<2)&0x3f];
    rsltblock >>= 4;
    for (int i=12; --i>=2; ) {
        cryptresult[i] = ITOA64[((int)rsltblock)&0x3f];
        rsltblock >>= 6;
    }

    return new String(cryptresult, 0, 13, StandardCharsets.US_ASCII);
}
 
Example 10
Source File: CSSTokenizer.java    From ph-css with Apache License 2.0 5 votes vote down vote up
@Nonnull
private Charset _determineCharset (@Nonnull @WillNotClose final CSSInputStream aIS) throws IOException,
                                                                                    CSSTokenizeException
{
  // Determine charset
  // https://www.w3.org/TR/css-syntax-3/#input-byte-stream
  final int nMaxHeader = Math.min (1024, aIS.available ());
  if (nMaxHeader > 11)
  {
    final byte [] aBuffer = new byte [nMaxHeader];
    aIS.read (aBuffer);
    aIS.unread (aBuffer);

    final String sPrefix = new String (aBuffer, 0, CHARSET.length (), StandardCharsets.US_ASCII);
    if (m_bStrictMode ? CHARSET.equals (sPrefix) : CHARSET.equalsIgnoreCase (sPrefix))
    {
      int nEnd = CHARSET.length ();
      while (nEnd < nMaxHeader && aBuffer[nEnd] != '"')
        nEnd++;
      if (nEnd == nMaxHeader)
        throw new CSSTokenizeException ("Unexpected end of @charset declaration");
      String sCharset = new String (aBuffer, CHARSET.length (), nEnd - CHARSET.length (), StandardCharsets.US_ASCII);
      if ("utf-16be".equalsIgnoreCase (sCharset) || "utf-16le".equalsIgnoreCase (sCharset))
        sCharset = "utf-8";
      final Charset aCharset = CharsetHelper.getCharsetFromNameOrNull (sCharset);
      if (aCharset == null)
        throw new CSSTokenizeException ("Unsupported charset '" + sCharset + "' provided!");
      return aCharset;
    }
  }
  return m_aFallbackEncoding;
}
 
Example 11
Source File: KeysMap.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void loadKeysMap(final InputStream inputStream) throws IOException {
    BufferedReader mapReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.US_ASCII));
    String currentLine;

    while ((currentLine = getNextLine(mapReader)) != null) {
        String[] parts = currentLine.split("=", 2);
        ArtifactInfo artifactInfo = createArtifactInfo(parts[0], parts.length == 1 ? "" : parts[1]);
        keysMapList.add(artifactInfo);
    }
}
 
Example 12
Source File: TelnetTtyConnection.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public Charset inputCharset() {
  return inBinary ? charset : StandardCharsets.US_ASCII;
}
 
Example 13
Source File: StringField.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
public StringField(int length) {
    super(length);

    charset = StandardCharsets.US_ASCII;
}
 
Example 14
Source File: DataURIEncodingInputStream.java    From extract with MIT License 4 votes vote down vote up
public static Reader createReader(final Path path, final Metadata metadata) throws IOException {
	return new InputStreamReader(new DataURIEncodingInputStream(path, metadata), StandardCharsets.US_ASCII);
}
 
Example 15
Source File: ByteBuf.java    From AndroidAPS with GNU Affero General Public License v3.0 4 votes vote down vote up
private String getASCII(int position, int stringLength) {
    String string = new String(getBytes(position, stringLength + 1), StandardCharsets.US_ASCII);
    return string.substring(0, string.indexOf(0));
}
 
Example 16
Source File: DockerComputerAttachConnector.java    From docker-plugin with MIT License 4 votes vote down vote up
@Override
public void launch(final SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException {
    final PrintStream logger = computer.getListener().getLogger();
    final String jenkinsUrl = Jenkins.getInstance().getRootUrl();
    final String effectiveJavaExe = StringUtils.isNotBlank(javaExeOrNull) ? javaExeOrNull : DEFAULT_JAVA_EXE;
    final String effectiveJvmArgs = StringUtils.isNotBlank(jvmArgsOrEmpty) ? jvmArgsOrEmpty : DEFAULT_JVM_ARGS ;
    final EnvVars knownVariables = calculateVariablesForVariableSubstitution(effectiveJavaExe, effectiveJvmArgs, remoting.getName(), remoteFs, jenkinsUrl);
    final String effectiveEntryPointCmdString = StringUtils.isNotBlank(entryPointCmdOrEmpty) ? entryPointCmdOrEmpty : DEFAULT_ENTRY_POINT_CMD_STRING;
    final String resolvedEntryPointCmdString = Util.replaceMacro(effectiveEntryPointCmdString, knownVariables);
    final String[] resolvedEntryPointCmd = splitAndFilterEmpty(resolvedEntryPointCmdString, "\n");
    logger.println("Connecting to docker container " + containerId + ", running command " + Joiner.on(" ").join(resolvedEntryPointCmd));

    final String execId;
    try(final DockerClient client = api.getClient()) {
        final ExecCreateCmd cmd = client.execCreateCmd(containerId)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withAttachStderr(true)
                .withTty(false)
                .withCmd(resolvedEntryPointCmd);
        if (StringUtils.isNotBlank(userOrNull)) {
            cmd.withUser(userOrNull);
        }
        final ExecCreateCmdResponse exec = cmd.exec();
        execId = exec.getId();
    }
    final String js = "{ \"Detach\": false, \"Tty\": false }";
    final Socket socket = api.getSocket();
    final OutputStream out = socket.getOutputStream();
    final InputStream in = socket.getInputStream();
    final PrintWriter w = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.US_ASCII));
    w.println("POST /v1.32/exec/" + execId + "/start HTTP/1.1");
    w.println("Host: docker.sock");
    w.println("Content-Type: application/json");
    w.println("Upgrade: tcp");
    w.println("Connection: Upgrade");
    w.println("Content-Length: " + js.length());
    w.println();
    w.println(js);
    w.flush();

    // read HTTP response headers
    String line = readLine(in);
    logger.println(line);
    if (! line.startsWith("HTTP/1.1 101 ")) {   // Switching Protocols
        throw new IOException("Unexpected HTTP response status line " + line);
    }

    // Skip HTTP header
    while ((line = readLine(in)).length() > 0) {
        if (line.length() == 0) break; // end of header
        logger.println(line);
    }

    final InputStream demux = new DockerMultiplexedInputStream(in);

    computer.setChannel(demux, out, listener, new Channel.Listener() {
        @Override
        public void onClosed(Channel channel, IOException cause) {
            // Bye!
        }
    });

}
 
Example 17
Source File: DefaultAdminClientProvider.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Create a Kafka Admin interface instance handling the following different scenarios:
 *
 * 1. No TLS connection, no TLS client authentication:
 *
 * If {@code clusterCaCertSecret}, {@code keyCertSecret} and {@code keyCertName} are null, the returned Admin Client instance
 * is configured to connect to the Apache Kafka bootstrap (defined via {@code hostname}) on plain connection with no
 * TLS encryption and no TLS client authentication.
 *
 * 2. TLS connection, no TLS client authentication
 *
 * If only {@code clusterCaCertSecret} is provided as not null, the returned Admin Client instance is configured to
 * connect to the Apache Kafka bootstrap (defined via {@code hostname}) on TLS encrypted connection but with no
 * TLS authentication.
 *
 * 3. TLS connection and TLS client authentication
 *
 * If {@code clusterCaCertSecret}, {@code keyCertSecret} and {@code keyCertName} are provided as not null, the returned
 * Admin Client instance is configured to connect to the Apache Kafka bootstrap (defined via {@code hostname}) on
 * TLS encrypted connection and with TLS client authentication.
 */
@Override
public Admin createAdminClient(String hostname, Secret clusterCaCertSecret, Secret keyCertSecret, String keyCertName) {
    Admin ac;
    String trustStorePassword = null;
    File truststoreFile = null;
    // provided Secret with cluster CA certificate for TLS encryption
    if (clusterCaCertSecret != null) {
        PasswordGenerator pg = new PasswordGenerator(12);
        trustStorePassword = pg.generate();
        truststoreFile = Util.createFileTrustStore(getClass().getName(), "ts", Ca.cert(clusterCaCertSecret, Ca.CA_CRT), trustStorePassword.toCharArray());
    }

    try {
        String keyStorePassword = null;
        File keystoreFile = null;
        // provided Secret and related key for getting the private key for TLS client authentication
        if (keyCertSecret != null && keyCertName != null && !keyCertName.isEmpty()) {
            keyStorePassword = new String(Util.decodeFromSecret(keyCertSecret, keyCertName + ".password"), StandardCharsets.US_ASCII);
            keystoreFile = Util.createFileStore(getClass().getName(), "ts", Util.decodeFromSecret(keyCertSecret, keyCertName + ".p12"));
        }

        try {
            Properties p = new Properties();
            p.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, hostname);

            // configuring TLS encryption if requested
            if (truststoreFile != null && trustStorePassword != null) {
                p.setProperty(AdminClientConfig.SECURITY_PROTOCOL_CONFIG, "SSL");

                p.setProperty(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, truststoreFile.getAbsolutePath());
                p.setProperty(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12");
                p.setProperty(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, trustStorePassword);
            }

            // configuring TLS client authentication
            if (keystoreFile != null && keyStorePassword != null) {
                p.setProperty(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, keystoreFile.getAbsolutePath());
                p.setProperty(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12");
                p.setProperty(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, keyStorePassword);
            }

            p.setProperty(AdminClientConfig.METADATA_MAX_AGE_CONFIG, "30000");

            ac = Admin.create(p);
        } finally {
            if (keystoreFile != null && !keystoreFile.delete()) {
                LOGGER.warn("Unable to delete keystore file {}", keystoreFile);
            }
        }
    } finally {
        if (truststoreFile != null && !truststoreFile.delete()) {
            LOGGER.warn("Unable to delete truststore file {}", truststoreFile);
        }
    }
    return ac;
}
 
Example 18
Source File: MCRDataURL.java    From mycore with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Constructs a new {@link MCRDataURL}.
 *
 * @param data the data
 * @param encoding the encoding of data url
 * @param mimeType the mimeType of data url
 * @throws MalformedURLException
 */
public MCRDataURL(final byte[] data, final MCRDataURLEncoding encoding, final String mimeType)
    throws MalformedURLException {
    this(data, encoding, DEFAULT_MIMETYPE, StandardCharsets.US_ASCII);
}
 
Example 19
Source File: Source.java    From openjdk-jdk9 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 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);
}