Java Code Examples for java.nio.charset.StandardCharsets.UTF_8

The following are Jave code examples for showing how to use UTF_8 of the java.nio.charset.StandardCharsets class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: spark-examples   File: ApiGatewayResponse.java   Source Code and License Vote up 6 votes
public ApiGatewayResponse build() {
    String body = null;
    if (rawBody != null) {
        body = rawBody;
    } else if (objectBody != null) {
        try {
            body = objectMapper.writeValueAsString(objectBody);
        } catch (JsonProcessingException e) {
            LOG.error("failed to serialize object", e);
            throw new RuntimeException(e);
        }
    } else if (binaryBody != null) {
        body = new String(Base64.getEncoder().encode(binaryBody), StandardCharsets.UTF_8);
    }
    return new ApiGatewayResponse(statusCode, body, headers, base64Encoded);
}
 
Example 2
Project: elasticsearch_my   File: Ec2NameResolver.java   Source Code and License Vote up 6 votes
/**
 * @param type the ec2 hostname type to discover.
 * @return the appropriate host resolved from ec2 meta-data, or null if it cannot be obtained.
 * @see CustomNameResolver#resolveIfPossible(String)
 */
@SuppressForbidden(reason = "We call getInputStream in doPrivileged and provide SocketPermission")
public InetAddress[] resolve(Ec2HostnameType type) throws IOException {
    InputStream in = null;
    String metadataUrl = AwsEc2ServiceImpl.EC2_METADATA_URL + type.ec2Name;
    try {
        URL url = new URL(metadataUrl);
        logger.debug("obtaining ec2 hostname from ec2 meta-data url {}", url);
        URLConnection urlConnection = SocketAccess.doPrivilegedIOException(url::openConnection);
        urlConnection.setConnectTimeout(2000);
        in = SocketAccess.doPrivilegedIOException(urlConnection::getInputStream);
        BufferedReader urlReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

        String metadataResult = urlReader.readLine();
        if (metadataResult == null || metadataResult.length() == 0) {
            throw new IOException("no gce metadata returned from [" + url + "] for [" + type.configName + "]");
        }
        // only one address: because we explicitly ask for only one via the Ec2HostnameType
        return new InetAddress[] { InetAddress.getByName(metadataResult) };
    } catch (IOException e) {
        throw new IOException("IOException caught when fetching InetAddress from [" + metadataUrl + "]", e);
    } finally {
        IOUtils.closeWhileHandlingException(in);
    }
}
 
Example 3
Project: java-course   File: CijeliBrojeviKonzola.java   Source Code and License Vote up 6 votes
/**
 * Početna točka programa CijeliBrojeviKonzola. Parametri komandne linije se ne koriste.
 * @param args Parametri komandne linije.
 * @throws IOException Problem s čitanjem s konzole.
 */
public static void main(String[] args) throws IOException {
	BufferedReader ulaz = new BufferedReader(new InputStreamReader(System.in,
			StandardCharsets.UTF_8));

	while (true) {
		System.out.print("Unesite broj> "); 
		String brojString = ulaz.readLine();
		if(brojString.trim().equals("quit")) {
			System.exit(0);
		}
		int broj = 0;
		try {
			broj = Integer.parseInt(brojString);
		} catch (NumberFormatException e) {
			System.out.println("Neispravan unos!");
			continue;
		}
		System.out.print("Paran: " + (CijeliBrojevi.jeParan(broj) ? "DA" : "NE") + ", ");
		System.out.print("neparan: " + (CijeliBrojevi.jeNeparan(broj) ? "DA" : "NE") + ", ");
		System.out.println("prim: " + (CijeliBrojevi.jeProst(broj) ? "DA" : "NE"));
	}
}
 
Example 4
Project: allure-java   File: AllureHttpClientResponse.java   Source Code and License Vote up 6 votes
@Override
public void process(final HttpResponse response,
                    final HttpContext context) throws HttpException, IOException {

    final HttpResponseAttachment.Builder builder = create("Response")
            .withResponseCode(response.getStatusLine().getStatusCode());

    Stream.of(response.getAllHeaders())
            .forEach(header -> builder.withHeader(header.getName(), header.getValue()));

    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    response.getEntity().writeTo(os);

    final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
    builder.withBody(body);

    final HttpResponseAttachment responseAttachment = builder.build();
    processor.addAttachment(responseAttachment, renderer);
}
 
Example 5
Project: light-session-4j   File: HttpClientUtils.java   Source Code and License Vote up 5 votes
public static String readResponse(InputStream stream) throws IOException {

        byte[] data = new byte[100];
        int read;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((read = stream.read(data)) != -1) {
            out.write(data, 0, read);
        }
        return new String(out.toByteArray(), StandardCharsets.UTF_8);
    }
 
Example 6
Project: openjdk-jdk10   File: Utils.java   Source Code and License Vote up 5 votes
/**
 * Get the Charset from the Content-encoding header. Defaults to
 * UTF_8
 */
