当前位置: 首页>>代码示例>>Java>>正文


Java Charsets类代码示例

本文整理汇总了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();
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:23,代码来源:EncryptionTestUtils.java

示例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();
}
 
开发者ID:dotwebstack,项目名称:dotwebstack-framework,代码行数:22,代码来源:FileConfigurationBackendTest.java

示例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);
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:29,代码来源:TestTimestampInterceptor.java

示例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);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:22,代码来源:TestTableMapping.java

示例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"));
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:22,代码来源:TestTaildirEventReader.java

示例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);
}
 
开发者ID:salesforce,项目名称:kafka-junit,代码行数:29,代码来源:KafkaTestUtils.java

示例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);
}
 
开发者ID:eclipse,项目名称:n4js,代码行数:21,代码来源:EclipseBasedProjectModelSetup.java

示例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_;
}
 
开发者ID:F1r3w477,项目名称:CustomWorldGen,代码行数:22,代码来源:ModelBakery.java

示例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());
                    }
                  })));
}
 
开发者ID:isi-nlp,项目名称:tac-kbp-eal,代码行数:17,代码来源:PerDocResultWriter.java

示例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");
}
 
开发者ID:jomof,项目名称:cmakeify,代码行数:26,代码来源:TestCmakeify.java

示例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);
}
 
开发者ID:vrapio,项目名称:vrap,代码行数:22,代码来源:BaseUriReplacer.java

示例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);
    }


}
 
开发者ID:skhalifa,项目名称:QDrill,代码行数:19,代码来源:TestDistributedFragmentRun.java

示例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());
}
 
开发者ID:LAW-Unimi,项目名称:BUbiNG,代码行数:24,代码来源:VisitStateSetTest.java

示例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);
    }
 
开发者ID:uavorg,项目名称:uavstack,代码行数:18,代码来源:TailFile.java

示例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);
    }
}
 
开发者ID:MineboxOS,项目名称:tools,代码行数:24,代码来源:FileUtil.java


注:本文中的com.google.common.base.Charsets类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。