Java 类java.nio.charset.StandardCharsets 实例源码

项目:java-restclient    文件:RestClientSyncTest.java   
@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());
}
项目:Word2VecfJava    文件:WordVectorSerializer.java   
/** 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();
    }
}
项目:plugin-km-confluence    文件:ConfluencePluginResourceTest.java   
@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));
}
项目:apollo-custom    文件:DefaultApplicationProvider.java   
@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);
  }
}
项目:uroborosql    文件:UroboroSQLTest.java   
@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();
    }
}
项目:buenojo    文件:PhotoLocationExtraPhotosKeywordCSVParserTest.java   
@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());
}
项目:paraflow    文件:MessageUtils.java   
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();
    }
}
项目:ColorMOTD    文件:MotdServerIcon.java   
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);
    }
}
项目:cas-5.1.0    文件:EncodingUtils.java   
/**
 * 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);
    }
}
项目:CloudNet    文件:CloudFlareService.java   
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();
}
项目:JavaSDK    文件:PortfolioDataFile.java   
/**
 * 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);
  }
}
项目:plugin-bt-jira    文件:JiraExportPluginResource.java   
/**
 * 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();

}
项目:s3-inventory-usage-examples    文件:InventoryManifestRetrieverTest.java   
@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"));
}
项目:ACHelper    文件:ProblemSync.java   
private String readFromFile(String fileName) throws IOException {
    Path path = Paths.get(directory, fileName);
    if (!Files.exists(path)) {
        writeToFile(fileName, "");
        return "";
    } else {
        int fileSize = (int) new File(path.toString()).length();
        char[] data = new char[Math.min(fileSize, maxLength)];
        BufferedReader reader = newBufferedReader(path, StandardCharsets.UTF_8);
        fileSize = reader.read(data, 0, data.length);
        String result = new String(data, 0, fileSize);
        if (fileSize == maxLength) {
            result += "...";
        }
        return result;
    }
}
项目:elasticsearch_my    文件:BulkRequestTests.java   
public void testSimpleBulk4() throws Exception {
    String bulkAction = copyToStringFromClasspath("/org/elasticsearch/action/bulk/simple-bulk4.json");
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, null, XContentType.JSON);
    assertThat(bulkRequest.numberOfActions(), equalTo(4));
    assertThat(((UpdateRequest) bulkRequest.requests().get(0)).id(), equalTo("1"));
    assertThat(((UpdateRequest) bulkRequest.requests().get(0)).retryOnConflict(), equalTo(2));
    assertThat(((UpdateRequest) bulkRequest.requests().get(0)).doc().source().utf8ToString(), equalTo("{\"field\":\"value\"}"));
    assertThat(((UpdateRequest) bulkRequest.requests().get(1)).id(), equalTo("0"));
    assertThat(((UpdateRequest) bulkRequest.requests().get(1)).type(), equalTo("type1"));
    assertThat(((UpdateRequest) bulkRequest.requests().get(1)).index(), equalTo("index1"));
    Script script = ((UpdateRequest) bulkRequest.requests().get(1)).script();
    assertThat(script, notNullValue());
    assertThat(script.getIdOrCode(), equalTo("counter += param1"));
    assertThat(script.getLang(), equalTo("javascript"));
    Map<String, Object> scriptParams = script.getParams();
    assertThat(scriptParams, notNullValue());
    assertThat(scriptParams.size(), equalTo(1));
    assertThat(((Integer) scriptParams.get("param1")), equalTo(1));
    assertThat(((UpdateRequest) bulkRequest.requests().get(1)).upsertRequest().source().utf8ToString(), equalTo("{\"counter\":1}"));
}
项目:beaker-notebook-archive    文件:ConnectionStringHolder.java   
/**
 * MSSQL driver do not return password, so we need to parse it manually
 * @param property
 * @param connectionString
 * @return
 */