public static Charset charsetFrom(HttpHeaders headers) {
    String encoding = headers.firstValue("Content-encoding")
            .orElse("UTF_8");
    try {
        return Charset.forName(encoding);
    } catch (IllegalArgumentException e) {
        return StandardCharsets.UTF_8;
    }
}
 
Example 7
Project: r8   File: ProguardConfigurationParser.java   Source Code and License Vote up 5 votes
ProguardFileParser(Path path) throws IOException {
  this.path = path;
  contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
  baseDirectory = path.getParent();
  if (baseDirectory == null) {
    // path parent can be null only if it's root dir or if its a one element path relative to
    // current directory.
    baseDirectory = Paths.get(".");
  }
}
 
Example 8
Project: java-course   File: SearchEngine.java   Source Code and License Vote up 5 votes
/**
 * Fills stopwords collection from stopwords file.
 * 
 * @throws IOException
 *             On error with reading a file.
 */
private void getStopWords() throws IOException {
    stopWords = new HashSet<String>();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(
            stopwords, StandardCharsets.UTF_8))) {
        String word = reader.readLine().toLowerCase();

        while (word != null && !word.isEmpty()) {
            stopWords.add(word);
            word = reader.readLine();
        }
    }
}
 
Example 9
Project: hygene   File: GraphArrayFile.java   Source Code and License Vote up 5 votes
/**
 * Reads a cached graph and parses it to the internal graph array data structure.
 *
 * @param graphSize       the number of nodes in the graph
 * @param progressUpdater a {@link ProgressUpdater} to notify interested parties on progress updates
 * @return internal graph array data structure from cache file
 * @throws IOException if the cache file cannot be read
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") // Unique instance per iteration
public int[][] read(final int graphSize, final ProgressUpdater progressUpdater) throws IOException {
    final int[][] graph = new int[graphSize][];

    try (BufferedReader cache = new BufferedReader(new InputStreamReader(
            new FileInputStream(file), StandardCharsets.UTF_8))) {
        String node;
        int nodeIndex = 0;
        while ((node = cache.readLine()) != null) {
            if (nodeIndex % PROGRESS_UPDATE_INTERVAL == 0) {
                progressUpdater.updateProgress(
                        PROGRESS_TOTAL * nodeIndex / graphSize,
                        "Restoring graph from cache...");
            }

            final StringTokenizer nodeTokenizer = new StringTokenizer(node, NODE_VALUE_SEPARATOR);
            graph[nodeIndex] = new int[nodeTokenizer.countTokens()];

            int valueIndex = 0;
            while (nodeTokenizer.hasMoreTokens()) {
                graph[nodeIndex][valueIndex] = Integer.parseInt(nodeTokenizer.nextToken());
                valueIndex++;
            }

            nodeIndex++;
        }
    }

    return graph;
}
 
Example 10
Project: microbean-helm   File: TestDigest.java   Source Code and License Vote up 5 votes
@Test
public void testDigest() throws IOException, NoSuchAlgorithmException {
  final URL redisChart = Thread.currentThread().getContextClassLoader().getResource("redis-0.5.1/redis-0.5.1.tgz");
  assertNotNull(redisChart);
  final URL digest = Thread.currentThread().getContextClassLoader().getResource("redis-0.5.1/digest");
  assertNotNull(digest);
  assertTrue(digest.getProtocol().equals("file"));
  String expectedDigest = null;
  try (final BufferedReader reader = new BufferedReader(new InputStreamReader(digest.openStream(), StandardCharsets.UTF_8))) {
    assertNotNull(reader);
    expectedDigest = reader.readLine();
    assertNotNull(expectedDigest);
    expectedDigest = expectedDigest.toUpperCase();
  }
  final MessageDigest md = MessageDigest.getInstance("SHA-256");
  assertNotNull(md);
  ByteBuffer buffer = null;
  try (final InputStream rawInputStream = redisChart.openStream();
       final BufferedInputStream stream = rawInputStream instanceof BufferedInputStream ? (BufferedInputStream)rawInputStream : new BufferedInputStream(rawInputStream)) {
    assertNotNull(rawInputStream);
    assertNotNull(stream);
    buffer = readByteBuffer(stream);
  }
  assertNotNull(buffer);
  md.update(buffer);
  assertEquals(expectedDigest, DatatypeConverter.printHexBinary(md.digest()));
}
 
Example 11
Project: grpc-spring-security-demo   File: BasicAuthenticationInterceptor.java   Source Code and License Vote up 5 votes
private String[] decodeBasicAuth(String authHeader) {
    String basicAuth;
    try {
        basicAuth = new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
    } catch (IllegalArgumentException | IndexOutOfBoundsException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }

    int delim = basicAuth.indexOf(":");
    if (delim == -1) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }

    return new String[] { basicAuth.substring(0, delim), basicAuth.substring(delim + 1) };
}
 
Example 12
Project: kafka-0.11.0.0-src-with-comment   File: OffsetCheckpoint.java   Source Code and License Vote up 5 votes
/**
 * @throws IOException if any file operation fails with an IO exception
 */
