Java Code Examples for java.nio.charset.StandardCharsets

The following are top voted examples for showing how to use java.nio.charset.StandardCharsets. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: cas-5.1.0   File: EncodingUtils.java   View source code 7 votes vote down vote up
/**
 * 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);
    }
}
 
Example 2
Project: cactoos   File: InputAsBytesTest.java   View source code 7 votes vote down vote up
@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("друг!")
        )
    );
}
 
Example 3
Project: java-restclient   File: RestClientSyncTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 4
Project: Word2VecfJava   File: WordVectorSerializer.java   View source code 6 votes vote down vote up
/** 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();
	}
}
 
Example 5
Project: plugin-km-confluence   File: ConfluencePluginResourceTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 6
Project: apollo-custom   File: DefaultApplicationProvider.java   View source code 6 votes vote down vote up
@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);
  }
}
 
Example 7
Project: uroborosql   File: UroboroSQLTest.java   View source code 6 votes vote down vote up
@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();
	}
}
 
Example 8
Project: buenojo   File: PhotoLocationExtraPhotosKeywordCSVParserTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 9
Project: paraflow   File: MessageUtils.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 10
Project: ColorMOTD   File: MotdServerIcon.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 11
Project: CloudNet   File: CloudFlareService.java   View source code 6 votes vote down vote up
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();
}
 
Example 12
Project: JavaSDK   File: PortfolioDataFile.java   View source code 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example 13
Project: plugin-bt-jira   File: JiraExportPluginResource.java   View source code 6 votes vote down vote up
/**
 * 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();

}
 
Example 14
Project: Razor   File: BookController.java   View source code 6 votes vote down vote up
@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");
    }
}
 
Example 15
Project: s3-inventory-usage-examples   File: InventoryManifestRetrieverTest.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 16
Project: ACHelper   File: ProblemSync.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 17
Project: elasticsearch_my   File: BulkRequestTests.java   View source code 6 votes vote down vote up
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}"));
}
 
Example 18
Project: beaker-notebook-archive   File: ConnectionStringHolder.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 19
Project: oryx2   File: SecureAPIConfigIT.java   View source code 6 votes vote down vote up
@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);
  }
}
 
Example 20
Project: CloudNet   File: NetworkUtils.java   View source code 6 votes vote down vote up
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();
        }
    }

}
 
Example 21
Project: bootstrap   File: ValidationJSonIT.java   View source code 5 votes vote down vote up
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();
	}
}
 
Example 22
Project: beaker-notebook-archive   File: KernelSocketsZMQ.java   View source code 5 votes vote down vote up
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;
}
 
Example 23
Project: matrix-appservice-email   File: EmailFormatterOutboud.java   View source code 5 votes vote down vote up
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;
}
 
Example 24
Project: aws-codecommit-trigger-plugin   File: JenkinsIT.java   View source code 5 votes vote down vote up
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);
}
 
Example 25
Project: poppynotes   File: NoteEncryptionServiceTest.java   View source code 5 votes vote down vote up
@Test
public void testDecryptEncryptWithFullContent_withInvalidRequestJson_shouldStillWork() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
	String noteJson = "{\"title\":\"secret stuff\",\"content\":null,\"userId\":1,\"lastEdit\":null,\"pinned\":false,\"initVector\":null";
	byte[] key = createKey();
	
	InputStream encryptedStream = service.encryptNote(new ByteArrayInputStream(noteJson.getBytes(StandardCharsets.UTF_8)), EncryptionUtils.encodeBase64(key), "[email protected]");
	String encryptedResult = IOUtils.toString(encryptedStream, StandardCharsets.UTF_8);
	assertEquals("broken json should be unchanged",noteJson,encryptedResult);

	InputStream decryptedStream = service.decryptNote(new ByteArrayInputStream(encryptedResult.getBytes(StandardCharsets.UTF_8)), EncryptionUtils.encodeBase64(key), "[email protected]");
	String decryptedResult = IOUtils.toString(decryptedStream, StandardCharsets.UTF_8);
	
	assertEquals("broken json should be unchanged",noteJson,decryptedResult);
}
 
Example 26
Project: elasticsearch_my   File: BulkRequestTests.java   View source code 5 votes vote down vote up
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]"));
}
 
Example 27
Project: maxcube-java   File: CliRendererTest.java   View source code 5 votes vote down vote up
@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()))));
    });
}
 
Example 28
Project: RollenspielAlexaSkill   File: SoloRoleplayGameTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 29
Project: wamp2spring   File: PublishedMessageTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 30
Project: reactive-pg-client   File: DataType.java   View source code 5 votes vote down vote up
@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);
}
 
Example 31
Project: bilibili-api   File: ErrorResponseConverterInterceptor.java   View source code 5 votes vote down vote up
@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();
}
 
Example 32
Project: alfresco-repository   File: ApplyTemplateMethodTest.java   View source code 5 votes vote down vote up
@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);

}
 
Example 33
Project: spring-boot-start-current   File: Export.java   View source code 5 votes vote down vote up
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() );
}
 
Example 34
Project: oscm   File: MySubscriptionsCtrl.java   View source code 5 votes vote down vote up
private String encodeBase64(String str) {
    return Base64.encodeBase64URLSafeString(
            str.getBytes(StandardCharsets.UTF_8));
}
 
Example 35
Project: dble   File: ViewMeta.java   View source code 5 votes vote down vote up
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;
    }
 
Example 36
Project: cmakeify   File: TestCmakeify.java   View source code 5 votes vote down vote up
@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);
}
 
Example 37
Project: openjdk-jdk10   File: JdiInitiator.java   View source code 5 votes vote down vote up
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();
    }
}
 
Example 38
Project: incubator-netbeans   File: OptionsExportModel.java   View source code 5 votes vote down vote up
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();
}
 
Example 39
Project: Jupiter   File: NBTInputStream.java   View source code 5 votes vote down vote up
@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);
}
 
Example 40
Project: BLE-HID-Peripheral-for-Android   File: HidPeripheral.java   View source code 5 votes vote down vote up
/**
 * Set the serial number
 *
 * @param newSerialNumber the number
 */
public final void setSerialNumber(@NonNull final String newSerialNumber) {
    // length check
    final byte[] deviceNameBytes = newSerialNumber.getBytes(StandardCharsets.UTF_8);
    if (deviceNameBytes.length > DEVICE_INFO_MAX_LENGTH) {
        // shorten
        final byte[] bytes = new byte[DEVICE_INFO_MAX_LENGTH];
        System.arraycopy(deviceNameBytes, 0, bytes, 0, DEVICE_INFO_MAX_LENGTH);
        serialNumber = new String(bytes, StandardCharsets.UTF_8);
    } else {
        serialNumber = newSerialNumber;
    }
}