protected static String getProperty(String property, String connectionString) {
  String ret = null;
  if (property != null && !property.isEmpty() && connectionString != null && !connectionString.isEmpty()) {
    for (NameValuePair param : URLEncodedUtils.parse(connectionString, StandardCharsets.UTF_8, SEPARATORS)) {
      if(property.equals(param.getName())){
        ret = param.getValue();
        break;
      }
    }
  }
  return ret;
}
项目:oryx2    文件:SecureAPIConfigIT.java   
@Test
public void testUserPassword() throws Exception {
  startServer(buildUserPasswordConfig());

  Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication("oryx", "pass".toCharArray());
    }
  });

  try {
    String response = Resources.toString(
        new URL("http://localhost:" + getHTTPPort() + "/helloWorld"),
        StandardCharsets.UTF_8);
    assertEquals("Hello, World", response);
  } finally {
    Authenticator.setDefault(null);
  }
}
项目:cactoos    文件:InputAsBytesTest.java   
@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("друг!")
        )
    );
}
项目:rubenlagus-TelegramBots    文件:DefaultAbsSender.java   
@Override
protected final <T extends Serializable, Method extends BotApiMethod<T>> T sendApiMethod(Method method) throws TelegramApiException {
    method.validate();
    String responseContent;
    try {
        String url = getBaseUrl() + method.getMethod();
        HttpPost httppost = new HttpPost(url);
        httppost.setConfig(requestConfig);
        httppost.addHeader("charset", StandardCharsets.UTF_8.name());
        httppost.setEntity(new StringEntity(objectMapper.writeValueAsString(method), ContentType.APPLICATION_JSON));
        try (CloseableHttpResponse response = httpclient.execute(httppost)) {
            HttpEntity ht = response.getEntity();
            BufferedHttpEntity buf = new BufferedHttpEntity(ht);
            responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
        }
    } catch (IOException e) {
        throw new TelegramApiException("Unable to execute " + method.getMethod() + " method", e);
    }

    return method.deserializeResponse(responseContent);
}
项目:CloudNet    文件:NetworkUtils.java   
public static void writeWrapperKey()
{
    Random random = new Random();

    Path path = Paths.get("WRAPPER_KEY.cnd");
    if (!Files.exists(path))
    {
        StringBuilder stringBuilder = new StringBuilder();
        for (short i = 0; i < 4096; i++)
            stringBuilder.append(values[random.nextInt(values.length)]);

        try
        {
            Files.createFile(path);
            try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(Files.newOutputStream(path), StandardCharsets.UTF_8))
            {
                outputStreamWriter.write(stringBuilder.substring(0) + "\n");
                outputStreamWriter.flush();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

}
项目:bootstrap    文件:ValidationJSonIT.java   
private List<Map<String, Object>> checkResponse(final HttpResponse response) throws IOException {
    try {
        Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode());
        final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
        Assert.assertNotNull(content);
        @SuppressWarnings("all")
        final Map<String, Map<String, List<Map<String, Object>>>> result = (Map<String, Map<String, List<Map<String, Object>>>>) new ObjectMapperTrim()
                .readValue(content, HashMap.class);

        Assert.assertFalse(result.isEmpty());
        final Map<String, List<Map<String, Object>>> errors = result.get("errors");
        Assert.assertNotNull(errors);
        Assert.assertFalse(errors.isEmpty());
        final List<Map<String, Object>> errorsOnName = errors.get("name");
        Assert.assertNotNull(errorsOnName);
        Assert.assertEquals(2, errorsOnName.size());
        Assert.assertNotNull(errorsOnName.get(0));
        Assert.assertNotNull(errorsOnName.get(1));
        final List<Map<String, Object>> errorsOnYear = errors.get("year");
        Assert.assertNotNull(errorsOnYear);
        Assert.assertEquals(1, errorsOnYear.size());
        Assert.assertNotNull(errorsOnYear.get(0));
        return errorsOnName;
    } finally {
        response.getEntity().getContent().close();
    }
}
项目:beaker-notebook-archive    文件:KernelSocketsZMQ.java   
private String verifyDelim(ZFrame zframe) {
  String delim = new String(zframe.getData(), StandardCharsets.UTF_8);
  if (!DELIM.equals(delim)) {
    throw new RuntimeException("Delimiter <IDS|MSG> not found");
  }
  return delim;
}
项目:matrix-appservice-email    文件:EmailFormatterOutboud.java   
private MimeMessage makeEmail(TokenData data, _EmailTemplate template, MimeMultipart body, boolean allowReply) throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(session);
    if (allowReply) {
        msg.setReplyTo(InternetAddress.parse(recvCfg.getEmail().replace("%KEY%", data.getKey())));
    }

    String sender = data.isSelf() ? sendCfg.getName() : data.getSenderName();
    msg.setFrom(new InternetAddress(sendCfg.getEmail(), sender, StandardCharsets.UTF_8.name()));
    msg.setSubject(processToken(data, template.getSubject()));
    msg.setContent(body);
    return msg;
}
项目:aws-codecommit-trigger-plugin    文件:JenkinsIT.java   
public JenkinsIT() throws IOException {
    String sqsMessage = IOUtils.toString(Utils.getResource(this.getClass(), "us-east-1.json"), StandardCharsets.UTF_8);
    GitSCM scm = MockGitSCM.fromSqsMessage(sqsMessage);
    this.fixture = new ProjectFixture()
        .setSqsMessage(sqsMessage)
        .setSubscribeInternalScm(true)
        .setScm(scm)
        .setShouldStarted(Boolean.TRUE);
}
项目:elasticsearch_my    文件:BulkRequestTests.java   
public void testSimpleBulk7() throws Exception {
    String bulkAction = copyToStringFromClasspath("/org/elasticsearch/action/bulk/simple-bulk7.json");
    BulkRequest bulkRequest = new BulkRequest();
    IllegalArgumentException exc = expectThrows(IllegalArgumentException.class,
        () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, null, XContentType.JSON));
    assertThat(exc.getMessage(),
        containsString("Malformed action/metadata line [5], expected a simple value for field [_unkown] but found [START_ARRAY]"));
}
项目:maxcube-java    文件:CliRendererTest.java   
@Test
public void checkThatAsciiTableFormattingWorls() throws Exception {
    Cube cube = new Cube(randomAsciiOfLength(10), randomInt(10), randomAsciiOfLength(10), LocalDateTime.now());
    int roomCount = randomIntBetween(1, 10);
    for (int i = 0; i < roomCount; i++) {
        cube.getRooms().add(createRandomRoom(i));
    }

    Renderer renderer = new CliRenderer();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    renderer.render(cube, bos);

    String output = bos.toString(StandardCharsets.UTF_8.name());
    logger.info(output);

    String[] lines = output.split("\n");

    // drawing lines: roomCount * 2 + 3 (start line, headers, separator) + 6 (cube info table)
    int expectedTotalLines = roomCount * 2 + 3 + 6;
    assertThat(lines.length, is(expectedTotalLines));

    // second line should contain all the headers
    for (String header : CliRenderer.HEADERS) {
        // skip cube info table
        assertThat(lines[7], containsString(header));
    }

    // ensure all rooms are displayed
    cube.getRooms().stream().forEach(room -> {
        String line = findLineForRoom(room, lines);
        assertThat(line, containsString(String.valueOf(room.isWindowOpen())));
        assertThat(line, containsString(String.valueOf(room.isLowBattery())));
        assertThat(line, containsString(String.valueOf(room.getValvePositionInPercent())));
        assertThat(line, containsString(String.valueOf(room.getId())));
        DecimalFormat df = new DecimalFormat("##.#");
        assertThat(line, containsString(String.valueOf(df.format(room.getCurrentTemperature()))));
    });
}
项目:RollenspielAlexaSkill    文件:SoloRoleplayGameTest.java   
@Test
public void testExampleSoloOutput() {
    String expected = TextUtil.readResource("expected_solotext_output.txt", StandardCharsets.ISO_8859_1);
    expected = TextUtil.makeEndl(expected);
    String actual = TextUtil.makeEndl(soloData.toString());
    Assert.assertEquals(expected, actual);
}
项目:wamp2spring    文件:PublishedMessageTest.java   
@Test
public void deserializeTest() throws IOException {
    String json = "[17, 239714735, 4429313566]";

    PublishedMessage publishedMessage = WampMessage.deserialize(getJsonFactory(),
            json.getBytes(StandardCharsets.UTF_8));

    assertThat(publishedMessage.getCode()).isEqualTo(17);
    assertThat(publishedMessage.getRequestId()).isEqualTo(239714735L);
    assertThat(publishedMessage.getPublicationId()).isEqualTo(4429313566L);
}
项目:reactive-pg-client    文件:DataType.java   
@Override
public void encodeText(Buffer value, ByteBuf buff) {
  int index = buff.writerIndex();
  buff.setByte(index + 4, '\\');
  buff.setByte(index + 5, 'x');
  // todo : optimize - no need to create an intermediate string here
  int len = buff.setCharSequence(index + 6, printHexBinary(value.getBytes()), StandardCharsets.UTF_8);
  buff.writeInt(2 + len);
  buff.writerIndex(index + 2 + len);
}
项目:bilibili-api    文件:ErrorResponseConverterInterceptor.java   
@Override
public Response intercept(Chain chain) throws IOException {
    Response response = chain.proceed(chain.request());
    ResponseBody responseBody = response.body();

    BufferedSource bufferedSource = responseBody.source();
    bufferedSource.request(Long.MAX_VALUE);
    Buffer buffer = bufferedSource.buffer();
    //必须要 clone 一次, 否则将导致流关闭
    String json = buffer.clone().readString(StandardCharsets.UTF_8);

    JsonObject jsonObject = JSON_PARSER.parse(json).getAsJsonObject();
    JsonElement code = jsonObject.get("code");
    //code 字段不存在
    if (code == null) {
        return response;
    }
    //code 为 0
    if (code.getAsInt() == 0) {
        return response;
    }
    //data 字段不存在
    if (jsonObject.get("data") == null) {
        return response;
    }
    jsonObject.add("data", JsonNull.INSTANCE);
    return response.newBuilder()
            .body(ResponseBody.create(
                    responseBody.contentType(),
                    GSON.toJson(jsonObject))
            ).build();
}
项目:alfresco-repository    文件:ApplyTemplateMethodTest.java   
@Test
public void testExecute_vanillaRepositoryJSON() throws Exception
{
    ChildAssociationRef templateAssoc = createContent(testRootFolder.getNodeRef(),
                                                      "template1.json",
                                                      ApplyTemplateMethodTest.class
                                                                  .getResourceAsStream(TEST_TEMPLATE_1_JSON_NAME),
                                                      MimetypeMap.MIMETYPE_JSON,
                                                      StandardCharsets.UTF_8.name());
    ApplyTemplateMethod applyTemplateMethod = new ApplyTemplateMethod(environment);

    NewVirtualReferenceMethod newVirtualReferenceMethod = new NewVirtualReferenceMethod(templateAssoc.getChildRef(),
                                                                                        "/",
                                                                                        virtualFolder1NodeRef,
                                                                                        VANILLA_PROCESSOR_JS_CLASSPATH);
    Reference ref = Protocols.VANILLA.protocol.dispatch(newVirtualReferenceMethod,
                                                        null);
    VirtualFolderDefinition structure = ref.execute(applyTemplateMethod);

    String templateName = structure.getName();
    assertEquals("Test",
                 templateName);

    List<VirtualFolderDefinition> children = structure.getChildren();
    assertEquals(2,
                 children.size());

    VirtualFolderDefinition child1 = structure.findChildByName("Node1");
    assertTrue(child1 != null);

    VirtualFolderDefinition child2 = structure.findChildByName("Node2");
    assertTrue(child2 != null);

}
项目:spring-boot-start-current    文件:Export.java   
public static void exportCsv ( HttpServletResponse response , String fileName ,
                               LinkedHashMap< String, String > titleMap , List< ? > dataList ) throws IOException {
    String content = convertCsv( titleMap , dataList );

    // 导出 csv
    setResponse( response , "csv" , fileName );
    response.getOutputStream().write( content.getBytes( StandardCharsets.UTF_8 ) );

    POIFSFileSystem poifsFileSystem = new POIFSFileSystem();
    poifsFileSystem.createDocument( new ByteArrayInputStream( content.getBytes( "GBK" ) ) , "WordDocument" );
    poifsFileSystem.writeFilesystem( response.getOutputStream() );
}
项目:oscm    文件:MySubscriptionsCtrl.java   
private String encodeBase64(String str) {
    return Base64.encodeBase64URLSafeString(
            str.getBytes(StandardCharsets.UTF_8));
}
项目:dble    文件:ViewMeta.java   
public ErrorPacket init(boolean isReplace) {

        ViewMetaParser viewParser = new ViewMetaParser(createSql);
        try {
            viewParser.parseCreateView(this);
            //check if the select part has
            this.checkDuplicate(viewParser, isReplace);

            SQLSelectStatement selectStatement = (SQLSelectStatement) RouteStrategyFactory.getRouteStrategy().parserSQL(selectSql);

            MySQLPlanNodeVisitor msv = new MySQLPlanNodeVisitor(this.schema, 63, tmManager, true);
            msv.visit(selectStatement.getSelect().getQuery());
            PlanNode selNode = msv.getTableNode();
            selNode.setUpFields();

            //set the view column name into
            this.setFieldsAlias(selNode);

            viewQuery = new QueryNode(selNode);
        } catch (Exception e) {
            //the select part sql is wrong & report the error
            ErrorPacket error = new ErrorPacket();
            error.setMessage(e.getMessage() == null ? "unknow error".getBytes(StandardCharsets.UTF_8) :
                    e.getMessage().getBytes(StandardCharsets.UTF_8));
            error.setErrNo(CREATE_VIEW_ERROR);
            return error;
        }
        return null;
    }
