本文整理汇总了Java中java.nio.charset.StandardCharsets类的典型用法代码示例。如果您正苦于以下问题:Java StandardCharsets类的具体用法?Java StandardCharsets怎么用?Java StandardCharsets使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
StandardCharsets类属于java.nio.charset包,在下文中一共展示了StandardCharsets类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: verifyJwsSignature
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
/**
* Verify jws signature byte [ ].
*
* @param value the value
* @param signingKey the signing key
* @return the byte [ ]
*/
public static byte[] verifyJwsSignature(final Key signingKey, final byte[] value) {
try {
final String asString = new String(value, StandardCharsets.UTF_8);
final JsonWebSignature jws = new JsonWebSignature();
jws.setCompactSerialization(asString);
jws.setKey(signingKey);
final boolean verified = jws.verifySignature();
if (verified) {
final String payload = jws.getPayload();
LOGGER.trace("Successfully decoded value. Result in Base64-encoding is [{}]", payload);
return EncodingUtils.decodeBase64(payload);
}
return null;
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
示例2: readsInputIntoBytes
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
@Test
public void readsInputIntoBytes() throws IOException {
MatcherAssert.assertThat(
"Can't read bytes from Input",
new String(
new InputAsBytes(
new InputOf(
new BytesOf(
new TextOf("Hello, друг!")
)
)
).asBytes(),
StandardCharsets.UTF_8
),
Matchers.allOf(
Matchers.startsWith("Hello, "),
Matchers.endsWith("друг!")
)
);
}
示例3: shouldPostWithDefaultPoolAndOutputStreamAndHeadersAndNoBody
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
@Test
public void shouldPostWithDefaultPoolAndOutputStreamAndHeadersAndNoBody() throws RestException, IOException {
String url = "http://dummy.com/test";
String output;
Response response;
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
MockResponse.builder()
.withURL(url)
.withMethod(POST)
.withStatusCode(201)
.withResponseHeader(ContentType.HEADER_NAME, ContentType.TEXT_PLAIN.toString())
.build();
response = RestClient.getDefault().post(url, new Headers(Collections.singletonMap("test","1")), os);
output = new String(os.toByteArray(), StandardCharsets.UTF_8);
}
assertEquals(201, response.getStatus());
assertNull(response.getString());
assertEquals(output, "");
assertEquals("1", response.getHeaders().getHeader("REQUEST-test").getValue());
}
示例4: saveWord2VecToBinary
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
/** Save the word2vec model as binary file */
@SuppressWarnings("unused")
public static void saveWord2VecToBinary(String toPath, Word2Vec w2v){
final Charset cs = StandardCharsets.UTF_8;
try {
final OutputStream os = new FileOutputStream(new File(toPath));
final String header = String.format("%d %d\n", w2v.wordVocabSize(), w2v.getLayerSize());
os.write(header.getBytes(cs));
final ByteBuffer buffer = ByteBuffer.allocate(4 * w2v.getLayerSize());
buffer.order(byteOrder);
for (int i = 0; i < w2v.wordVocabSize(); ++i) {
os.write(String.format("%s ", w2v.getWordVocab().get(i)).getBytes(cs)); // Write one word in byte format, add a space.
buffer.clear();
for (int j = 0; j < w2v.getLayerSize(); ++j) {
buffer.putFloat(w2v.getWordVectors().getFloat(i, j));
}
os.write(buffer.array()); // Write all float values of one vector in byte format.
os.write('\n'); // Add a newline.
}
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
示例5: findAllByName
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
@Test
public void findAllByName() throws Exception {
prepareMockHome();
httpServer.stubFor(post(urlEqualTo("/dologin.action"))
.willReturn(aResponse().withStatus(HttpStatus.SC_MOVED_TEMPORARILY).withHeader("Location", "/")));
httpServer.stubFor(get(urlEqualTo("/rest/api/space?type=global&limit=100&start=0"))
.willReturn(aResponse().withStatus(HttpStatus.SC_OK).withBody(IOUtils.toString(
new ClassPathResource("mock-server/confluence/confluence-spaces.json").getInputStream(), StandardCharsets.UTF_8))));
httpServer.stubFor(
get(urlEqualTo("/rest/api/space?type=global&limit=100&start=100")).willReturn(aResponse().withStatus(HttpStatus.SC_OK)
.withBody(IOUtils.toString(new ClassPathResource("mock-server/confluence/confluence-spaces2.json").getInputStream(),
StandardCharsets.UTF_8))));
httpServer.start();
final List<Space> projects = resource.findAllByName("service:km:confluence:dig", "p");
Assert.assertEquals(10, projects.size());
checkSpace(projects.get(4));
}
示例6: initialize
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
@Override
public void initialize(InputStream in) {
try {
if (in != null) {
try {
m_appProperties.load(new InputStreamReader(new BOMInputStream(in), StandardCharsets.UTF_8));
} finally {
in.close();
}
}
initAppId();
} catch (Throwable ex) {
logger.error("Initialize DefaultApplicationProvider failed.", ex);
}
}
示例7: builderWithConnection
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
@Test
public void builderWithConnection() throws Exception {
SqlConfig config = UroboroSQL.builder(DriverManager.getConnection("jdbc:h2:mem:SqlAgentTest")).build();
try (SqlAgent agent = config.agent()) {
String[] sqls = new String(Files.readAllBytes(Paths.get("src/test/resources/sql/ddl/create_tables.sql")),
StandardCharsets.UTF_8).split(";");
for (String sql : sqls) {
if (StringUtils.isNotBlank(sql)) {
agent.updateWith(sql.trim()).count();
}
}
insert(agent, Paths.get("src/test/resources/data/setup", "testExecuteQuery.ltsv"));
agent.rollback();
}
}
示例8: test
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
@Test
public void test() {
InputStreamSource source = new ByteArrayResource(this.expectedText.getBytes(StandardCharsets.UTF_8));
assertThat(source).isNotNull();
PhotoLocationExtraPhotosKeywordCSVParser parser = new PhotoLocationExtraPhotosKeywordCSVParser(source);
assertThat(parser).isNotNull();
Map<String, List<String>> parsedMap = null;
try {
parsedMap = parser.parse();
} catch (IOException e) {
// TODO Auto-generated catch block
fail("exception on parse: "+ e.getMessage());
}
assertThat(parsedMap).isNotNull();
assertThat(parsedMap.size()).isEqualTo(3);
assertThat(parsedMap.keySet()).contains("DSC00305.txt","DSC00498.txt","DSC00520.txt");
List<String> photo1 = parsedMap.get("DSC00305.txt");
assertThat(photo1.size()).isEqualTo(2);
assertThat(photo1.get(0)).isNotNull();
assertThat(photo1.get(0)).isEqualTo(bosque.getName());
assertThat(photo1.get(1)).isNotNull();
assertThat(photo1.get(1)).isEqualTo(montanias.getName());
}
示例9: fromBytes
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
public static Message fromBytes(byte[] bytes) throws MessageDeSerializationException
{
try {
ByteBuffer wrapper = ByteBuffer.wrap(bytes);
long timestamp = wrapper.getLong();
int fiberId = wrapper.getInt();
int keyIndex = wrapper.getInt();
int valueNum = wrapper.getInt();
String[] values = new String[valueNum];
for (int i = 0; i < valueNum; i++) {
int vLen = wrapper.getInt();
byte[] v = new byte[vLen];
wrapper.get(v);
values[i] = new String(v, StandardCharsets.UTF_8);
}
int tLen = wrapper.getInt();
byte[] t = new byte[tLen];
wrapper.get(t);
String topic = new String(t, StandardCharsets.UTF_8);
return new Message(keyIndex, values, timestamp, topic, fiberId);
}
catch (Exception e) {
throw new MessageDeSerializationException();
}
}
示例10: dataStringToImage
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
static BufferedImage dataStringToImage(String data) {
final String header = "data:image/";
final int headerLength = header.length();
final String base64Header = "base64,";
if (!data.regionMatches(true, 0, header, 0, headerLength)) {
throw new IllegalArgumentException("Invalid data: " + data);
}
try {
String str = data.substring(headerLength);
int firstSemicolon = str.indexOf(';');
if (!str.regionMatches(true, firstSemicolon + 1, base64Header, 0, base64Header.length())) {
throw new IllegalArgumentException("Invalid data: " + data);
}
int firstComma = str.indexOf(',');
String base64 = str.substring(firstComma + 1);
return ImageIO.read(Base64.getDecoder().wrap(new ByteArrayInputStream(base64.getBytes(StandardCharsets.UTF_8))));
} catch (IndexOutOfBoundsException | IOException e) {
throw new IllegalArgumentException("Invalid data: " + data, e);
}
}
示例11: toJsonInput
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
private JsonObject toJsonInput(InputStream inputStream)
{
StringBuilder stringBuilder = new StringBuilder();
String input = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
try
{
while ((input = bufferedReader.readLine()) != null)
{
stringBuilder.append(input);
}
} catch (IOException e)
{
e.printStackTrace();
}
return new JsonParser().parse(stringBuilder.substring(0)).getAsJsonObject();
}
示例12: gzipBase64
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
/**
* Convert input to bytes using UTF-8, gzip it, then base-64 it.
*
* @param data the input data, as a String
* @return the compressed output, as a String
*/
private static String gzipBase64(String data) {
try {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length() / 4 + 1)) {
try (OutputStream baseos = Base64.getEncoder().wrap(baos)) {
try (GZIPOutputStream zos = new GZIPOutputStream(baseos)) {
try (OutputStreamWriter writer = new OutputStreamWriter(zos, StandardCharsets.UTF_8)) {
writer.write(data);
}
}
}
return baos.toString("ISO-8859-1"); // base-64 bytes are ASCII, so this is optimal
}
} catch (IOException ex) {
throw new UncheckedIOException("Failed to gzip base-64 content", ex);
}
}
示例13: getSlaComputationsXls
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
/**
* Return SLA computations as XLS input stream.
*
* @param subscription
* The subscription identifier.
* @param file
* The user file name to use in download response.
* @return the stream ready to be read during the serialization.
*/
@GET
@Path("{subscription:\\d+}/{file:.*.xml}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getSlaComputationsXls(@PathParam("subscription") final int subscription,
@PathParam("file") final String file) {
final JiraSlaComputations slaComputations = getSlaComputations(subscription, false);
final Map<String, Processor<?>> tags = mapTags(slaComputations);
// Get the template data
return AbstractToolPluginResource.download(output -> {
final InputStream template = new ClassPathResource("csv/template/template-sla.xml").getInputStream();
try {
final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
new Template<JiraSlaComputations>(IOUtils.toString(template, StandardCharsets.UTF_8)).write(writer,
tags, slaComputations);
writer.flush();
} finally {
IOUtils.closeQuietly(template);
}
}, file).build();
}
示例14: upload
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
@HttpPost
@Route("books/upload")
public void upload() {
// curl -F "key=key1" -F "comment=this is an txt file" -F "[email protected]/Users/WXQ/Desktop/filetest.txt" http://127.0.0.1:8090/api/books/upload
Request request = Request();
Response response = Response();
Map<String, List<String>> params = request.getFormParams();
System.out.println(GsonFactory.getGson().toJson(params));
FormFile file = request.getFile("file1").orElse(null);
if (file != null) {
String data = new String(file.getData(), StandardCharsets.UTF_8);
response.end(data);
} else {
response.end("get form file failed");
}
}
示例15: getInventoryManifestSuccess
import java.nio.charset.StandardCharsets; //导入依赖的package包/类
@Test
public void getInventoryManifestSuccess() throws Exception {
InventoryManifest expectedManifest = manifest();
byte[] expectedManifestBytes = manifestBytes(expectedManifest);
when(mockS3JsonObject.getObjectContent()).thenReturn(new S3ObjectInputStream(
new ByteArrayInputStream(expectedManifestBytes), null));
String expectedChecksum = "a6121a6a788be627a68d7e9def9f6968";
byte[] expectedChecksumBytes = expectedChecksum.getBytes(StandardCharsets.UTF_8);
when(mockS3ChecksumObject.getObjectContent()).thenReturn(new S3ObjectInputStream(
new ByteArrayInputStream(expectedChecksumBytes), null));
when(mockS3Client.getObject(getObjectRequestCaptor.capture()))
.thenReturn(mockS3JsonObject)
.thenReturn(mockS3ChecksumObject);
InventoryManifest result = retriever.getInventoryManifest();
assertThat(result, is(expectedManifest));
List<GetObjectRequest> request = getObjectRequestCaptor.getAllValues();
assertThat(request.get(0).getBucketName(), is("testBucketName"));
assertThat(request.get(0).getKey(), is("testBucketKey/manifest.json"));
assertThat(request.get(1).getBucketName(), is("testBucketName"));
assertThat(request.get(1).getKey(), is("testBucketKey/manifest.checksum"));
}