本文整理汇总了Java中com.google.common.base.Charsets类的典型用法代码示例。如果您正苦于以下问题:Java Charsets类的具体用法?Java Charsets怎么用?Java Charsets使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Charsets类属于com.google.common.base包,在下文中一共展示了Charsets类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createKeyStore
import com.google.common.base.Charsets; //导入依赖的package包/类
public static void createKeyStore(File keyStoreFile, File keyStorePasswordFile,
Map<String, File> keyAliasPassword) throws Exception {
KeyStore ks = KeyStore.getInstance("jceks");
ks.load(null);
List<String> keysWithSeperatePasswords = Lists.newArrayList();
for (String alias : keyAliasPassword.keySet()) {
Key key = newKey();
char[] password = null;
File passwordFile = keyAliasPassword.get(alias);
if (passwordFile == null) {
password = Files.toString(keyStorePasswordFile, Charsets.UTF_8).toCharArray();
} else {
keysWithSeperatePasswords.add(alias);
password = Files.toString(passwordFile, Charsets.UTF_8).toCharArray();
}
ks.setKeyEntry(alias, key, password, null);
}
char[] keyStorePassword = Files.toString(keyStorePasswordFile, Charsets.UTF_8).toCharArray();
FileOutputStream outputStream = new FileOutputStream(keyStoreFile);
ks.store(outputStream, keyStorePassword);
outputStream.close();
}
示例2: loadPrefixes_ThrowConfigurationException_FoundUnknownPrefix
import com.google.common.base.Charsets; //导入依赖的package包/类
@Test
public void loadPrefixes_ThrowConfigurationException_FoundUnknownPrefix() throws Exception {
// Arrange
Resource resource = mock(Resource.class);
when(resource.getInputStream()).thenReturn(
new ByteArrayInputStream(new String("@prefix dbeerpedia: <http://dbeerpedia.org#> .\n"
+ "@prefix elmo: <http://dotwebstack.org/def/elmo#> .\n"
+ "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
+ "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n"
+ "this is not a valid prefix").getBytes(Charsets.UTF_8)));
when(resource.getFilename()).thenReturn("_prefixes.trig");
when(((ResourcePatternResolver) resourceLoader).getResources(any())).thenReturn(
new Resource[] {resource});
// Assert
thrown.expect(ConfigurationException.class);
thrown.expectMessage("Found unknown prefix format <this is not a valid prefix> at line <5>");
// Act
backend.loadResources();
}
示例3: testPreserve
import com.google.common.base.Charsets; //导入依赖的package包/类
/**
* Ensure timestamp is NOT overwritten when preserveExistingTimestamp == true
*/
@Test
public void testPreserve() throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
Context ctx = new Context();
ctx.put("preserveExisting", "true");
InterceptorBuilderFactory factory = new InterceptorBuilderFactory();
Interceptor.Builder builder = InterceptorBuilderFactory.newInstance(
InterceptorType.TIMESTAMP.toString());
builder.configure(ctx);
Interceptor interceptor = builder.build();
long originalTs = 1L;
Event event = EventBuilder.withBody("test event", Charsets.UTF_8);
event.getHeaders().put(Constants.TIMESTAMP, Long.toString(originalTs));
Assert.assertEquals(Long.toString(originalTs),
event.getHeaders().get(Constants.TIMESTAMP));
Long now = System.currentTimeMillis();
event = interceptor.intercept(event);
String timestampStr = event.getHeaders().get(Constants.TIMESTAMP);
Assert.assertNotNull(timestampStr);
Assert.assertTrue(Long.parseLong(timestampStr) == originalTs);
}
示例4: testBadFile
import com.google.common.base.Charsets; //导入依赖的package包/类
@Test(timeout=60000)
public void testBadFile() throws IOException {
File mapFile = File.createTempFile(getClass().getSimpleName() +
".testBadFile", ".txt");
Files.write("bad contents", mapFile, Charsets.UTF_8);
mapFile.deleteOnExit();
TableMapping mapping = new TableMapping();
Configuration conf = new Configuration();
conf.set(NET_TOPOLOGY_TABLE_MAPPING_FILE_KEY, mapFile.getCanonicalPath());
mapping.setConf(conf);
List<String> names = new ArrayList<String>();
names.add(hostName1);
names.add(hostName2);
List<String> result = mapping.resolve(names);
assertEquals(names.size(), result.size());
assertEquals(result.get(0), NetworkTopology.DEFAULT_RACK);
assertEquals(result.get(1), NetworkTopology.DEFAULT_RACK);
}
示例5: testNewLineBoundaries
import com.google.common.base.Charsets; //导入依赖的package包/类
@Test
public void testNewLineBoundaries() throws IOException {
File f1 = new File(tmpDir, "file1");
Files.write("file1line1\nfile1line2\rfile1line2\nfile1line3\r\nfile1line4\n",
f1, Charsets.UTF_8);
ReliableTaildirEventReader reader = getReader();
List<String> out = Lists.newArrayList();
for (TailFile tf : reader.getTailFiles().values()) {
out.addAll(bodiesAsStrings(reader.readEvents(tf, 5)));
reader.commit();
}
assertEquals(4, out.size());
//Should treat \n as line boundary
assertTrue(out.contains("file1line1"));
//Should not treat \r as line boundary
assertTrue(out.contains("file1line2\rfile1line2"));
//Should treat \r\n as line boundary
assertTrue(out.contains("file1line3"));
assertTrue(out.contains("file1line4"));
}
示例6: produceRecords
import com.google.common.base.Charsets; //导入依赖的package包/类
/**
* Produce randomly generated records into the defined kafka namespace.
*
* @param numberOfRecords how many records to produce
* @param topicName the namespace name to produce into.
* @param partitionId the partition to produce into.
* @return List of ProducedKafkaRecords.
*/
public List<ProducedKafkaRecord<byte[], byte[]>> produceRecords(
final int numberOfRecords,
final String topicName,
final int partitionId
) {
Map<byte[], byte[]> keysAndValues = new HashMap<>();
// Generate random & unique data
for (int x = 0; x < numberOfRecords; x++) {
// Construct key and value
long timeStamp = Clock.systemUTC().millis();
String key = "key" + timeStamp;
String value = "value" + timeStamp;
// Add to map
keysAndValues.put(key.getBytes(Charsets.UTF_8), value.getBytes(Charsets.UTF_8));
}
return produceRecords(keysAndValues, topicName, partitionId);
}
示例7: createManifest
import com.google.common.base.Charsets; //导入依赖的package包/类
private void createManifest(String projectName, String string) throws CoreException, UnsupportedEncodingException {
IProject project = workspace.getProject(projectName);
IFile manifestFile = project.getFile(IN4JSProject.N4MF_MANIFEST);
@SuppressWarnings("resource")
StringInputStream content = new StringInputStream(string, Charsets.UTF_8.name());
manifestFile.create(content, false, null);
manifestFile.setCharset(Charsets.UTF_8.name(), null);
IFolder src = project.getFolder("src");
src.create(false, true, null);
IFolder sub = src.getFolder("sub");
sub.create(false, true, null);
IFolder leaf = sub.getFolder("leaf");
leaf.create(false, true, null);
src.getFile("A.js").create(new ByteArrayInputStream(new byte[0]), false, null);
src.getFile("B.js").create(new ByteArrayInputStream(new byte[0]), false, null);
sub.getFile("B.js").create(new ByteArrayInputStream(new byte[0]), false, null);
sub.getFile("C.js").create(new ByteArrayInputStream(new byte[0]), false, null);
leaf.getFile("D.js").create(new ByteArrayInputStream(new byte[0]), false, null);
}
示例8: loadModelBlockDefinition
import com.google.common.base.Charsets; //导入依赖的package包/类
private ModelBlockDefinition loadModelBlockDefinition(ResourceLocation location, IResource resource)
{
InputStream inputstream = null;
ModelBlockDefinition lvt_4_1_;
try
{
inputstream = resource.getInputStream();
lvt_4_1_ = ModelBlockDefinition.parseFromReader(new InputStreamReader(inputstream, Charsets.UTF_8));
}
catch (Exception exception)
{
throw new RuntimeException("Encountered an exception when loading model definition of \'" + location + "\' from: \'" + resource.getResourceLocation() + "\' in resourcepack: \'" + resource.getResourcePackName() + "\'", exception);
}
finally
{
IOUtils.closeQuietly(inputstream);
}
return lvt_4_1_;
}
示例9: writeArgPerDoc
import com.google.common.base.Charsets; //导入依赖的package包/类
static void writeArgPerDoc(final List<EALScorer2015Style.ArgResult> perDocResults,
final File outFile)
throws IOException {
Files.asCharSink(outFile, Charsets.UTF_8).write(
String.format("%40s\t%10s\n", "Document", "Arg") +
Joiner.on("\n").join(
FluentIterable.from(perDocResults)
.transform(new Function<EALScorer2015Style.ArgResult, String>() {
@Override
public String apply(final EALScorer2015Style.ArgResult input) {
return String.format("%40s\t%10.2f",
input.docID(),
100.0 * input.scaledArgumentScore());
}
})));
}
示例10: testSQLite
import com.google.common.base.Charsets; //导入依赖的package包/类
@Test
public void testSQLite() throws IOException {
File yaml = new File("test-files/testScript/cmakeify.yml");
yaml.getParentFile().mkdirs();
Files.write("targets: [android]\n" +
"buildTarget: sqlite\n" +
"android:\n" +
" ndk:\n" +
" runtimes: [c++, gnustl, stlport]\n" +
" platforms: [12, 21]\n" +
"example: |\n" +
" #include <sqlite3.h>\n" +
" void test() {\n" +
" sqlite3_initialize();\n" +
" }",
yaml, StandardCharsets.UTF_8);
main("-wf", yaml.getParent(),
"--host", "Linux",
"--group-id", "my-group-id",
"--artifact-id", "my-artifact-id",
"--target-version", "my-target-version");
File scriptFile = new File(".cmakeify/build.sh");
String script = Joiner.on("\n").join(Files.readLines(scriptFile, Charsets.UTF_8));
assertThat(script).contains("cmake-3.7.2-Linux-x86_64.tar.gz");
}
示例11: preprocess
import com.google.common.base.Charsets; //导入依赖的package包/类
public StringWriter preprocess(Context ctx, final Path filePath, final Api api) throws IOException {
final Integer port = ctx.getServerConfig().getPort();
final StringWriter stringWriter = new StringWriter();
final String baseUri = api.baseUri().value();
final List<SecurityScheme> oauthSchemes = api.securitySchemes().stream().filter(securityScheme -> securityScheme.type().equals("OAuth 2.0")).collect(Collectors.toList());
String content = new String(Files.readAllBytes(filePath), Charsets.UTF_8);
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
final JsonNode file = mapper.readValue(filePath.toFile(), JsonNode.class);
if (file.has("baseUri")) {
content = content.replaceAll(baseUri, "http://localhost:" + port.toString() + "/api");
}
if (!oauthSchemes.isEmpty()) {
for (SecurityScheme scheme : oauthSchemes) {
content = content.replaceAll(scheme.settings().accessTokenUri().value(), "http://localhost:" + port.toString() + "/auth/" + scheme.name());
}
}
return stringWriter.append(content);
}
示例12: oneBitOneExchangeTwoEntryRunLogical
import com.google.common.base.Charsets; //导入依赖的package包/类
@Test
public void oneBitOneExchangeTwoEntryRunLogical() throws Exception{
RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet();
try(Drillbit bit1 = new Drillbit(CONFIG, serviceSet); DrillClient client = new DrillClient(CONFIG, serviceSet.getCoordinator());){
bit1.run();
client.connect();
List<QueryDataBatch> results = client.runQuery(QueryType.LOGICAL, Files.toString(FileUtils.getResourceAsFile("/scan_screen_logical.json"), Charsets.UTF_8));
int count = 0;
for(QueryDataBatch b : results){
count += b.getHeader().getRowCount();
b.release();
}
assertEquals(100, count);
}
}
示例13: testResize
import com.google.common.base.Charsets; //导入依赖的package包/类
@Test
public void testResize() {
final VisitState[] visitState = new VisitState[2000];
for(int i = visitState.length; i-- != 0;) visitState[i] = new VisitState(null, Integer.toString(i).getBytes(Charsets.ISO_8859_1));
VisitStateSet s = new VisitStateSet();
for(int i = 2000; i-- != 0;) assertTrue(s.add(visitState[i]));
assertEquals(2000, s.size());
for(int i = 2000; i-- != 0;) assertFalse(s.add(new VisitState(null, Integer.toString(i).getBytes(Charsets.ISO_8859_1))));
for(int i = 1000; i-- != 0;) assertTrue(s.remove(visitState[i]));
for(int i = 1000; i-- != 0;) assertFalse(s.remove(visitState[i]));
for(int i = 1000; i-- != 0;) assertNull(s.get(Integer.toString(i).getBytes(Charsets.ISO_8859_1)));
for(int i = 2000; i-- != 1000;) assertSame(visitState[i], s.get(Integer.toString(i).getBytes(Charsets.ISO_8859_1)));
assertEquals(1000, s.size());
assertFalse(s.isEmpty());
s.clear();
assertEquals(0, s.size());
assertTrue(s.isEmpty());
s.clear();
assertEquals(0, s.size());
assertTrue(s.isEmpty());
}
示例14: readLine
import com.google.common.base.Charsets; //导入依赖的package包/类
private String readLine() throws IOException {
ByteArrayDataOutput out = ByteStreams.newDataOutput(300);
int i = 0;
int c;
while ((c = raf.read()) != -1) {
i++;
out.write((byte) c);
if (c == LINE_SEP.charAt(0)) {
break;
}
}
if (i == 0) {
return null;
}
return new String(out.toByteArray(), Charsets.UTF_8);
}
示例15: readLocalAuth
import com.google.common.base.Charsets; //导入依赖的package包/类
static String readLocalAuth(String filePath) {
final Path path = Paths.get(filePath);
try {
if (!Files.exists(path)) {
LOGGER.info("authFile not found, creating it");
final UUID uuid = UUID.randomUUID();
final Path temp = path.getParent().resolve(path.getFileName().toString() + ".temp");
createFileWithPermissions(temp);
final String written = uuid.toString();
Files.write(temp, written.getBytes(Charsets.UTF_8));
Files.move(temp, path, StandardCopyOption.ATOMIC_MOVE);
return written;
} else {
final List<String> lines = Files.readAllLines(path);
Preconditions.checkState(lines.size() == 1);
final String ret = lines.get(0);
final UUID ignored = UUID.fromString(ret);//check if this throws an exception, that might mean that
return ret;
}
} catch (IOException e) {
throw new RuntimeException("unable to read password file at " + filePath, e);
}
}