下面列出了java.nio.charset.StandardCharsets#ISO_8859_1 ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private String readId3v22TagName() throws IOException {
dataInput.readFully(tagHeaderBuffer, 0, 3);
if (tagHeaderBuffer[0] == 0) {
return null;
}
String shortName = new String(tagHeaderBuffer, 0, 3, StandardCharsets.ISO_8859_1);
if ("TT2".equals(shortName)) {
return "TIT2";
} else if ("TP1".equals(shortName)) {
return "TPE1";
} else {
return shortName;
}
}
private long doCreateString(String input, int size,
boolean defensiveCopyWorkAround) {
int loops = 10000;
byte[] inputBytes = input.getBytes();
byte[] bytes = new byte[size];
int inputLength = inputBytes.length;
System.arraycopy(inputBytes, 0, bytes, 0, inputLength);
String[] result = new String[loops];
Charset charset = StandardCharsets.ISO_8859_1;
long start = System.nanoTime();
for (int i = 0; i < loops; i++) {
if (defensiveCopyWorkAround) {
byte[] tmp = new byte[inputLength];
System.arraycopy(bytes, 0, tmp, 0, inputLength);
result[i] = new String(tmp, 0, inputLength, charset);
} else {
result[i] = new String(bytes, 0, inputLength, charset);
}
}
return System.nanoTime() - start;
}
@Test
public void testAutomaticUsage ()
{
final HelpFormatter hf = new HelpFormatter ();
Options options = null;
String expected = "usage: app [-a]";
final NonBlockingByteArrayOutputStream out = new NonBlockingByteArrayOutputStream ();
final PrintWriter pw = new PrintWriter (new OutputStreamWriter (out, StandardCharsets.ISO_8859_1));
options = new Options ().addOption (Option.builder ("a").desc ("aaaa aaaa aaaa aaaa aaaa"));
hf.printUsage (pw, 60, "app", options);
pw.flush ();
assertEquals ("simple auto usage", expected, out.getAsString (StandardCharsets.ISO_8859_1).trim ());
out.reset ();
expected = "usage: app [-a] [-b]";
options = new Options ().addOption (Option.builder ("a").desc ("aaaa aaaa aaaa aaaa aaaa"))
.addOption (Option.builder ("b").desc ("bbb"));
hf.printUsage (pw, 60, "app", options);
pw.flush ();
assertEquals ("simple auto usage", expected, out.getAsString (StandardCharsets.ISO_8859_1).trim ());
out.reset ();
}
public void setCharset(String charsetString) {
// Only acceptable options are null, "" or "UTF-8" (case insensitive)
if (charsetString == null || charsetString.isEmpty()) {
charset = StandardCharsets.ISO_8859_1;
} else if ("UTF-8".equalsIgnoreCase(charsetString)) {
charset = StandardCharsets.UTF_8;
} else {
throw new IllegalArgumentException(sm.getString("basicAuthenticator.invalidCharset"));
}
this.charsetString = charsetString;
}
private String getNameString(int[] ram, int offset) {
byte[] bytes = new byte[128];
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().put(ram, offset, 32);
String result = new String(bytes, StandardCharsets.ISO_8859_1);
int pos = result.indexOf('\0');
if (pos != -1) {
result = result.substring(0, pos);
}
return result;
}
/**
* Main loop of the SMTP server.
*/
private void performWork() {
try {
// Server: loop until stopped
while (!stopped) {
// Start server socket and listen for client connections
//noinspection resource
try (Socket socket = serverSocket.accept();
Scanner input = new Scanner(new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1)).useDelimiter(CRLF);
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.ISO_8859_1));) {
synchronized (receivedMail) {
/*
* We synchronize over the handle method and the list update because the client call completes inside
* the handle method and we have to prevent the client from reading the list until we've updated it.
*/
receivedMail.addAll(handleTransaction(out, input));
}
}
}
} catch (Exception e) {
// SocketException expected when stopping the server
if (!stopped) {
log.error("hit exception when running server", e);
try {
serverSocket.close();
} catch (IOException ex) {
log.error("and one when closing the port", ex);
}
}
}
}
@Test
public void testTransformCsv() throws IOException {
final TestRunner runner = TestRunners.newTestRunner(new TransformXml());
runner.setProperty(TransformXml.XSLT_FILE_NAME, "src/test/resources/TestTransformXml/tokens.xsl");
runner.setProperty("uuid_0", "${uuid_0}");
runner.setProperty("uuid_1", "${uuid_1}");
final Map<String, String> attributes = new HashMap<>();
attributes.put("uuid_0", "uuid_0");
attributes.put("uuid_1", "uuid_1");
StringBuilder builder = new StringBuilder();
builder.append("<data>\n");
try(BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(new File("src/test/resources/TestTransformXml/tokens.csv"))))){
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
builder.append("</data>");
String data = builder.toString();
runner.enqueue(data.getBytes(), attributes);
runner.run();
runner.assertAllFlowFilesTransferred(TransformXml.REL_SUCCESS);
final MockFlowFile transformed = runner.getFlowFilesForRelationship(TransformXml.REL_SUCCESS).get(0);
final String transformedContent = new String(transformed.toByteArray(), StandardCharsets.ISO_8859_1);
final String expectedContent = new String(Files.readAllBytes(Paths.get("src/test/resources/TestTransformXml/tokens.xml")));
transformed.assertContentEquals(expectedContent);
}
}
@Override
public String getString() {
final int arraySize = getInt(); // for C++ zero terminated string
final String str = new String(buffer, (int) (position), arraySize - 1, StandardCharsets.ISO_8859_1);
position += arraySize; // N.B. +1 larger to be compatible with C++ zero terminated string
return str;
}
private static void testPrintAndExit() {
String expected = "<e4> 7.44 100.0 100.0 S";
String content = "";
File file = new File("out.ps");
if (!DEBUG) {
file.deleteOnExit();
}
try (FileInputStream stream = new FileInputStream(file)) {
byte[] data = new byte[(int) file.length()];
stream.read(data);
content = new String(data, StandardCharsets.ISO_8859_1);
} catch (IOException ex) {
ex.printStackTrace();
}
if (!content.contains(expected)) {
System.err.println("FAIL");
if (DEBUG) {
System.err.println("printing content");
System.err.println(content);
}
throw new RuntimeException("Expected <e4> to represent 'ä' but not found!");
}
System.err.println("SUCCESS");
}
String readSecurityBuffer(int offset, boolean unicode)
throws NTLMException {
byte[] raw = readSecurityBuffer(offset);
return raw == null ? null : new String(
raw, unicode ? StandardCharsets.UTF_16LE
: StandardCharsets.ISO_8859_1);
}
@Override
protected String getRemoteChecksum(String uri) throws Exception {
File file = new File(uri + ".sha1");
if (file.isFile()) {
return new String(Files.readAllBytes(file.toPath()), StandardCharsets.ISO_8859_1);
}
return new CheckSum("SHA-1").getChecksum(new File(uri));
}
private String readTagName() throws IOException {
dataInput.readFully(tagHeaderBuffer, 0, 4);
if (tagHeaderBuffer[0] == 0) {
return null;
}
return new String(tagHeaderBuffer, 0, 4, StandardCharsets.ISO_8859_1);
}
private StringEntity createEntry(String requestStr) {
try {
return new StringEntity(new String(requestStr.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
} catch (UnsupportedEncodingException e) {
//cannot happen
this.log.error(e.getMessage(),e);
return null;
}
}
public static void main(String[] args) throws Exception {
Charset charset = StandardCharsets.ISO_8859_1; // 只能表示的英文字符
CharsetEncoder encoder = charset.newEncoder(); // 得到编码器
CharsetDecoder decoder = charset.newDecoder(); // 得到解码器
// 通过CharBuffer类中的
CharBuffer cb = CharBuffer.wrap("梦里花落知多少");
ByteBuffer buf = encoder.encode(cb); // 进行编码操作
System.out.println(decoder.decode(buf)); // 进行解码操作
}
/**
* Constructor with a prepared message.
* @since 5.1.4
*/
public WebClientResponseException(String message, int statusCode, String statusText,
@Nullable HttpHeaders headers, @Nullable byte[] responseBody, @Nullable Charset charset,
@Nullable HttpRequest request) {
super(message);
this.statusCode = statusCode;
this.statusText = statusText;
this.headers = (headers != null ? headers : HttpHeaders.EMPTY);
this.responseBody = (responseBody != null ? responseBody : new byte[0]);
this.responseCharset = (charset != null ? charset : StandardCharsets.ISO_8859_1);
this.request = request;
}
private Charset getCharset() {
Charset charset = this.webRequest.getCharset();
return (charset != null ? charset : StandardCharsets.ISO_8859_1);
}
public Client(String[] args) throws Exception {
serverConnection = SocketChannel.open(new InetSocketAddress(InetAddress.getLoopbackAddress(), Server.SERVER_PORT));
serverConnection.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
serverConnection.socket().setSoTimeout(0);
String workDir = Paths.get("").toAbsolutePath().normalize().toString();
List<byte[]> argsList = Arrays.asList(args).stream().map(s -> s.getBytes(StandardCharsets.UTF_8)).collect(Collectors.toList());
Map<String, Object> command = new HashMap<>();
command.put("arguments", argsList);
command.put("cwd", workDir.getBytes(StandardCharsets.UTF_8));
BEncoder encoder = new BEncoder();
ByteBuffer buf = encoder.encode(command, 65535);
serverConnection.write(tap(ByteBuffer.allocate(4), b -> b.putInt(0, buf.limit())));
serverConnection.write(buf);
//serverConnection.shutdownOutput();
ByteBuffer header = ByteBuffer.allocate(4);
ByteBuffer message;
while(serverConnection.isOpen()) {
header.clear();
serverConnection.read(header);
header.flip();
message = ByteBuffer.allocate(header.getInt(0));
serverConnection.read(message);
message.flip();
BDecoder dec = new BDecoder();
Map<String,Object> msg = dec.decode(message);
String action = new String((byte[])msg.get("action"), StandardCharsets.ISO_8859_1);
switch (action) {
case "sysout":
System.out.append(new String((byte[])msg.get("payload"), StandardCharsets.UTF_8));
break;
case "syserr":
System.err.append(new String((byte[])msg.get("payload"), StandardCharsets.UTF_8));
break;
case "exit":
serverConnection.close();
System.exit(((Long)msg.get("exitCode")).intValue());
break;
default:
throw new IllegalStateException("unexpected action " + action);
}
}
}
CommonsHttpResponseHandler(HttpResponseHandler httpResponseHandler) {
this.defaultHttpCharset = StandardCharsets.ISO_8859_1;
this.httpResponseHandler = httpResponseHandler;
}
public static void setVersion (int ver) {
version = "ml" + new String(new byte[] { (byte) (ver >> 8 & 0xFF) , (byte) (ver & 0xff) }, StandardCharsets.ISO_8859_1);
}
public PngChunkItxt(final int length, final int chunkType, final int crc, final byte[] bytes)
throws ImageReadException, IOException {
super(length, chunkType, crc, bytes);
int terminator = findNull(bytes);
if (terminator < 0) {
throw new ImageReadException(
"PNG iTXt chunk keyword is not terminated.");
}
keyword = new String(bytes, 0, terminator, StandardCharsets.ISO_8859_1);
int index = terminator + 1;
final int compressionFlag = bytes[index++];
if (compressionFlag != 0 && compressionFlag != 1) {
throw new ImageReadException(
"PNG iTXt chunk has invalid compression flag: "
+ compressionFlag);
}
final boolean compressed = compressionFlag == 1;
final int compressionMethod = bytes[index++];
if (compressed && compressionMethod != PngConstants.COMPRESSION_DEFLATE_INFLATE) {
throw new ImageReadException("PNG iTXt chunk has unexpected compression method: " + compressionMethod);
}
terminator = findNull(bytes, index);
if (terminator < 0) {
throw new ImageReadException("PNG iTXt chunk language tag is not terminated.");
}
languageTag = new String(bytes, index, terminator - index, StandardCharsets.ISO_8859_1);
index = terminator + 1;
terminator = findNull(bytes, index);
if (terminator < 0) {
throw new ImageReadException("PNG iTXt chunk translated keyword is not terminated.");
}
translatedKeyword = new String(bytes, index, terminator - index, StandardCharsets.UTF_8);
index = terminator + 1;
if (compressed) {
final int compressedTextLength = bytes.length - index;
final byte[] compressedText = new byte[compressedTextLength];
System.arraycopy(bytes, index, compressedText, 0, compressedTextLength);
text = new String(getStreamBytes(
new InflaterInputStream(new ByteArrayInputStream(compressedText))), StandardCharsets.UTF_8);
} else {
text = new String(bytes, index, bytes.length - index, StandardCharsets.UTF_8);
}
}