项目:cmakeify    文件:TestCmakeify.java   
@Test
public void dumpIsSelfHost() throws IOException {
  CMakeifyYml config = new CMakeifyYml();
  System.out.printf(new Yaml().dump(config));
  File yaml = new File("test-files/simpleConfiguration/cmakeify.yml");
  yaml.getParentFile().mkdirs();
  Files.write("", yaml, StandardCharsets.UTF_8);
  String result1 = main("-wf", yaml.getParent(), "--dump");
  yaml.delete();
  Files.write(result1, yaml, StandardCharsets.UTF_8);
  System.out.print(result1);
  String result2 = main("-wf", yaml.getParent(), "--dump");
  assertThat(result2).isEqualTo(result1);
}
项目:openjdk-jdk10    文件:JdiInitiator.java   
private String readFile(File f) {
    try {
        return new String(Files.readAllBytes(f.toPath()),
                StandardCharsets.UTF_8);
    } catch (IOException ex) {
        return "error reading " + f + " : " + ex.toString();
    }
}
项目:incubator-netbeans    文件:OptionsExportModel.java   
private void createEnabledItemsInfo(ZipOutputStream out, ArrayList<String> enabledItems) throws IOException {
    out.putNextEntry(new ZipEntry(ENABLED_ITEMS_INFO));
    if (!enabledItems.isEmpty()) {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
        for (String item : enabledItems) {
            writer.append(item).append('\n');
        }
        writer.flush();
    }
    // Complete the entry
    out.closeEntry();
}
项目:Jupiter    文件:NBTInputStream.java   
@Override
public String readUTF() throws IOException {
    int length = (int) (network ? VarInt.readUnsignedVarInt(stream) : this.readUnsignedShort());
    byte[] bytes = new byte[length];
    this.stream.read(bytes);
    return new String(bytes, StandardCharsets.UTF_8);
}