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

The following examples show how to use java.nio.charset.StandardCharsets#US_ASCII . These examples are extracted from open source projects. 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 Project: sailfish-core   File: MiscUtils.java    License: 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
/**
 * 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 Project: pgpverify-maven-plugin   File: KeysMap.java    License: 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 4
/**
 * 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 5
Source Project: ph-css   File: CSSTokenizer.java    License: 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 6
/**
 * 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 7
Source Project: quarkus-http   File: EncodableObject.java    License: 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 8
Source Project: sis   File: GeoTiffStore.java    License: 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 9
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 10
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 11
Source Project: CapturePacket   File: EncryptionUtil.java    License: 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 12
Source Project: unidbg   File: MachOModule.java    License: Apache License 2.0 4 votes vote down vote up
MachOModule(MachO machO, String name, long base, long size, Map<String, Module> neededLibraries, List<MemRegion> regions,
            MachO.SymtabCommand symtabCommand, MachO.DysymtabCommand dysymtabCommand, ByteBuffer buffer,
            List<NeedLibrary> lazyLoadNeededList, Map<String, Module> upwardLibraries, Map<String, Module> exportModules,
            String path, Emulator<?> emulator, MachO.DyldInfoCommand dyldInfoCommand, UnicornPointer envp, UnicornPointer apple, UnicornPointer vars,
            long machHeader, boolean executable, MachOLoader loader, List<HookListener> hookListeners, List<String> ordinalList,
            Section fEHFrameSection, Section fUnwindInfoSection) {
    super(name, base, size, neededLibraries, regions);
    this.machO = machO;
    this.symtabCommand = symtabCommand;
    this.dysymtabCommand = dysymtabCommand;
    this.buffer = buffer;
    this.lazyLoadNeededList = lazyLoadNeededList;
    this.upwardLibraries = upwardLibraries;
    this.exportModules = exportModules;
    this.path = path;
    this.dyldInfoCommand = dyldInfoCommand;
    this.envp = envp;
    this.apple = apple;
    this.vars = vars;
    this.machHeader = machHeader;
    this.executable = executable;
    this.loader = loader;
    this.hookListeners = hookListeners;
    this.ordinalList = ordinalList;
    this.fEHFrameSection = fEHFrameSection;
    this.fUnwindInfoSection = fUnwindInfoSection;

    this.log = LogFactory.getLog("com.github.unidbg.ios." + name);
    this.routines = machO == null ? Collections.<InitFunction>emptyList() : parseRoutines(machO);
    this.initFunctionList = machO == null ? Collections.<InitFunction>emptyList() : parseInitFunction(machO, buffer.duplicate(), name, emulator);

    if (machO == null) {
        exportSymbols = Collections.emptyMap();
        return;
    }

    exportSymbols = processExportNode(log, dyldInfoCommand, buffer);

    if (symtabCommand != null) {
        buffer.limit((int) (symtabCommand.strOff() + symtabCommand.strSize()));
        buffer.position((int) symtabCommand.strOff());
        ByteBuffer strBuffer = buffer.slice();
        ByteBufferKaitaiStream io = new ByteBufferKaitaiStream(strBuffer);
        for (MachO.SymtabCommand.Nlist nlist : symtabCommand.symbols()) {
            int type = nlist.type() & N_TYPE;
            if (nlist.un() == 0) {
                continue;
            }

            boolean isWeakDef = (nlist.desc() & N_WEAK_DEF) != 0;
            boolean isThumb = (nlist.desc() & N_ARM_THUMB_DEF) != 0;
            strBuffer.position((int) nlist.un());
            String symbolName = new String(io.readBytesTerm(0, false, true, true), StandardCharsets.US_ASCII);
            if ((type == N_SECT || type == N_ABS) && (nlist.type() & N_STAB) == 0) {
                ExportSymbol exportSymbol = null;
                if (exportSymbols.isEmpty() || (exportSymbol = exportSymbols.remove(symbolName)) != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("nlist un=0x" + Long.toHexString(nlist.un()) + ", symbolName=" + symbolName + ", type=0x" + Long.toHexString(nlist.type()) + ", isWeakDef=" + isWeakDef + ", isThumb=" + isThumb + ", value=0x" + Long.toHexString(nlist.value()));
                    }

                    MachOSymbol symbol = new MachOSymbol(this, nlist, symbolName);
                    if (exportSymbol != null && symbol.getAddress() == exportSymbol.getOtherWithBase()) {
                        if (log.isDebugEnabled()) {
                            log.debug("nlist un=0x" + Long.toHexString(nlist.un()) + ", symbolName=" + symbolName + ", value=0x" + Long.toHexString(nlist.value()) + ", address=0x" + Long.toHexString(exportSymbol.getValue()) + ", other=0x" + Long.toHexString(exportSymbol.getOtherWithBase()));
                        }
                        symbolMap.put(symbolName, exportSymbol);
                    } else {
                        symbolMap.put(symbolName, symbol);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("nlist FILTER un=0x" + Long.toHexString(nlist.un()) + ", symbolName=" + symbolName + ", type=0x" + Long.toHexString(nlist.type()) + ", isWeakDef=" + isWeakDef + ", isThumb=" + isThumb + ", value=0x" + Long.toHexString(nlist.value()));
                    }
                }
            } else if (type == N_INDR) {
                strBuffer.position(nlist.value().intValue());
                String indirectSymbol = new String(io.readBytesTerm(0, false, true, true), StandardCharsets.US_ASCII);
                if (!symbolName.equals(indirectSymbol)) {
                    if (log.isDebugEnabled()) {
                        log.debug("nlist indirect symbolName=" + symbolName + ", indirectSymbol=" + indirectSymbol);
                    }
                    symbolMap.put(symbolName, new IndirectSymbol(symbolName, this, indirectSymbol));
                }
            } else if (log.isDebugEnabled()) {
                log.debug("nlist isWeakDef=" + isWeakDef + ", isThumb=" + isThumb + ", type=" + type + ", symbolName=" + symbolName);
            }
        }
    }
}
 
Example 13
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 14
Source Project: extract   File: DataURIEncodingInputStream.java    License: 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 Project: smarthome   File: StringField.java    License: Eclipse Public License 2.0 4 votes vote down vote up
public StringField(int length) {
    super(length);

    charset = StandardCharsets.US_ASCII;
}
 
Example 16
Source Project: termd   File: TelnetTtyConnection.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Charset inputCharset() {
  return inBinary ? charset : StandardCharsets.US_ASCII;
}
 
Example 17
@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 18
/**
 * 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 19
Source Project: mycore   File: MCRDataURL.java    License: 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 20
/**
 * 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);
}