public void write(final Map<TopicPartition, Long> offsets) throws IOException {
    synchronized (lock) {
        // write to temp file and then swap with the existing file
        final File temp = new File(file.getAbsolutePath() + ".tmp");

        final FileOutputStream fileOutputStream = new FileOutputStream(temp);
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8))) {
            writeIntLine(writer, VERSION);
            writeIntLine(writer, offsets.size());

            for (final Map.Entry<TopicPartition, Long> entry : offsets.entrySet()) {
                writeEntry(writer, entry.getKey(), entry.getValue());
            }

            writer.flush();
            fileOutputStream.getFD().sync();
        }

        Utils.atomicMoveWithFallback(temp.toPath(), file.toPath());
    }
}
 
Example 13
Project: Hydrograph   File: ProjectStructureCreator.java   Source Code and License Vote up 5 votes
private void updateMavenFile(String source, IProject project) throws CoreException {
	try{
		IFile destinationFile = project.getFile(source);
		java.nio.file.Path path = Paths.get(destinationFile.getLocationURI());
		Charset charset = StandardCharsets.UTF_8;
		String content = new String(Files.readAllBytes(path), charset);
		content = content.replaceAll(TEMPLATE_PROJECT_NAME, project.getName());
		Files.write(path, content.getBytes(charset));
	} catch (IOException exception) {
		logger.debug("Could not change the group and artifact name");
		throw new CoreException(new MultiStatus(Activator.PLUGIN_ID, 100, "Could not change the group and artifact name", exception));
	}
}
 
Example 14
Project: JavaRushTasks   File: Solution.java   Source Code and License Vote up 5 votes
public static void main(String[] args) throws IOException {
    String fileName = null;
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)))
    {fileName = reader.readLine();}

    String content = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);
    String[] words = content.split(" ");

    StringBuilder result = getLine(words);
    System.out.println(result.toString());
}
 
Example 15
Project: firefox-tv   File: HostScreencapScreenshotStrategy.java   Source Code and License Vote up 5 votes
private static String readInput(InputStream stream) throws IOException {
    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
        final StringBuilder builder = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        return builder.toString();
    }
}
 
Example 16
Project: neo-java   File: RegisterExclusiveData.java   Source Code and License Vote up 5 votes
/**
 * the constructor.
 *
 * @param bb
 *            the ByteBuffer to read.
 */
public RegisterExclusiveData(final ByteBuffer bb) {
	assetType = AssetType.valueOfByte(ModelUtil.getByte(bb));
	nameBa = ModelUtil.getVariableLengthByteArray(bb);
	name = new String(nameBa, StandardCharsets.UTF_8);
	amount = ModelUtil.getFixed8(bb);
	precision = ModelUtil.getByte(bb);
	owner = ECPoint.DeserializeFrom(bb, ECCurve.Secp256r1);
	admin = ModelUtil.getUInt160(bb, false);
}
 
Example 17
Project: gemoc-studio   File: IFileUtils.java   Source Code and License Vote up 5 votes
public static String getStringContent(IFile file) throws CoreException, IOException {
	BufferedReader r = new BufferedReader(new InputStreamReader(file.getContents(), StandardCharsets.UTF_8));     
    String str = null;
    StringBuilder sb = new StringBuilder();
    while ((str = r.readLine()) != null) {
    	sb.append(str+'\n');
    }
	return sb.toString();     
}
 
Example 18
Project: Jenisys3   File: Packet.java   Source Code and License Vote up 4 votes
protected String getString() {
    return new String(this.get(this.getSignedShort()), StandardCharsets.UTF_8);
}
 
Example 19
Project: uroborosql   File: DebugSqlFilterTest.java   Source Code and License Vote up 4 votes
public void assertFile(final String expectedFilePath, final String actualFilePath) throws IOException {
	String expected = new String(Files.readAllBytes(Paths.get(expectedFilePath)), StandardCharsets.UTF_8);
	String actual = new String(Files.readAllBytes(Paths.get(actualFilePath)), StandardCharsets.UTF_8);

	assertEquals(expected, actual);
}
 
Example 20
Project: ServerBrowser   File: Encoding.java   Source Code and License Vote up 3 votes
/**
 * Tries to decode a given byte array using the given charset. As a fallback
 * {@link StandardCharsets#UTF_8} will be used.
 *
 * @param toDecode
 *            the byte array to decode
 * @param charset
 *            the charset to be used for decoding
 * @return the decoded string
 */
public static String decodeUsingCharsetIfPossible(final byte[] toDecode, final String charset) {
	try {
		return new String(toDecode, charset);
	} catch (@SuppressWarnings("unused") final UnsupportedEncodingException exception) {// In case that the given encoding is invalid, we use UTF-8 as fallback
		return new String(toDecode, StandardCharsets.UTF_8);
	}
}