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:com.github.ambry.utils.UtilsTest.java
@Test public void testSerializeString() { String randomString = getRandomString(10); ByteBuffer outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length); Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); outputBuffer.flip();// w w w . j av a2 s .c om int length = outputBuffer.getInt(); assertEquals("Input and output string lengths don't match", randomString.getBytes().length, length); byte[] output = new byte[length]; outputBuffer.get(output); assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes", outputBuffer.hasRemaining()); String outputString = new String(output); assertEquals("Input and output strings don't match", randomString, outputString); randomString = getRandomString(10) + ""; outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length); Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); outputBuffer.flip(); length = outputBuffer.getInt(); assertEquals("Input and output string lengths don't match ", (randomString.getBytes().length - 1), length); output = new byte[length]; outputBuffer.get(output); assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes", outputBuffer.hasRemaining()); outputString = new String(output); randomString = randomString.substring(0, randomString.length() - 1) + "?"; assertEquals("Input and output strings don't match", randomString, outputString); randomString = ""; outputBuffer = ByteBuffer.allocate(4); Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); outputBuffer.flip(); length = outputBuffer.getInt(); assertEquals("Input and output string lengths don't match", 0, length); output = new byte[length]; outputBuffer.get(output); assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes", outputBuffer.hasRemaining()); outputString = new String(output); assertEquals("Output string \"" + outputString + "\" expected to be empty", outputString, ""); randomString = getRandomString(10); outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length - 1); try { Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); Assert.fail("Serialization should have failed due to insufficient space"); } catch (RuntimeException e) { } }
From source file:patientlinkage.Util.Util.java
public static Helper readAndEncodeWithProps(String FileName, int[][] lens) { Helper ret = new Helper(); ArrayList<boolean[][]> retArrList = new ArrayList<>(); int properties_num = lens[0].length; Soundex sdx = new Soundex(); try (CSVReader reader = new CSVReader(new FileReader(FileName))) { String[] strs;//from w w w. j a v a 2 s . c o m ret.pros = reader.readNext(); ret.updatingrules(lens); while ((strs = reader.readNext()) != null) { ret.IDs.add(strs[0]); String[] coms_strs = new String[lens.length]; Arrays.fill(coms_strs, ""); for (int i = 0; i < properties_num; i++) { String temp = strs[i].replace("-", "").toLowerCase(); for (int j = 0; j < coms_strs.length; j++) { if (lens[j][i] > (Integer.MAX_VALUE / 2)) { coms_strs[j] += sdx.soundex(temp) + resizeString(temp, Integer.MAX_VALUE - lens[j][i]); } else { coms_strs[j] += resizeString(temp, lens[j][i]); } } } boolean[][] bool_arr = new boolean[coms_strs.length][]; for (int j = 0; j < coms_strs.length; j++) { bool_arr[j] = bytes2boolean(coms_strs[j].getBytes(StandardCharsets.US_ASCII)); } retArrList.add(bool_arr); } } catch (FileNotFoundException ex) { Logger.getLogger(PatientLinkageGadget.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PatientLinkageGadget.class.getName()).log(Level.SEVERE, null, ex); } ret.data_bin = new boolean[retArrList.size()][][]; for (int i = 0; i < ret.data_bin.length; i++) { ret.data_bin[i] = retArrList.get(i); } return ret; }
From source file:org.apache.solr.client.solrj.TestSolrJErrorHandling.java
@Test public void testRawSocket() throws Exception { String hostName = "127.0.0.1"; int port = jetty.getLocalPort(); try (Socket socket = new Socket(hostName, port); OutputStream out = new BufferedOutputStream(socket.getOutputStream()); InputStream in = socket.getInputStream();) { byte[] body = getJsonDocs(100000).getBytes(StandardCharsets.UTF_8); int bodyLen = body.length; // bodyLen *= 10; // make server wait for more byte[] whitespace = whitespace(1000000); bodyLen += whitespace.length;/*from ww w . j a v a 2 s .c om*/ String headers = "POST /solr/collection1/update HTTP/1.1\n" + "Host: localhost:" + port + "\n" + // "User-Agent: curl/7.43.0\n" + "Accept: */*\n" + "Content-type:application/json\n" + "Content-Length: " + bodyLen + "\n" + "Connection: Keep-Alive\n"; // Headers of HTTP connection are defined to be ASCII only: out.write(headers.getBytes(StandardCharsets.US_ASCII)); out.write('\n'); // extra newline separates headers from body out.write(body); out.flush(); // Now what if I try to write more? This doesn't seem to throw an exception! Thread.sleep(1000); out.write(whitespace); // whitespace out.flush(); String rbody = getResponse(in); // This will throw a connection reset exception if you try to read past the end of the HTTP response log.info("RESPONSE BODY:" + rbody); assertTrue(rbody.contains("unknown_field")); /*** // can I reuse now? // writing another request doesn't actually throw an exception, but the following read does out.write(headers); out.write("\n"); // extra newline separates headers from body out.write(body); out.flush(); rbody = getResponse(in); log.info("RESPONSE BODY:" + rbody); assertTrue(rbody.contains("unknown_field")); ***/ } }
From source file:org.apache.james.core.builder.MimeMessageBuilder.java
public MimeMessageBuilder setMultipartWithSubMessage(MimeMessage mimeMessage) throws MessagingException, IOException { return setMultipartWithBodyParts(new MimeBodyPart( new InternetHeaders(new ByteArrayInputStream( "Content-Type: multipart/mixed".getBytes(StandardCharsets.US_ASCII))), IOUtils.toByteArray(mimeMessage.getInputStream()))); }
From source file:org.zaproxy.zap.extension.dynssl.DynamicSSLPanel.java
/** * Converts the given {@code .pem} file into a {@link KeyStore}. * * @param pemFile the {@code .pem} file that contains the certificate and the private key. * @return the {@code KeyStore} with the certificate, or {@code null} if the conversion failed. *//*from w w w. j a v a 2s . c o m*/ private KeyStore convertPemFileToKeyStore(Path pemFile) { String pem; try { pem = FileUtils.readFileToString(pemFile.toFile(), StandardCharsets.US_ASCII); } catch (IOException e) { logger.warn("Failed to read .pem file:", e); JOptionPane.showMessageDialog(this, Constant.messages.getString("dynssl.importpem.failedreadfile", e.getLocalizedMessage()), Constant.messages.getString("dynssl.importpem.failed.title"), JOptionPane.ERROR_MESSAGE); return null; } byte[] cert; try { cert = SslCertificateUtils.extractCertificate(pem); if (cert.length == 0) { JOptionPane.showMessageDialog(this, Constant.messages.getString("dynssl.importpem.nocertsection", SslCertificateUtils.BEGIN_CERTIFICATE_TOKEN, SslCertificateUtils.END_CERTIFICATE_TOKEN), Constant.messages.getString("dynssl.importpem.failed.title"), JOptionPane.ERROR_MESSAGE); return null; } } catch (IllegalArgumentException e) { logger.warn("Failed to base64 decode the certificate from .pem file:", e); JOptionPane.showMessageDialog(this, Constant.messages.getString("dynssl.importpem.certnobase64"), Constant.messages.getString("dynssl.importpem.failed.title"), JOptionPane.ERROR_MESSAGE); return null; } byte[] key; try { key = SslCertificateUtils.extractPrivateKey(pem); if (key.length == 0) { JOptionPane.showMessageDialog(this, Constant.messages.getString("dynssl.importpem.noprivkeysection", SslCertificateUtils.BEGIN_PRIVATE_KEY_TOKEN, SslCertificateUtils.END_PRIVATE_KEY_TOKEN), Constant.messages.getString("dynssl.importpem.failed.title"), JOptionPane.ERROR_MESSAGE); return null; } } catch (IllegalArgumentException e) { logger.warn("Failed to base64 decode the private key from .pem file:", e); JOptionPane.showMessageDialog(this, Constant.messages.getString("dynssl.importpem.privkeynobase64"), Constant.messages.getString("dynssl.importpem.failed.title"), JOptionPane.ERROR_MESSAGE); return null; } try { return SslCertificateUtils.pem2KeyStore(cert, key); } catch (Exception e) { logger.error("Error creating KeyStore for Root CA cert from .pem file:", e); JOptionPane.showMessageDialog(this, Constant.messages.getString("dynssl.importpem.failedkeystore", e.getLocalizedMessage()), Constant.messages.getString("dynssl.importpem.failed.title"), JOptionPane.ERROR_MESSAGE); return null; } }
From source file:org.apache.solr.servlet.SolrRequestParserTest.java
License:asdf
@Test public void testStandardFormdataUploadLimit() throws Exception { final int limitKBytes = 128; final StringBuilder large = new StringBuilder("q=hello"); // grow exponentially to reach 128 KB limit: while (large.length() <= limitKBytes * 1024) { large.append('&').append(large); }// ww w . ja v a 2 s .c o m HttpServletRequest request = getMock("/solr/select", "application/x-www-form-urlencoded", -1); expect(request.getMethod()).andReturn("POST").anyTimes(); expect(request.getQueryString()).andReturn(null).anyTimes(); expect(request.getInputStream()) .andReturn(new ByteServletInputStream(large.toString().getBytes(StandardCharsets.US_ASCII))); replay(request); FormDataRequestParser formdata = new FormDataRequestParser(limitKBytes); try { formdata.parseParamsAndFillStreams(request, new ArrayList<ContentStream>()); fail("should throw SolrException"); } catch (SolrException solre) { assertTrue(solre.getMessage().contains("upload limit")); assertEquals(400, solre.code()); } }
From source file:net.pms.util.AudioUtils.java
private static void parseRealAudioMetaData(ByteBuffer buffer, DLNAMediaAudio audio, short version) { buffer.position(buffer.position() + (version == 4 ? 3 : 4)); // skip unknown byte b = buffer.get(); if (b != 0) { byte[] title = new byte[Math.min(b & 0xFF, buffer.remaining())]; buffer.get(title);/*from w w w . java2s. c o m*/ String titleString = new String(title, StandardCharsets.US_ASCII); audio.setSongname(titleString); audio.setAudioTrackTitleFromMetadata(titleString); } if (buffer.hasRemaining()) { b = buffer.get(); if (b != 0) { byte[] artist = new byte[Math.min(b & 0xFF, buffer.remaining())]; buffer.get(artist); audio.setArtist(new String(artist, StandardCharsets.US_ASCII)); } } }
From source file:com.github.ambry.utils.UtilsTest.java
@Test public void testDeserializeString() { String randomString = getRandomString(10); ByteBuffer outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length); Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); outputBuffer.flip();/* w ww.j a va2 s . c o m*/ String outputString = Utils.deserializeString(outputBuffer, StandardCharsets.US_ASCII); assertEquals("Input and output strings don't match", randomString, outputString); randomString = getRandomString(10) + ""; outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length); Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); outputBuffer.flip(); outputString = Utils.deserializeString(outputBuffer, StandardCharsets.US_ASCII); randomString = randomString.substring(0, randomString.length() - 1) + "?"; assertEquals("Input and output strings don't match", randomString, outputString); randomString = ""; outputBuffer = ByteBuffer.allocate(4); Utils.serializeString(outputBuffer, randomString, StandardCharsets.US_ASCII); outputBuffer.flip(); outputString = Utils.deserializeString(outputBuffer, StandardCharsets.US_ASCII); assertEquals("Output string \"" + outputString + "\" expected to be empty", outputString, ""); randomString = getRandomString(10); outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length); outputBuffer.putInt(12); outputBuffer.put(randomString.getBytes()); outputBuffer.flip(); try { outputString = Utils.deserializeString(outputBuffer, StandardCharsets.US_ASCII); Assert.fail("Deserialization should have failed " + randomString); } catch (RuntimeException e) { } }
From source file:it.uniud.ailab.dcore.launchers.Launcher.java
/** * Load the document trying different charsets. The charset tried, are, in * order://from w w w .ja va 2 s . c om * <ul> * <li>UTF-16;</li> * <li>UTF-8;</li> * <li>US-ASCII.</li> * </ul> * * @param filePath the path of the document * @return the text of the document * @throws IOException if the charset is not supported */ private static String loadDocument(File filePath) throws IOException { String document = ""; IOException exception = null; // try different charsets. if none is recognized, throw the // exception detected when reading. try { document = String.join(" ", Files.readAllLines(filePath.toPath(), StandardCharsets.UTF_8)); } catch (java.nio.charset.MalformedInputException e) { exception = e; } if (exception != null) { try { exception = null; document = String.join(" ", Files.readAllLines(filePath.toPath(), StandardCharsets.UTF_16)); } catch (java.nio.charset.MalformedInputException e) { exception = e; } } if (exception != null) { try { exception = null; document = String.join(" ", Files.readAllLines(filePath.toPath(), StandardCharsets.US_ASCII)); } catch (java.nio.charset.MalformedInputException e) { exception = e; } } // no charset has been recognized if (exception != null) { throw exception; } return document; }